In the previous Http request article we saw that an Http request contains a request header, a request body, a response header, and a response body. So we have standards for interacting with browsers for these request aspects and response aspects. If we need a Request and Response API on the back end, we introduced the concept of Request and Response to describe an HTTP Request.

Request

Request the object without prior statement, you can use in the JSP page, after the compiler for the Servlet, it will be converted to javax.mail. Servlet. HTTP. Objects in the form of it, The HttpServletRequest object is an object that contains information about the request made by the client, such as request headers, request methods, request parameters, client IP, client browser, and so on

ServletRequest – A generic request that provides the most basic methods a request should have. HttpSerletRequest is a subclass of Rquest that further enhances the HTTP protocol

The operation of the Request

Getting client information

The getRequestURL() method returns the full URL of the request made by the client. The getRequestURI() method returns the resource name portion of the request line. The getQueryString() method returns the parameter portion of the request line. GetMethod () gets the request mode of the client getContextPath() gets the name of the current Web application virtual directory

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //1. Get the full URL requested by the client
        String url=request.getRequestURL().toString();
        System.out.println(url);
        //2. Obtain the partial name of the resource requested by the client
        String uri=request.getRequestURI();
        System.out.println(uri);
        //3. Get the parameter part of the request line
        String pram=request.getQueryString();
        System.out.println(pram);
        //4. Return the client IP address (*)
        String ip=request.getRemoteAddr();
        System.out.println(ip);
        //5. Obtain the client's request mode
        String method=request.getMethod();
        System.out.println(method);
        //6. Obtain the name of the current Web application
        String name=request.getContextPath();
        System.out.println(name);

        // This method is available after the request is forwarded
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

Copy the code
Gets the request header information

Get the client request header getHeader(name) method — String getHeaders(String name) method — Enumeration Enumeration variable getHeaderNames method — Enumeration GetIntHeader (name) method — int getDateHeader(name) method — long(date corresponds to milliseconds)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO auto-generated method stub // Obtaining the request header from the client //String Value =request.getHeader("Host"); //System.out.println(value); // Walk through all the request header Enumeration<String> enument= request.getheaderNames (); while(enument.hasMoreElements()){ String name=enument.nextElement(); String values=request.getHeader(name); System.out.println(name+":"+values); }}Copy the code
Get request parameters

request.getParameter()

In what code does the browser send the request parameters? The browser sends the submitted data in the code in which the form page is opened. What code does the server open in? If not specified, use iso8859-1, so if you have any Chinese inevitably request parameters in the code For POST submission, you can set the request. SetCharacterEncoding (” utf-8 “); Explicitly notifying the server to open the data in the code sent by the browser solves the problem. However, the above method only works on the physical content part of the request, so the GET submission does not solve the problem. String username = request.getParameter(“username”); String username = request.getparameter (“username”); username = new String(username.getBytes(“iso8859-1″),”utf-8”);

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO auto-generated method stub /* * POST Generated method stub /* // request.setCharacterEncoding("utf-8"); String name=request.getParameter("username"); String name=request.getParameter("username"); //System.out.println(name); * */ String username=new * */ String username=new * */ String username=new String(name.getBytes("iso8859-1"),"utf-8"); ///// // gets the type with an enumeration variable; Enumeration<String> enumeration=request.getParameterNames(); while(enumeration.hasMoreElements()){ String names=enumeration.nextElement(); String values=request.getParameter(names); System.out.println(names+":"+values); }}Copy the code
Pass objects using the request domain
A request begins when the server receives a request and creates a request object that represents the request. When the request ends, the server destroys the request object representing the request, and the request field ends. Function: The data is shared throughout the request chainCopy the code
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Request scope global getRequestDispater() returns a RequestDispatcher object that acts as a wrapper for the resource resource located in the given path.
        request.setAttribute("banana"."color:yellow");
        this.getServletContext().getRequestDispatcher("/Demo2").forward(request, response);
        // Forward to XXXJSP
        // get the data ru
        String result="xxxx";
        request.setAttribute("xxx", result);
        request.getRequestDispatcher("xxx.jsp");
    }

Copy the code
Implement request forwarding and request inclusion

(.forward()): this.getServletContext().getrequestDispatcher (“”).forward(request,response); request.getRequestDispatcher(“”).forward(request,response);

` forward requests is that I wish to request to another resource, so you should ensure that only true to perform resource finally able to output data, so: ` ` forward requests, if you have data to be written to the response of the buffer, but the data has not been sent to the client, the request is forwarded, the data will be cleared. However, only the physical content of the response will be cleared, and the header will not be cleared. If the request fails to be forwarded, it will throw an exception because the response has already ended and there is no point in forwarding the request to others 'After the Servlet execution of the final output data is completed, the data in the content of the response entity will be set to the submitted state, and writing data into it will not work'Copy the code

This.getservletcontext ().getrequestDispatcher (“”).include(request,response); request.getRequestDispatcher(“”).include(request,response);

The included Servlet program cannot change the status code and response header of the response message. If it contains such statements, the execution results of these statements will be ignored and used for page layoutCopy the code

(3) The differences between the three resource processing methods

Request to redirect response.sendreDirect (); Request to forward the request. GetRequestDispatcher (). The forward (); Request contains request. GetRequestDispatcher (). The include ();

The difference between request redirection and request forwarding:

'The request redirection address bar will change. Request forwarding address bar does not change. ' 'Request redirection twice request twice response. Request to forward a request a response. ` ` if you need to jump when the utilization of resources request domain transfer domain properties are request to forward the request must be used. The getRequestDispatcher (). The forward (); If you want to modify the user's address bar after a resource jump, redirect response.sendreDirect () with a request; If the use of request forwarding can also be redirected, the use of request forwarding is preferred to reduce the number of browser visits to the server to reduce the pressure on the serverCopy the code

Response

Response is the Servlet. A parameter of the service method, type of javax.mail. Servlet. HTTP. HttpServletResponse. For each request made by the client, the server creates a response object and passes it to the servlet.service () method. The Response object is used to respond to the client, which means that the response object can be used in the service() method to respond to the client.

The Response operation

Set encoding mode

response.setHeader(“Content-Type”, “text/html; charset=utf-8”); response.setCharacterEncoding(“utf-8″); The response. GetWriter (). The write (” China “);

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Here is a coding process, using the operating system code;
        // The browser is also opened in GBK mode, so there is no garble
        //response.getOutputStream().write("English very so easy".getBytes());
        // This will cause garbled characters. You need to open the browser using UTF-8 encoding to avoid garbled characters or use the following method
        //response.setHeader("Content-Type", "text/html; charset=utf-8");
        / / response. GetOutputStream (). The write (" Chinese ". GetBytes (" utf-8 "));
        /* the server can only convert Chinese characters to 010101 and then check the ISO8859-1 code table this code table does not have Chinese, if in iso8859-1 can not find it will be converted to? However, the browser will open the code with GBK so it will display?? Specify the code table */ for the server
        // specify the server to check the code table
        response.setCharacterEncoding("gbk");
        response.getWriter().write("beijiang");
        response.getWriter().write("China");
        // Or so;
        response.setHeader("Content-Type"."text/html; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("China");
        // Or so; SetContentType can directly specify the browser and server encoding
        response.setContentType("text/html,charset=utf-8");
        response.getWriter().write("China");
        // Or SetCharacterEnconding specifies the server encoding
        //setContentType specifies the browser encoding
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html,charset=utf-8");
        response.getWriter().write("China");
    }

Copy the code
Set whether to cache (cache time)

Response. SetIntHeader (“Expires”, -1); response.setHeader(“Cache-control”,”no-cache”); response.setHeader(“Pragma”,”no-cache”); Response.setdateheader (“Expires”, System.currentTimemillis ()+1000L_3600_24*30);

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the buffer time
        response.setDateHeader("Expires", System.currentTimeMillis()+1000L*3600*24*30);
        // It reads the file but does not download it
        InputStream in=new  FileInputStream(this.getServletContext().getRealPath("1.jpg"));
        OutputStream out=response.getOutputStream();
        byte[]bs=new byte[1024];
        int i=0;
        i=in.read(bs);
        while(i! = -1){
            out.write(bs,0,i);
            i=in.read(bs);
        }
        in.close();
        /// The download format should be this way

    }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Set the response header not to be cached in the browser
        response.setIntHeader("Expires", -1);
        response.setHeader("Cache-control"."no-cache");
        response.setHeader("Pragma"."no-cache");
        // Set the encoding mode of both server and browser
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().write("Current time is :"+new Date().toLocaleString());
    }

Copy the code
Setting resource Download

Urlencoding. encode(‘ ah.jpg ‘,’ utF-8 ‘); If not encoded, the file name is displayed incorrectly and cannot be downloaded

/// The download should be in the form of this

response.setHeader("Content-Disposition", "attachment; filename=1.jpg");

InputStream in=new FileInputStream(this.getServletContext().getrealPath (“1.jpg”));

OutputStream out=response.getOutputStream();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO auto-generated method stub /// setHeader header does not support Chinese format so name cannot be used to specify the name displayed for the download //response.setHeader("Content-Disposition", "attachment; Filename = beauty. JPG "); // Response. setHeader(" content-disposition ", "attachment; filename=butiful.jpg"); Responsetheader (" Content-disposition ", "attachment; response.setheader (" content-disposition ", "attachment; Filename = "+ URLEncoder. Encode (" beauty. JPG", "utf-8")); (N) InputStream in=new FileInputStream(this.getServletContext().getrealPath ("1.jpg")); OutputStream out=response.getOutputStream(); byte[]bs=new byte[1024]; int i=0; i=in.read(bs); while(i! =-1){ out.write(bs,0,i); i=in.read(bs); } in.close(); }Copy the code
Request redirection

response.sendRedirect(“/Test/index.jsp”);

Set refresh jump

response.setHeader(“refresh”, “3; url=/Test/index.jsp”); Forward / / request. GetRequestDispatcher (“/index. The JSP “). The forward (request, response); Include/request. GetRequestDispatcher (“/index. The JSP “). The include (request, response); Redirect response. SendRedirect (“/Test/index. The JSP “);

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO auto-generated method stub // Refresh the page every few seconds // Response.getwriter ().write(new Date().toString()); //response.setHeader("Refresh", "1"); A few seconds to the home page / / / / response. SetCharacterEncoding (" utf-8 "); //response.setHeader("Content-Type", "text/html; charset=utf-8"); response.setContentType("text/html; charset=utf-8"); Response.getwriter ().write(" Congratulations on your successful registration 3 seconds after the jump to the page...." ); response.setHeader("refresh", "3; url=/Test/index.jsp"); <meta http-equiv="" content=""> to simulate the response header}Copy the code

The above is the technology of shared request and response. However, with the separation of front and back ends, most of us now use Response to directly write data to that location. Most of the frameworks help us to do some things, but we should also really understand the connotation of it. Like to pay attention to, but also hope you put forward valuable suggestions.