杰瑞科技汇

JSP与Servlet如何协同工作?

Of course! Let's break down JSP and Java Servlets, their relationship, and how they work together. This is a fundamental concept in classic Java web development.

JSP与Servlet如何协同工作?-图1
(图片来源网络,侵删)

The Big Picture: A Classic Web Application Architecture

Think of a web application as a restaurant:

  • Java Servlet: The Chef in the kitchen. It's the powerful, back-end expert that handles all the complex logic: fetching ingredients (data from a database), performing calculations, and making decisions. It can't directly serve the final meal to the customer.
  • JSP (JavaServer Pages): The Waiter / Presentation Staff. It takes the prepared meal (the data) from the Chef and presents it beautifully on a plate (the HTML page) for the customer to see. It's focused on the "how it looks" part.

In modern web development, this role is often split between a Backend API (the Chef) and a Frontend Framework like React or Vue (the Waiter). But understanding the Servlet/JSP model is crucial because it's the foundation of Java web development and many concepts still apply.


Java Servlets: The Controller and Backend Engine

A Servlet is a Java class that runs on a web server (like Apache Tomcat) and handles requests from web clients (usually browsers).

Key Characteristics of Servlets:

  • Java-Based: They are written in Java.
  • Request-Response Model: They handle HttpServletRequest (the request from the browser) and HttpServletResponse (the response sent back to the browser).
  • Lifecycle: Managed by the web server container (e.g., Tomcat).
    1. Loading and Instantiation: The container loads the servlet class and creates an instance of it.
    2. Initialization: The container calls the init() method once. This is used for one-time setup, like creating a database connection pool.
    3. Request Handling: For every client request, the container calls the service() method, which typically calls doGet(), doPost(), etc.
    4. Destruction: When the application is shut down, the container calls the destroy() method to clean up resources.
  • No HTML: A servlet's primary job is not to generate HTML. It's a Java program. Generating HTML directly in a servlet is cumbersome and considered bad practice.

Example: A Simple Servlet

This servlet responds to a GET request with plain text.

JSP与Servlet如何协同工作?-图2
(图片来源网络,侵删)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 1. Extend HttpServlet
public class SimpleServlet extends HttpServlet {
    // 2. Override the doGet method to handle GET requests
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 3. Set the content type of the response
        response.setContentType("text/html");
        // 4. Get a PrintWriter to write the response
        PrintWriter out = response.getWriter();
        // 5. Write HTML content to the response
        out.println("<html>");
        out.println("<head><title>Hello Servlet</title></head>");
        out.println("<body>");
        out.println("<h1>Hello from a Java Servlet!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Problem with the above: Mixing Java logic with HTML is messy, hard to maintain, and not what developers want to do.


JSP (JavaServer Pages): The View/Presentation Layer

A JSP is a text file that contains two types of content:

  1. Static Data: HTML, CSS, XML, JavaScript.
  2. Dynamic Content: Special JSP elements that are executed by the server to generate the final page.

Key JSP Elements:

  • Scriptlets: Java code embedded directly in the page. (Discouraged for complex logic)
    <%
        // Java code here
        String user = "John Doe";
    %>
  • Expressions: Output a value directly to the HTML.
    Hello, <%= user %>!
  • Declarations: Declare instance variables or methods for the JSP page.
    <%!
        private int hitCount = 0;
    %>
  • Actions: Special XML-like tags that control the behavior of the JSP engine.
    • <jsp:useBean>: Instantiates or locates a JavaBean.
    • <jsp:getProperty>: Gets a property from a JavaBean.
    • <jsp:setProperty>: Sets a property in a JavaBean.
    • <jsp:include>: Includes the output of another resource at request time.
    • <jsp:forward>: Forwards the request to another resource.

Example: A Simple JSP

This JSP displays a welcome message.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">Welcome Page</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
    <p>Today's date is: <%= new java.util.Date() %></p>
</body>
</html>

How They Work Together: The MVC Pattern

The real power comes from combining Servlets and JSPs using the Model-View-Controller (MVC) design pattern.

JSP与Servlet如何协同工作?-图3
(图片来源网络,侵删)
  • Model: Your data and business logic (e.g., Java classes, database).
  • View: The presentation layer (JSP). It displays the data from the Model.
  • Controller: The entry point that handles user input and orchestrates the flow (Servlet).

The Workflow:

  1. Request: The user clicks a link or submits a form. The request goes to a Servlet (Controller).
  2. Process: The servlet receives the request.
    • It may read parameters (e.g., username, password).
    • It performs business logic (e.g., authenticates the user with the Model).
    • It fetches or creates data (e.g., gets a list of products from the database).
  3. Store Data: The servlet stores this data in a request-scoped object called request.setAttribute("key", value).
  4. Forward: The servlet forwards the request to a JSP page (View) using RequestDispatcher.forward().
  5. Display: The JSP page receives the request, retrieves the data using the key (request.getAttribute("key")), and displays it in a nicely formatted HTML page.
  6. Response: The final HTML is sent back to the user's browser.

Example: Servlet + JSP Interaction

The Servlet (Controller): LoginServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. Get user input from the request
        String username = request.getParameter("username");
        // 2. Perform business logic (simple check)
        if ("admin".equals(username)) {
            // 3. Store data in the request scope
            request.setAttribute("user", username);
            request.setAttribute("welcomeMessage", "Welcome, Administrator!");
            // 4. Forward to the JSP (View)
            RequestDispatcher dispatcher = request.getRequestDispatcher("/welcome.jsp");
            dispatcher.forward(request, response);
        } else {
            // If login fails, redirect back to login page with an error
            request.setAttribute("error", "Invalid username. Try 'admin'.");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
            dispatcher.forward(request, response);
        }
    }
}

The JSP (View): welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>Welcome</title>
</head>
<body>
    <h1>Welcome Page</h1>
    <!-- 
      Retrieve the data set by the Servlet.
      This is the "View" part of MVC.
    -->
    <p><strong>User:</strong> ${user}</p>
    <p><strong>Message:</strong> ${welcomeMessage}</p>
    <!-- Note: Using JSTL (JSP Standard Tag Library) is even better -->
    <%-- <p><strong>User:</strong> <c:out value="${user}"/></p> --%>
</body>
</html>

Modern Context: Is This Still Used?

  • JSP: Its use in new projects has drastically declined. Modern frameworks like Spring Boot and JSF (JavaServer Faces) have largely replaced it. Frontend frameworks like React, Angular, and Vue are now the dominant "View" technology, communicating with the backend via REST APIs.
  • Servlets: The concept is more relevant than ever. In a Spring Boot application, for example, you don't usually write HttpServlet classes by hand. Instead, you write "controller" methods annotated with @GetMapping or @PostMapping. Under the hood, the Spring framework is using a Servlet (the DispatcherServlet) to route all requests to your annotated controller methods. So, the core Servlet API is still the engine driving Java web applications.

Summary Table

Feature Servlet JSP (JavaServer Pages)
Primary Role Controller, Backend Logic View, Presentation
Content Java Code HTML, JSP Tags, Scriptlets
Execution Compiled to a Java class. Translated into a Servlet, then compiled.
Output Typically forwards to another resource or writes raw data. Generates HTML, XML, etc.
Best For Handling requests, business logic, routing. Displaying dynamic data in a formatted way.
Analogy The Chef (kitchen, logic) The Waiter (presentation, customer-facing)
Modern Usage Still relevant as the foundation (e.g., Spring's DispatcherServlet). Largely superseded by modern frontend frameworks.
分享:
扫描分享到社交APP
上一篇
下一篇