Servlet technology provides a specification for building web applications in Java. As part of Java EE standards, it enables server-side processing of client requests. The API documentation for Servlet is available in the JavaEE package structure, separate from standard JDK documentation.
Key Characteristics
- Server-side Java components that handle client requests
- Requires implementation of the Servlet interface or extension of helper classes
- Processes requests through the service() method
- Supports configuration through deployment descriptors
Basic Implementation Example
public class BasicServlet extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Request handling logic
}
}
Servlet Lifecycle and Thread Safety
The Servlet lifecycle consists of three phases:
- Initialization: When the container loads the Servlet
- Service: During request processing
- Destruction: When the container unloads the Servlet
Thread safety considerations:
public class CounterServlet extends HttpServlet {
private int count; // Potential thread safety issue
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
count++;
// Critical section needs synchronization
}
}
Configuration Methods
Servlets can be configured through:
- Exact path matching (/example)
- Directory pattern matching (/path/*)
- Extension matching (*.action)
Multiple Mapping Example
<servlet-mapping>
<servlet-name>MultiServlet</servlet-name>
<url-pattern>/primary</url-pattern>
<url-pattern>/secondary</url-pattern>
</servlet-mapping>
Servlet Context and Configuration
The ServletContext provides:
- Application-wide initialization parameters
- Resource access methods
- Attriubte sharing across Servlets
// Accessing context parameters
String dbUrl = getServletContext().getInitParameter("databaseUrl");
Annotation-Based Development
Servlet 3.0+ supports annotation configuration:
@WebServlet(
name = "AnnotatedServlet",
urlPatterns = {"/annotated"},
initParams = {
@WebInitParam(name = "config", value = "value")
}
)
public class AnnotatedServlet extends HttpServlet {
// Servlet implementation
}
Practical Application Example
Implementing a student management system:
@WebServlet("/students/add")
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String name = req.getParameter("studentName");
// Process and store student data
}
}