杰瑞科技汇

Java ServletRequest如何获取请求参数与属性?

Of course! Let's dive deep into the ServletRequest interface in Java. This is a fundamental concept in Java web development, especially when working with servlets.

Java ServletRequest如何获取请求参数与属性?-图1
(图片来源网络,侵删)

What is ServletRequest?

ServletRequest is an interface in the javax.servlet package that defines an object to provide client request information to a servlet. When a client (usually a web browser) makes a request to a web server, the server creates a ServletRequest object. This object acts as a wrapper or a data holder for all the information about that specific request.

A servlet (typically the service() or doGet()/doPost() method) receives this ServletRequest object as its first parameter, along with a ServletResponse object.

// Inside a HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
    // 'request' is the ServletRequest object (specifically, an HttpServletRequest)
    // 'response' is the ServletResponse object (specifically, an HttpServletResponse)
}

Note: In modern servlets, you almost always work with HttpServletRequest, which is a sub-interface of ServletRequest. It adds HTTP-specific functionality. We'll focus on HttpServletRequest for most of this explanation.


Key Information You Can Get from ServletRequest

The ServletRequest object gives you access to a wealth of information about the incoming request. Here are the most common things you'll use it for:

Java ServletRequest如何获取请求参数与属性?-图2
(图片来源网络,侵删)

A. Request Parameters (getParameter)

This is one of the most common uses. Parameters are sent from the client, typically from an HTML form.

  • How it works: You get the value of a form field by its name attribute.
  • Example: A form with <input type="text" name="username"> will send a parameter named username.
  • Method: String getParameter(String name)
  • Handling Multiple Values: If a parameter can have multiple values (e.g., checkboxes with the same name), use String[] getParameterValues(String name).

Example: login.html

<form action="LoginServlet" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    Hobbies:
    <input type="checkbox" name="hobbies" value="reading"> Reading
    <input type="checkbox" name="hobbies" value="sports"> Sports<br>
    <input type="submit" value="Login">
</form>

Example: LoginServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    // Get single-valued parameters
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    // Get multi-valued parameter
    String[] hobbies = request.getParameterValues("hobbies");
    System.out.println("Username: " + username);
    System.out.println("Password: " + password); // Note: Never log passwords!
    if (hobbies != null) {
        System.out.println("Hobbies:");
        for (String hobby : hobbies) {
            System.out.println("- " + hobby);
        }
    }
}

B. Request Headers (getHeader)

HTTP headers contain metadata about the request, such as the client's browser type, accepted content types, or authentication information.

Java ServletRequest如何获取请求参数与属性?-图3
(图片来源网络,侵删)
  • Method: String getHeader(String name)
  • Common Headers: User-Agent, Accept, Accept-Language, Cookie, Referer, Authorization.

Example:

// Get the user's browser information
String userAgent = request.getHeader("User-Agent");
System.out.println("Browser: " + userAgent);
// Get the list of accepted languages by the client
String acceptLanguage = request.getHeader("Accept-Language");
System.out.println("Preferred Language: " + acceptLanguage);

C. Request Attributes (setAttribute / getAttribute)

Attributes are objects that you can store in the request scope. They are used to pass data between different components of the application that handle the same request (e.g., from a servlet to a JavaServer Page - JSP).

  • Setting an attribute: void setAttribute(String name, Object o)
  • Getting an attribute: Object getAttribute(String name)
  • Removing an attribute: void removeAttribute(String name)

Example:

// In a servlet
User user = new User("John Doe");
request.setAttribute("loggedInUser", user);
// Forward the request to a JSP page
request.getRequestDispatcher("/profile.jsp").forward(request, response);
// In profile.jsp
// You can access the attribute like this: ${loggedInUser.name}

D. Request URI vs. URL

It's crucial to understand the difference between these two.

  • getRequestURI(): Returns the part of the URL from the protocol name up to the query string, but without the domain name.
    • Example: For http://example.com/contextPath/servletPath?id=123, this returns /contextPath/servletPath.
  • getRequestURL(): Reconstructs the full URL the client used to make the request.
    • Example: For the same URL, this returns http://example.com/contextPath/servletPath.
  • getQueryString(): Returns the query string (the part after the ).
    • Example: For .../servletPath?id=123, this returns id=123.

Example:

String uri = request.getRequestURI(); // e.g., /myApp/login
String url = request.getRequestURL(); // e.g., http://localhost:8080/myApp/login
String query = request.getQueryString(); // e.g., username=foo&password=bar
System.out.println("URI: " + uri);
System.out.println("URL: " + url);
System.out.println("Query String: " + query);

E. Other Useful Information

  • Method Type: String getMethod() -> Returns "GET", "POST", "PUT", "DELETE", etc.
  • Protocol: String getProtocol() -> Returns "HTTP/1.1" or "HTTP/1.0".
  • Server Name: String getServerName() -> Returns the host name of the server.
  • Server Port: int getServerPort() -> Returns the port number the server is listening on.
  • Client Information:
    • String getRemoteAddr(): The IP address of the client.
    • String getRemoteHost(): The fully qualified name of the client.
  • Character Encoding: String getCharacterEncoding() / void setCharacterEncoding(String env): Crucial for handling non-English text correctly.

Request Scope and Lifecycle

The scope of a ServletRequest object is single-request. This means:

  1. A new ServletRequest object is created for every single request that comes to the server.
  2. It is destroyed after the server has finished processing that request and generated the response.
  3. Attributes set in the request are only visible to components that handle that same request (e.g., when you use RequestDispatcher.forward()).

This is different from HttpSession scope, which lasts for the duration of a user's session (across multiple requests).


Code Example: A Complete Servlet

Here is a simple servlet that demonstrates many of the concepts above.

InfoServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/InfoServlet")
public class InfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // Set content type and writer
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        // --- 1. Display Request Parameters ---
        out.println("<h1>Request Parameters</h1>");
        String name = request.getParameter("name");
        if (name != null && !name.isEmpty()) {
            out.println("<p>Hello, " + name + "!</p>");
        } else {
            out.println("<p>No 'name' parameter provided. Try adding ?name=YourName to the URL.</p>");
        }
        // --- 2. Display Request Headers ---
        out.println("<h1>Request Headers</h1>");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            out.println("<p><b>" + headerName + ":</b> " + request.getHeader(headerName) + "</p>");
        }
        // --- 3. Display Request URI, URL, etc. ---
        out.println("<h1>Request Information</h1>");
        out.println("<p><b>Request URI:</b> " + request.getRequestURI() + "</p>");
        out.println("<p><b>Request URL:</b> " + request.getRequestURL() + "</p>");
        out.println("<p><b>Query String:</b> " + request.getQueryString() + "</p>");
        out.println("<p><b>Method:</b>
分享:
扫描分享到社交APP
上一篇
下一篇