Servlets · Lesson 1
Introduction to Servlets
What are Servlets?
A servlet is a Java program that extends the capabilities of a web server, handling HTTP requests and generating responses. Unlike static HTML files, servlets execute on the server side and generate dynamic content based on the request. Servlets are the foundation of Java web development — they run inside a servlet container (like Apache Tomcat) that manages their lifecycle and handles networking. Before modern frameworks like Spring, servlets were the primary way to build web applications in Java.
How Servlets Work in the HTTP Request-Response Cycle
When a browser requests a URL, the servlet container intercepts it and routes it to the appropriate servlet. The servlet processes the request (query parameters, form data, headers), executes business logic, and returns an HTTP response (HTML, JSON, etc.). The container handles low-level details like socket communication, leaving you to focus on application logic. This server-side execution allows you to access databases, perform calculations, and generate personalized content securely.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html;charset=UTF-8");
// Get a PrintWriter to send response
PrintWriter out = response.getWriter();
// Generate HTML response
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Welcome to Java Servlets!</h1>");
out.println("</body>");
out.println("</html>");
}
}
Handling GET and POST Requests
Servlets handle different HTTP methods through methods like doGet() and doPost(). GET requests retrieve data (query parameters in the URL), while POST requests submit data (in the request body). Your servlet examines the request method and handles each appropriately. Many servlets handle both by delegating to a shared helper method.
public class UserFormServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display form for user input
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<form method='POST'>");
out.println("Name: <input type='text' name='username'><br>");
out.println("Email: <input type='email' name='email'><br>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Process form submission
String username = request.getParameter("username");
String email = request.getParameter("email");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Thank you, " + username + "!</h1>");
out.println("<p>Your email is: " + email + "</p>");
out.println("</body></html>");
}
}
Request and Response Objects
The HttpServletRequest provides access to all information about the incoming request: parameters, headers, session data, cookies. The HttpServletResponse lets you build the reply: set status codes, add headers, write output. Understanding these objects is crucial for servlet development.
public class RequestResponseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Access request information
String queryParam = request.getParameter("message");
String remoteAddr = request.getRemoteAddr();
String userAgent = request.getHeader("User-Agent");
String sessionId = request.getSession().getId();
// Set response properties
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html;charset=UTF-8");
response.addHeader("Custom-Header", "CustomValue");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<p>Query Parameter: " + queryParam + "</p>");
out.println("<p>Client IP: " + remoteAddr + "</p>");
out.println("<p>User Agent: " + userAgent + "</p>");
out.println("<p>Session ID: " + sessionId + "</p>");
out.println("</body></html>");
}
}
URL Mapping and Routing Requests
Servlets are mapped to URL patterns through web.xml or annotations. A URL pattern like /hello routes to HelloServlet. Modern frameworks use annotations for cleaner mapping. The servlet container uses these mappings to route incoming requests to the correct servlet handler.
import javax.servlet.annotation.WebServlet;
// Using annotation (modern approach)
@WebServlet(urlPatterns = {"/user", "/profile"})
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>User Profile Page</h1>");
}
}
// Traditional web.xml mapping (older approach):
// <servlet>
// <servlet-name>UserServlet</servlet-name>
// <servlet-class>com.example.UserServlet</servlet-class>
// </servlet>
// <servlet-mapping>
// <servlet-name>UserServlet</servlet-name>
// <url-pattern>/user</url-pattern>
// </servlet-mapping>
| Aspect | Description |
|---|---|
| Container | Tomcat, JettyManager runs servlets and handles HTTP |
| doGet() | Handles GET requests (retrieve data) |
| doPost() | Handles POST requests (submit data) |
| Request | Provides access to query params, headers, cookies, session |
| Response | Allows setting headers, status, writing output |
| URL Mapping | Associates servlet to URL patterns via annotation or web.xml |
Common Mistake: Mixing presentation logic with business logic in servlets. Servlets become hard to maintain when they contain SQL queries, HTML generation, and validation all tangled together. Use the Model-View-Controller (MVC) pattern: servlets as controllers, separate classes for business logic (model), and JSP or template engines for presentation (view).
Best Practices for Servlet Development
- Use annotations (
@WebServlet) instead of web.xml for cleaner code - Keep servlets thin: delegate to service classes for business logic
- Always set Content-Type on responses to specify format (HTML, JSON, etc.)
- Validate all input from requests before using it
- Use try-catch for IOException handling and proper error responses
- Consider modern frameworks like Spring MVC or Spring Boot for new projects
- Implement proper security: prevent SQL injection, XSS, CSRF attacks
- Use sessions carefully: they consume server resources; use judiciously
Real-World Example: E-Commerce Product Listing Servlet
A servlet at /products receives GET requests with optional category and page query parameters. It queries the database for matching products, formats them as HTML, and returns the response. A POST endpoint /products/add accepts new product details from a form, validates input, saves to the database, and redirects to the product list. By using request objects for parameters and response objects for output, the servlet cleanly separates request handling from business logic.
Quiz Check