Search code examples
intellij-ideaservletscode-templates

Cant create a new Servlet in IntelliJ Ultimate Edition 2023.2


Similar to this question, I cant create a Servlet file with the 'new' context menu New -> Servlet. However, as shown in the screenshot, src/main/java is alreay marked as a source root directory, so its a different problem than the answers suggest.Manually creating a Servlet from a javaclass works, however it would be nice to have the boilerplate code created automatically.

Im following this text tutorial from JetBrains

Screenshot showing the missing of 'new servlet'

Screenshot showing the source root activation

I checked if the Sources root is set correctly and if the default servlet works correctly, which it does.


Solution

  • Newest IntelliJ IDEA versions does not provide the default templates for creating servlets, listeners, and filters. However, you can define these templates yourself.

    Paste the following code as the template body:

    #if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
    #parse("File Header.java")
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "${Class_Name}", value = "/${Class_Name}")
    public class ${Class_Name} extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }
    

    under Settings/Preferences | Editor | File and Code Templates

    See https://www.jetbrains.com/help/idea/creating-and-configuring-web-application-elements.html#elements-templates for more information