Creating a New Project
Launch IntelliJ IDEA and initiate a new project by providing the necessary details, then proceed with creation.
Configuring Web Support
Once the project is created:
- Add web framework support to the project
- If the option is missing, use the action search feature: Select the project, press Shift twice rapidly, type "Add Framework Support" in the actions dialog, and execute
In the configuration dialog, select JavaEE version 6 or higher (enables @WebServlet annotation support for reduced web.xml configuration) and Web version 3.0 or above for annotation-based development.
Tomcat Integration
Two approaches exist for Tomcat setup:
Select Tomcat Server Local from the available options. Configure browser preferences and modify the default port (8080) if needed, selecting from the valid range of 0-65535.
Deploy the application via the Deployment tab, and include necessary Tomcat JAR files for access to required classes.
Verify successful integration within the project structure.
Servlet Implementation
Create a class implementing the Servlet interface with overridden methods:
import javax.servlet.*;
import java.io.IOException;
public class DemoServlet implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet initialized");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
System.out.println("Service method invoked");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("Servlet destroyed");
}
}
URL Mapping Configuratino
Configure virtual paths through either web.xml or annotations:
web.xml approach:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>demoServlet</servlet-name>
<servlet-class>com.example.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demoServlet</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
Annotation approach:
@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
// Implementation remains the same
}
Either method works effectively (note: annotation support requires Web 3.0+).
Testing the Deployment
Start the Tomcat server and verify successful launch. Access the configured endpoint by appending the mapped URL pattern to the base path. Monitor console output during startup and shutdown sequences to confirm proper lifecycle management.