Summary of java summer vacation learning (13) - - response & request

Keywords: Java encoding Tomcat Apache

Request

1. Principle of request object and response object
Request and response objects are created by the server. Let's use them.
2. The request object is to get the request message, and the response object is to set the response message.
    
Request Object Inheritance Architecture:
ServletRequest -- Interface
| Inheritance
HttpServletRequest -- Interface
| Realization
The org.apache.catalina.connector.RequestFacade class (tomcat)

3. request function:
1. Get request message data
1. Get request row data
                * GET /day14/demo1?name=zhangsan HTTP/1.1
* Methods:
1. Access request mode: GET
                        * String getMethod()  
2. (*) Get the virtual directory: / day14
                        * String getContextPath()
3. Get the Servlet path: / demo1
                        * String getServletPath()
Get get mode request parameter: name=zhangsan
                        * String getQueryString()
5. (*) Get the request URI:/day14/demo1
                        * String getRequestURI():        /day14/demo1
                        * StringBuffer getRequestURL()  :http://localhost/day14/demo1

* URL: Unified Resource Locator: http://localhost/day14/demo1
* URI: Unified Resource Identifier: / day14/demo1]
                    
Access Protocol and Version: HTTP/1.1
                        * String getProtocol()

7. Get the IP address of the client:
                        * String getRemoteAddr()
                

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Demonstrate Request Object to Get Request Row Data
 */

@WebServlet("/requestDemo1")
public class RequestDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
            1. Get the request way: GET
                * String getMethod()
            2. (*)Get the virtual directory: / day14
                * String getContextPath()
            3. Get the Servlet path: / requestDemo1
                * String getServletPath()
            4. Get the get mode request parameter: name=zhangsan
                * String getQueryString()
            5. (*)Get the request URI:/day14/demo1
                * String getRequestURI():		/day14/requestDemo1
                * StringBuffer getRequestURL()  :http://localhost/day14/requestDemo1
            6. Access Protocol and Version: HTTP/1.1
                * String getProtocol()

            7. Get the IP address of the client:
                * String getRemoteAddr()

         */
        //1. Access request mode: GET
        String method = request.getMethod();
        System.out.println(method);
        //2. (*) Get the virtual directory: / day14
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
        //3. Get the Servlet path: / demo1
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        //4. Get get mode request parameter: name=zhangsan
        String queryString = request.getQueryString();
        System.out.println(queryString);
        //5. (*) Get the request URI:/day14/demo1
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURI);
        System.out.println(requestURL);
        //6. Access Protocol and Version: HTTP/1.1
        String protocol = request.getProtocol();
        System.out.println(protocol);
        //7. Get the IP address of the client:
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
    }
}

    
2. Get the request header data
* Methods:
* (*) String getHeader(String name): Gets the value of the request header by the name of the request header
* Enumeration < String > getHeaderNames (): Get all request header names
                
3. Obtain requester data:
* Request body: Only the POST request mode can have the request body, which encapsulates the request parameters of the POST request.
* Steps:
1. Get stream objects
* BufferedReader getReader(): Gets the character input stream and can only operate on character data
* ServletInputStream getInputStream(): Gets a byte input stream that can manipulate all types of data
* Explain after uploading knowledge points

2. Get the data from the stream object
                
                
2. Other functions:
1. General way to get request parameters: either get or post request can use the following methods to get request parameters
String getParameter (String name): Get the parameter value from the parameter name: username = ZS & password = 123
String [] getParameterValues (String name): Array of parameter values based on parameter names hobby = XX & Hobby = game
Enumeration < String > getParameterNames (): Get the parameter names of all requests
Map < String, String []> getParameterMap (): Get the map set of all parameters

* Chinese scrambling problem:
* get mode: tomcat 8 has solved the problem of get mode scrambling
* Posting: scrambling
* Solution: Set the request encoding request.setCharacterEncoding("utf-8") before getting the parameters.
            
                    
2. Request Forwarding: A Resource Jumping Method within the Server
1. Steps:
Getting the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
2. Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response)

2. Characteristics:
1. Browser Address Bar Path does not change
2. Can only be forwarded to the internal resources of the current server.
3. Forwarding is a request

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo8888 I was interviewed...");
        //Forwarding to demo9 resources
/*
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestDemo9");
        requestDispatcher.forward(request,response);
        */

        //Store data in request domain
        request.setAttribute("msg","hello");

        request.getRequestDispatcher("/requestDemo9").forward(request,response);
        //request.getRequestDispatcher("http://www.baidu.com").forward(request,response);

    }

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

        this.doPost(request,response);
    }
}


3. Sharing data:
* Domain object: A scoped object that can share data within a scope
* Request domain: Represents the scope of a request and is generally used to share data among multiple resources for request forwarding
* Methods:
Void setAttribute (String name, Object obj): Store data
Object getAttitude (String name): Getting values by key
3. void removeAttribute(String name): Remove key-value pairs by key

4. Get ServletContext:
                * ServletContext getServletContext()
            
 

 

Response object

* Function: Setting Response Messages
1. Setting the response line
Format: HTTP/1.1 200 ok
Set status code: setStatus(int sc)
2. Set the response header: setHeader(String name, String value)
    
3. Set the response body:
* Use steps:
1. Get the output stream
* Character output stream: PrintWriter getWriter()

* Byte output stream: ServletOutputStream getOutputStream()

2. Use output stream to output data to client browser


* Case:
1. Complete redirection
* redirection: the way resources jump
* Code implementation:
// 1. Set the status code to 302
        response.setStatus(302);
// 2. Setting the response header location
        response.setHeader("location","/day15/responseDemo2");
// Simple redirection method
        response.sendRedirect("/day15/responseDemo2");


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * redirect
 */

@WebServlet("/responseDemo1")
public class ResponseDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("demo1........");



        //Accessing / responseDemo1 automatically jumps to / responseDemo2 resources
       /* //1. Set the status code to 302
        response.setStatus(302);
        //2.Setting the response header location
        response.setHeader("location","/day15/responseDemo2");*/

        request.setAttribute("msg","response");

        //Dynamic access to virtual directories
        String contextPath = request.getContextPath();

        //Simple redirection method
        response.sendRedirect(contextPath+"/responseDemo2");
   

    }

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

* The difference between forward and redirect

* The redirect feature: redirect
1. Changes in the address bar
2. Redirecting resources that can access other sites (servers) (key)
3. The redirection is two requests. Can't use request object to share data (key)
* Forwarding features:forward
1. The forwarding address bar path remains unchanged
2. Forwarding can only access resources under the current server (key)
3. Forwarding is a request that can be used to share data (key)
     
* Path Writing:
Path classification
Relative Path: It is not possible to determine a unique resource through a relative path
* For example:. / index.html
* Do not start with / start with. Start with. Path

* Rule: Find the relative location relationship between current and target resources
* /: Current directory
* /: Backward level catalogue
Absolute Path: Determining the Only Resource by Absolute Path
* For example: http://localhost/day15/responseDemo2; /day15/responseDemo2
* Path starting with/

* Rule: To whom is the defined path used? Determine where the request will come from in the future
* Used by client browser: virtual directory (access path of project)
* Recommended virtual directory dynamic acquisition: request.getContextPath()
*<a> <form> redirection...
* Server use: no need to add virtual directories
* Forwarding path

              

2. Server output character data to browser
* Steps:
Get the character output stream
2. Output data

* Note:
* Scrambling problem:
PrintWriter PW = response. getWriter (); the default encoding for the acquired stream is ISO-8859-1
2. Set the default encoding of the stream
3. Tell the browser the encoding used by the response body

// Simple form, set encoding, is set before getting the stream
            response.setContentType("text/html;charset=utf-8");


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/responseDemo4")
public class ResponseDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //Before getting the stream object, set the default encoding of the stream: ISO-8859-1 to: GBK
       // response.setCharacterEncoding("utf-8");

        //Tell the browser the encoding of message volume data sent by the server. It is recommended that browsers use this encoding and decoding
        //response.setHeader("content-type","text/html;charset=utf-8");

        //Simple form, set encoding
        response.setContentType("text/html;charset=utf-8");

        //1. Get the character output stream
        PrintWriter pw = response.getWriter();
        //2. Output data
        //pw.write("<h1>hello response</h1>");
        pw.write("Hello ah ah ah ah ah response");
    }

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


3. The server outputs byte data to the browser
* Steps:
Obtain byte output stream
2. Output data

 

4. Verification code
Essence: Pictures
2. Purpose: To prevent malicious form registration


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        int width = 100;
        int height = 50;

        //1. Create an object with pictures in memory (Verification Code Picture Object)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


        //2. Beautifying pictures
        //2.1 Filling Background Colors
        Graphics g = image.getGraphics();//Brush object
        g.setColor(Color.PINK);//setpc
        g.fillRect(0,0,width,height);

        //2.2 Drawing Borders
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //Generating Random Corner
        Random ran = new Random();

        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //Getting Characters
            char ch = str.charAt(index);//Random Characters
            //2.3 Write Verification Code
            g.drawString(ch+"",width/5*i,height/2);
        }


        //2.4 Draw interference lines
        g.setColor(Color.GREEN);

        //Random Generation of Coordinate Points

        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


        //3. Export pictures to page display
        ImageIO.write(image,"jpg",response.getOutputStream());


    }

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


 

Posted by Hoangsta on Tue, 23 Jul 2019 00:16:12 -0700