The Relationship Between Servlets and JSP

In the Java web development ecosystem, Servlets and JSP (JavaServer Pages) are the two cornerstones for building dynamic websites. They do not exist in isolation but work together through tight technical coupling to complete the full cycle from request-response to view rendering. Understanding their interdependencies and collaboration mechanisms is key to mastering modern Java Web architecture.
From a perspective of essential implementation, JSP is essentially a simplified version of a view component based on Servlet technology. When a browser requests a .jsp file, the web container (such as Tomcat) does not directly execute the JSP code; instead, it compiles and executes it by converting it into a corresponding Servlet. This conversion process occurs on the server side, where the generated Servlet class name typically follows specific naming conventions: removing the file extension and appending the JspServlet suffix.

The core advantage of JSP lies in separating business logic (Controller) from page presentation (View). Developers can freely use markup languages such as HTML, XML, or JavaScript within a .jsp file to construct page structures without embedding large amounts of Java code into the HTML itself. This "what you see is what you get" development mode significantly improves coding efficiency for pages. However, regardless of how concise a JSP file may be written at the surface level, it fundamentally relies on the Servlet API to handle HTTP request lifecycles, parameter retrieval, and output stream management.

Bidirectional Collaboration: Servlet as Controller Driving Views

In the MVC (Model-View-Controller) design pattern, Servlets typically play the role of the controller, responsible for receiving user requests, invoking backend services, and rendering JSP pages. Through the request.getRequestDispatcher() method, a Servlet forwards its processing results to a designated JSP page; this process is referred to as "including" or "forwarding."

When a Servlet completes execution and hands over the response object (Response) to the JSP, the JSP effectively acts as a passive view component. It receives the data model passed by the Servlet and utilizes Java's built-in EL (Expression Language) expressions or the JSTL (JavaServer Standard Tags Library) tag library to display data. If a JSP page requires executing additional business logic (such as database queries), such logic must still be encapsulated within an internal Servlet rather than written directly in scriptlets within the JSP, adhering to web container security specifications.

Code Example: Mapping from JSP to Servlet

To better understand their relationship intuitively, here is a simplified comparison example. Assume we need to implement a user information display feature:

JSP Page (user.jsp):

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>User Information</title></head>
<body>
    <h2>Welcome, ${userName}</h2>
    <p>Email: ${userEmail}</p>
    <!-- Note: Complex logic cannot be written directly here -->
</body>
</html>

Corresponding Servlet (UserServlet.java):

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        // 1. Simulate fetching user data
        String userName = "Zhang San";
        String userEmail = "zhangsan@example.com";

        // 2. Store data in the request object for use by JSP
        request.setAttribute("userName", userName);
        request.setAttribute("userEmail", userEmail);

        // 3. Forward to the JSP page for rendering
        try {
            response.sendRedirect(request.getContextPath() + "/user.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Although Servlets form the underlying foundation of JSP, in practical engineering development, over-reliance on JSP scriptlets often leads to difficult-to-maintain code. Modern Java web development favors using pure HTML combined with powerful template engines (such as Thymeleaf or Freemarker), or simply stripping business logic out into independent Servlet/Controller layers.

JSP technology itself is also evolving continuously. The latest JSP specifications are gradually phasing out the mandatory use of <% %> script tags, instead recommending EL expressions and JSTL for data binding and logical judgment processing. This design trend aims to make JSP act more like a pure view layer component while pushing complex Java code back into Servlet containers or Spring Boot Controllers for handling.

In summary, the relationship between Servlets and JSP is akin to that of an "engine" and a "body." Servlets provide a powerful runtime environment and business processing capabilities, while JSP builds upon this foundation offering convenient language mechanisms to rapidly construct user interfaces. Mastering this relationship helps developers leverage traditional advantages flexibly while meeting modern web development requirements.