| Lesson 10 | Servlets and Web Page Generation â Conclusion |
| Objective | Summarize the techniques and best practices for generating dynamic web pages using Jakarta Servlets. |
Jakarta Servlets are at the core of server-side web development in Java. They handle client requests, process data, and generate responsesâoften in the form of HTML or JSON. By now, you should understand not just how servlets create pages, but also how they fit within the broader Jakarta EE ecosystem that includes JSPs, filters, and template engines.
After completing this module, you should be able to:
HttpServletRequest.
While the classic approach involved printing raw HTML through a PrintWriter, modern Jakarta Servlet applications use a layered and modular approach to generating web pages. Here are the main strategies:
response.getWriter() to send HTML directly to the client. Useful for simple test pages or API status responses.ServletOutputStream for serving files, images, or reports (PDF, Excel, etc.).RequestDispatcher for modular response building.response.sendRedirect() to guide the client to a different URL or servlet after processing.
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
import java.time.LocalDateTime;
@WebServlet("/greet")
public class GreetingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html><head><title>Greeting</title></head>");
out.println("<body>");
out.println("<h1>Hello, " + req.getParameter("name") + "!" + "</h1>");
out.println("<p>Current time: " + LocalDateTime.now() + "</p>");
out.println("</body></html>");
}
}
}
While this example demonstrates direct HTML output, best practices encourage separating logic and presentation. You might forward the data to a JSP for rendering, or use a templating framework for more complex views.
<, >).The servlet lifecycle ensures that your dynamic pages are generated efficiently:
GET or POST).HttpServletRequest and HttpServletResponse objects.Servlets remain foundational in Jakarta EE web development, providing direct access to HTTP mechanics and full control over the response pipeline. However, for maintainability, modern applications typically combine servlets with JSPs, template engines, or RESTful frameworks like JAX-RS to separate logic from presentation. Understanding servlet-based page generation is the first step toward mastering Jakarta EE web architecture.
The next module explores database access using servlets, demonstrating how to connect to relational databases with JDBC and manage query results safely and efficiently.