Location>code7788 >text

Java Web request, response, relocation and forwarding details

Popularity:927 ℃/2024-08-18 22:05:27

Request and Response Responses

Web server receives the client's http request, it will be for each http request to create should represent the request of therequestobject, and aresponseObject.requestis to get the data submitted by the client, and response is to provide the data to the client.

request

  • anrequestThe request consists of the following data
    • Request method.Indicates the action to be performed by the client, e.g.GET,POST,PUT,DELETEwait a minute!
    • Request URL.The client wants to access the resource address
    • Request header.Contains metadata about the request such asContent-Type ,User-Agent ,Accept-Languge
    • Request body.This includes data sent to the server, such as data forms, JSON data, and so on.
    • Request Parameters.Parameters included in the URL, passing the data required by the server.

response

  • anresponseThe response includes the following data
    • Status Code.A three-digit status code, the result of a request such as200 OK ,404Not Found ,500 Internal Server Erroret al. (and other authors)
    • Response Header.responseresponse header is the same data type as the request's request header.Content-Type ,User-Agent ,Accept-Languge
    • Response body.Contains the data returned by the server to the client , such as HTML pages , JSON data , images and so on.

HttpServletRequest and HttpServletResponse

HttpServletRequestcap (a poem)HttpServletResponse were...ServletRequescap (a poem)ServletResponseThe Http interface is a sub-interface that specializes in the HTTP protocol.

ServletReques together withServletResponse is the top-level interface in the Servlet API, and theHttpServletRequestcap (a poem)HttpServletResponse The difference is that the former is dealing withRequest/responseIt defines the basic interfaces of variousRequest/responseinterfacesWorks with multiple protocols, not just HTTP requests

HttpServletRequest

The following is the main introduction forHttpServletRequestThe four applications, which also draw on the same platform creators @Evan Liu

Common methods for obtaining information about the client

  • String getRequestURL() :Returns the full URL of the request made by the client
  • String getRequestURI() :: Returns a portion of the resource name in the request line
  • String getQueryString() :: Returns the parameter part of the request line
  • String getRemoteAddr() : Returns the IP address of the client that made the request
  • String getMethod() Getting the client request method
  • getContextPath():Get the name of the project virtual directory

Eg:

@WebServlet("/test")
public class MyHttpServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        (());
        (());
        
        (());
       
        (());
        (());
        (());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ("fulfillmentPOSTRequest business logic");
    }

Get request header information

  • String getHeaders(String var1):: Get the value of the header, converting it to a string.var1 : The name of the request header, e.g..
    "Accept-Encoding","User-Agent""Content-Type" wait a minute!

  • Enumeration<String> getHeaders(String var1) : Get the value of the header information, return the value of theEnumeration<String>Arrays of type

  • Enumeration<String> getHeaderNames(String var1) : Get all the names of the headers, return the name of the header which should beEnumeration<String>Arrays of type

    • Enumeration: enumeration interface, is a special data type, mainly used for traversing the collection of elements, is an older technology, now the mainstream use ofIteratorcap (a poem)Iterable

    eg:

    @WebServlet("/test")
    public class MyHttpServlet01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            ("getHeaders: "+("Accept-Encoding"));
            //gainhttpin the request headerrefereranti-theft chain
            ("getHeaders: "+("referer"));
    
            ("--------------------------------------------------");
            Enumeration<String> headerNames = ();
            while())
            {
                String name=();
                (name+": "+(name));
            }
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ("fulfillmentPOSTRequest business logic");
        }
    }
    
    

Get request parameter information

  • String getParameter(String name):: Get the value of a request parameter with the specified name, or return it if not found.null
  • String getParameterValues(String name): Get all the values of the requested parameter with the specified name, i.e., if a parameter has more than one value, then return all of them, if none are found, then returnnull
  • Enumeration<String> getParameterNames() :Get all theparameter name
  • Map<String, String[]> getParameterMap() :Get all the parameters in the request and their mappings

eg:

@WebServlet("/test")
public class MyHttpServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String parameter = ("value");
        String[] values = ("value");
        Enumeration<String> parameterNames = ();
        Map<String, String[]> parameterMap = ();

        (parameter);
        ((values));

        while(())
        {
            String str=();
            (str);
        }

        for (<String, String[]> entry : ()) {
            String str = ();
            String[] string = ();
            (str+":");
            ((string));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ("fulfillmentPOSTRequest business logic");
    }
}

Request forwarding

In Java Web request forwarding is a very commonly used techniques, which is used in a Web application, from a resource such as (Servlet), jump to another resource, and achieve distributed utilization of resources

Principles of Request Forwarding

  • When a Servlet receives a request from a client, it may decide to forward the request to another resource for processing. In this case, theThe context of the original request (request parameters, request headers, etc.) is passed to the target resource.The client will not be able to detect that a forward has occurred

Forwarding method

Java, provides aRequestDispatcher interfaces for request forwarding and request containment, which is very useful when dealing with complex Web application logic

  • Main methods of RequestDispatcher

    • void forward(ServletRequest var1,ServletResponse var2 :: Forward the current request to the specified target resource, passing the original request and response objects.
    • void include(ServletRequest var1, ServletResponse var2) : Include the specified target resource in the current response, and the output of the target resource will be merged into the current response.
  • ServletRequest Request Scope Methods

    The ServletRequest interface in Java Web Development provides methods that allow some properties to be used in theLifecycle of a request is shared by multiple resources

    • void setAttribute(String name, Object object) : Its used to convert a<name-object>. pairs are added to the request scope, which is then used in the business logic of the
      • Underlying Principle.
        • Storage Principle.When calling thesetAttributemethod, theServletRequestinterface creates an internal mapping Map that maps its<name-object>.The Map is a thread-safe data structure suitable for storing range attributes.
        • Scope of action.The scope of action is usually within the lifecycle of an HTTP request, which means that the attributes stored in the Map can only be used during the processing of the current process, after the request is processed, these attributes will be automatically destroyed.
        • Shared Properties.pass (a bill or inspection etc)setAttribute The fact that stored properties can be accessed by multiple resources at different stages of processing means that they can be accessed in differentServletSharing of data between
    • Object getAttribute(String name) : Used to retrieve the value of the requested attribute with the specified name, if it is not retrieved then access thenull
    • viod removeAttribute(String name) :: Used to remove the attribute with the specified name from the request scope

Characteristics of Forwarding

  • Server-side operations.The forwarding operation is a server operation, the client will not be aware of it.The browser's address bar URL does not change
  • Relative path.Relative paths are often used to specify the location of the target resource when forwarding.The target resource must be located in the same web application
  • Life cycle.Request forwarding occurs within the same request lifecycle, and exception forwarding can share aHttpServletRequestcap (a poem)HttpServletResponse

HttpServletResponse

HttpServletResponse Encapsulation server sends a response data message to the client

Commonly used response methods

  • void setStatus(int status) :: Used to set the HTTP response status code, usually used to indicate whether the client was successful and how the response was handled.status: HTTP response status code, e.g.200 OKcap (a poem)404 Not Found

  • void setHeader(String name, String value) :Sets a value with the given name and value of theHeaderifnameAlready exists, then directly overrides

  • ServletOutputStream getOutputStream() :Get aServletOutputStream Byte Stream Object,Output the content of the response body

  • PrintWriter getWriter() :Get aPrintWriterCharacter Stream Object, outputs the content of the response body.PrintWriteractually inherits theWriter

  • status response code

    The status response code is used forIndicates the status of the server's response to the client's requestStatus codes are composed of a three-digit code and a short description, and can be categorized into five types: 1xx, 2xx, 3xx4xx, 5xx.

    • 1XX (message status code)

      This type of status code indicates that the request has been received by the server, but requires further processing.

      • 100 Continue:Typically used forPOSTrequest, which means that the server informs the client that it has received a portion of the request, and the client can continue to send the remaining portion of the request.
      • 101 Switching Protocols:Switching server protocols, usually used to upgrade from HTTP to WebSocket.
    • 2XX (success agreement)

      This type of status code indicates that the request has been successfully processed

      • 200 OK:Indicates that the request has been successfully processed and the response contains the requested data.
      • 201 Created:Indicates that a resource has been created, usually used in POST requests, when a resource has been created return
      • 202 Accepted:Indicates that the server has accepted the request, but not yet processed, usually used for asynchronous processing
      • 204 Not Content:Indicates that the server successfully processed the request, but did not return content.
    • 3XX (redirection status code)

      This type of status code indicates that the client has further actions to take to indicate the presence of the

      • 301 Moved Permanently:Indicates that a server resource has beenPermanently move to a new URL, the client (browser) will automatically redirect the resource to the new URL.

      • 302 Found (Previously "Moved Temporarily"):It means that the requested resources are temporarily transferred to a new URL, and the client will automatically redirect its resources to the new URL.

      • 4XX (client error status code)

        This type of status code indicates an error in the client's request

        • 400 Bad Request:It means that the request sent by the client is syntactically incorrect or cannot be correctly parsed and understood by the server.
        • 401 Unauthorized:It indicates that the client attempted to access a resource that requires authentication, but did not provide valid authentication information.
        • 403 Forbidden:Indicates that access to the resource was denied by the server, but there was sufficient privilege to access the resource.
        • 404 Not Found:The server cannot find the requested resource
        • 405 Method Not Allowed:: Indicates that the requested method is not allowed to be used to request resources
      • 5XX (server error status code)

        • 500 Internal Server Error:Usually indicates that the server has encountered an unforeseen situation and is unable to fulfill the request.Usually indicates an internal server error
        • 501 Not Implemented:Indicates that the server does not support the requested method, for example, the server may not support the PUT method.
        • 502 Bad Gateway:Indicates that the gateway or proxy working server received an invalid response
        • 503 Service Unavailable:Indicates that the server is currently unavailable (overloaded or down)
        • 504 Gatew TimeOut:Indicates that the server working as a gateway or proxy did not receive the request from the upstream server in a timely manner

reposition

Redirect is a common technique used to redirect a client request from one resource to another.Unlike forwarding, redirection creates a new HTTP request.

  • Repositioning approach

    In the Servlet API, theHttpServletResponseinterface provides a method to implement relocation

    • void sendRedirect(String location) :: Redirects the client to the appropriate URL, thelocation:: Target URL address

    eg:

    
    @WebServlet("/test01")
    public class MyHttpServlet01 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //Setting the output text format,i.e., the coding format
            ("text/html;charset=UTF-8");
            PrintWriter writer = ();
            ("<p>This is the first one.servlet</p>");
           //Forwarding to/test02
            ("/test02");
        }
    }
    //
    @WebServlet("/test02")
    public class MyHttpServlet02 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ("text/html;charset=UTF-8");
            PrintWriter writer = ();
            ("<p>This is the second one.servlet</p>");
        }
    }
    

    When accessing /test01 to the browser, the browser will receive the first Servlet response, and then will be redirected to /test02. Launch the request again, the client will see two jumps and the following interface

  • Principle of repositioning

    • After the server receives the request, it will provide its HTTP response code to determine whether to perform the relocation operation, if the status code is302 Found(or301 Moved Permanently) will look at its response header(Response Headers)and relocates according to the Location attribute in the
    • When the client receives the relocation response and resolves the new jump location, it makes another HTTP request to the new location.
    • sendRedirect() It actually sets the Status Code in the request header and the Location attribute in the response header.

Difference between relocation and forwarding

Forwarding and redirection are to realize the page jump, they are access to a Servlet, Servlet will help us jump to another interface, just the realization of the method is different, the following content borrowed from the creator @ Moe small Q

  • In terms of the URL address bar
    • forwardis the server to request resources, the server to access the target address of the URL, the server will be the target URL response content sent to the client (browser), in fact, the browser does not know where the content sent by the server, the operation is realized by the server
    • redirectIt is the server that sends a status code according to the business logic to tell the browser to re-request the new URL, so the URL in the redirection bar will change accordingly.
  • data sharing
    • forward:Both the forwarded page and the forwarded page can be shared.request Data in Scope
    • redirect:: Cannot share data
  • Purpose
    • forward: Generally used for user login, according to the role to forward the corresponding template
    • redirect:: Generally used to return to the main page when the user logs out or jumps to another website, etc.
  • Effectiveness
    • forward:: Higher efficiency
    • redirect:: Lower efficiency

Underlying Essential Differences

forward(forwarding) is server behavior.redirectround trip (redirection) is client-side behavior

  • action
    • forwardBehavior:Client (Browser) initiates the http request → web server (e.g.Tomcat) receives the request → calls one of its internal methods to complete the request processing or forwarding action → returns the resources of the request response to the client.For forward, the forwarded path must be a URL in the same web container.Cannot be redirected to another web path, forwarded byrequest , forwarding considers the browser to have made only one access request
    • redirect Behavior: the client sends a http request ¡ú the web server receives and sends a 302 status response code and for the location to the client ¡ú the client checks the response header is found to be a 302 response, it is the second time to send a http request, the request is for a new URL in the location ¡ú the server responds to the request for the corresponding resources to return to the client, the client.Since the request is re-initiated by the browser, it has nothing to do with the intermediate request delivery.Redirection is where the client does at least two access operations
  • operating privilege
    • forward:It is the process of internalizing a server that puts arequestmayberesponseto anotherServlet
    • redirect : is the client request A, the server responds, and response back, telling the browser you should go to B, the browser is not the same as the client.Redirects can access resources outside of your own web application
  • caveat
    • redirect(redirection): must be added after the jumpreturnOtherwise, the page will jump but still execute the statement after the jump.
    • forward(Forwarding): is the execution of the code below the jump page will not be executed in the