Request和Response。

Review: 1, 2 redirects the output string to the browser. 3, file download requirements: 1. The page displays a hyperlink pop 2. Click on the hyperlink to download prompt box 3. Complete the picture file download

Request和Response

Request:

1, request and response principle:

  1, the browser sends a request to the server, the server creates an object ServletDemo Tomcat classes according to the resource corresponding to the route request url.

  2, tomcat create request and response objects, and encapsulates the data object request message to the request

  3, tomcat calls the service method, and two request and response objects passed as parameters.

  4, the programmer can request message for acquiring a data request object, and Setup Response message data through the response object.

  5, the server response data from the response object out and fed back to the browser.

2, request objects inherit architecture:

  ServletRequest Interface <--- HttpServletRequest Interface <--- org.apache.catalina.connector.RequestFacade class (Tomcat implemented)

3, request function

  1, a data acquisition request message.

    1, a data acquisition request line commonly used methods:

      * Gets the virtual directory: String getContextPath ()

      * Get the request URI: String getRequestURI (), URL: StringBuffer getRequestURL ()

    2, the data acquisition request header:

      * String getHeader (String name): its value is obtained by requesting the name of the header.

    2, the volume data acquisition request:

      * Request POST request body only mode only, the package POST request request parameters in the request body.

      * Step: 1, obtaining the stream object:

            * Get the character input stream: BufferedReader getReader ()

            * Get input stream of bytes: ServletInputStream getInputStream ()

          2, to obtain data objects from the stream.

  2, request additional features:

    1, acquisition parameters common mode request (get / post may be):

      * String getParameter (String name): Gets the value according to the parameter name.

      * String [] getParameterValues ​​(String name): Gets the data value (box) The parameter name

      * Enumeration <String> getParameterName (): Gets all request parameter name.

      * Map <String, String []> getParameterMap (): Get all map the set of parameters.

      * Chinese chaos problem: get way: tomcat8 resolved automatically. post way: before the acquisition parameters provided encoding request.setCharacterEncoding ( "utf-8");

    2, the request is forwarded: a resource in a way to jump inside the server.

      * Step: 1, target acquisition request forwarder request object: RequestDispatcher getRequestDispatcher (String path)

          2, using the RequestDispatcher object to forward: forward (ServletRequest request, ServletResponse response)

      * Features: 1, the browser address bar does not change to access multiple resources.

            2, only forwarded to the internal resources of the current server.

          3, using a forwarding request.

    3, share data:

      * Domain objects: a scope of the object, the range data can be shared.

      * Request field: a request on behalf of a range, generally a plurality of resource requests forwarded shared data.

      * Methods: void setAttribute (String name, Object obj) storage resources.

           Object getAttribute (String name): Gets the value by key.

          void removeAttribute (String name) by removing the key to key.

    4, get ServletContext:

      *ServletContext getServletContext();

Response:

1, the response message:

Data Format:

  1, response line: Composition: Protocol / version response status code status code Description HTTP / 1.1 200 OK

    * Status codes are three-digit classification:

      1,1XX: server receives the client message, but does not receive complete, send 1xx asked whether it should send.

      2,2xx: success. Representative: 200.

      3,3xx: Redirect. Representative: 302 (redirect), A resource request can not solve the problem of data, but A knows B can be resolved, return 302, so that the Client Access B. 304 (access cache), the server finds the requested data in your client has to return 304 allows the client to find locally.

      4,4xx: client error. Representative: 404 (there is no corresponding resource request path) (doXX embodiment no corresponding request method) 405

      5,5xx: server error. Representative: 500 (internal server error)

    * 

  2, the first response: Format: Name header: Value

    * Common response header: 1, Content-Type: This response tells the client to present the volume data format and coding formats.

            2, Content-disposition: to tell the client to open the body in response to what data format.

              Value: in-line: By default, the page open in the current.

                attachment; filename = xxx: Open Response body attachment. For file downloads.

 

  3, in response to a blank line:

  Data transmission: 4, body response.

2, Response function.

1, setup response message.

  * Set response line: Set status code: setStatus (int sc)

  * Set response header: setHeader (String name, String value)

  * Setting response thereof: using the output stream.

    1, obtain an output stream: Character: PrintWriter getWriter () byte: ServletOuntputStream getOutputStream ()

Case:

  1, complete redirection: Resource jump way. Response.sendRedirect (jump path)

   * Forwarding features:

    1, the address bar the same path. 2, forwarding only have access to resources at the current server. 3, a request is forwarded, the data can be shared.

  * Redirect features:

    1, the address bar the path to change. 2, you can access resources from other servers. 3, two request is redirected, the data can not be shared.

  2, some of the problems paths.

  The proper use of the project relative / absolute path, use virtual directory, we recommend that dynamically acquire virtual directory: request.getContextPath ()

  3, server output character data to the browser:

    1, to solve the distortion problem: response.setContentType ( "text / html; charset = utf-8");

    2, obtaining the output character stream PrintWriter getWriter (). Then use WITE () output.

  4, the server outputs byte data to the browser: response.getOutputStream ()

  5, the verification code.

ServletContext object:

1, the concept of: representative of the web application, the container may program (server) to communicate.

2, access to:  

  * Be obtained by request: request.getServletContext ()

  * To get through HttpServlet: this.getServletContext ()

3, features:

  * Get the MIME type.

    MIME types: one file data type defined in the Internet communication. Format: Large type / small type text / html

    Gets: String getMimeType (String file) 

  * Domain objects: share data. setAttribute ()

  * Get real files (server) path String getRealPath (String path)

Case: file download.

Download requirements: 1. The page displays a hyperlink 2. Click on the hyperlink to download the pop-up message box 3. Complete the picture file download

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       String filename=request.getParameter("filename");
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        FileInputStream fis=new FileInputStream(realPath);

        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);
        response.setHeader("content-disposition","attachment;filename="+filename);

        ServletOutputStream sos=response.getOutputStream();
        byte[] buff=new byte[1024];
        int len=0;
        while ((len=fis.read(buff))!=-1){
            sos.write(buff,0,len);
        }
        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    }
}

Chinese file problem:

Solutions: Get information about the browser version used by the client, and then set the filename encoded according to different versions of the information.

Use tools easy to operate.

 

Guess you like

Origin www.cnblogs.com/zhangyuhao/p/11022062.html