JavaWeb core technology ~ Request

Posted by atzi on Sat, 18 Dec 2021 14:01:58 +0100

Request object

introduce

Request: obtain resources. In BS architecture, the client browser sends a query to the server
Request object: the object used to send the request in the project

Common method of request - obtain various paths

Return valueMethod nameexplain
StringgetContextPath()Get virtual directory name
StringgetServletPath()Get Servlet mapping path
StringgetRemoteAddr()Get visitor ip address
StringgetQueryString()Get the requested message data
StringgetRequestURI()Get the same resource identifier
StringBuffergetRequestURL()Get uniform resource locator

Common method of request object - get request header information

Return valueMethod nameexplain
StringgetHeader(String name)Gets a value based on the request header name
EnumerationgetHeaders(String neme)Get multiple values according to the request header name
EnumerationgetHeaderNames()Get all request header names

Common method of request object - get request parameter information

Return valueMethod nameexplain
StringgetParameter(String name)Get data by name
String[]getParameterValues(String name)Get all data by name
EnumerationgetParameterNamesGet all names
Map<String,String[]>getParmeterMap()Get key value pairs for all parameters

Get request parameters and encapsulate objects

1. Manual packaging mode

public class Student {
    private String username;
    private String password;
    private String[] hobby;

    public Student() {
    }

    public Student(String username, String password, String[] hobby) {
        this.username = username;
        this.password = password;
        this.hobby = hobby;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getHobby() {
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString() {
        return "Student{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", hobby=" + Arrays.toString(hobby) +
                '}';
    }
}
//Packaging method - manual packaging
@WebServlet(name = "ServletDemo01", value = "/ServletDemo01")
public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String[] hobbies = request.getParameterValues("hobby");

        Student stu = new Student(username,password,hobbies);

        System.out.println(stu);

    }


}

Note: it is troublesome to obtain data in this way. You must write one by one

2. Reflection packaging method

//Packaging method -- Reflection packaging method

@WebServlet(name = "ServletDemo02", value = "/ServletDemo02")
public class ServletDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        Student stu = new Student();
        for (String name : map.keySet()){
            String[] values = map.get(name);

            try {
                //Gets the property descriptor of the Student object, and the jdk provides the tool class
                PropertyDescriptor pd = new PropertyDescriptor(name,stu.getClass());
                //Get the corresponding setXxx method
                Method writeMethod = pd.getWriteMethod();
                //Execution method
                if (values.length>1){
                    writeMethod.invoke(stu,(Object) values);
                }else{
                    writeMethod.invoke(stu,values);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(stu);
    }


}

3. Tool packaging method

Import two jar packages (provided by Apache)

  1. commons-beanutils-1.9.4.jar
  2. commons-logging-1.2.jar
//Encapsulation method -- tool class encapsulation

@WebServlet(name = "ServletDemo03", value = "/ServletDemo03")
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        Student stu = new Student();
        try {
            BeanUtils.populate(stu,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(stu);
    }

}

Get request information from stream object

Return valueMethod nameexplain
BufferedReadergetReader()Get character input stream
ServletInputStreamgetInputStream()Get byte input stream

Get data from character stream

//Get request data from character stream (must be in post mode)

@WebServlet(name = "ServletDemo04", value = "/ServletDemo04")
public class ServletDemo04 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine())!=null){
            System.out.println(line);
        }
        //Without manual shutdown, the Servlet will shut down automatically
    }

}

Byte stream get request data

//Get request data from character stream (can only be obtained by Post)

@WebServlet(name = "ServletDemo05", value = "/ServletDemo05")
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream is = request.getInputStream();
        byte[] arr = new byte[1024];
        int len ;
        while ((len=is.read(arr))!=-1){
            System.out.println(new String(arr,0,len));
        }
        //Without manual shutdown, the Servlet will shut down automatically
    }

}

Chinese garbled code problem

  • GET mode
    There is no garbled code problem. It has been solved in Tomcat8

  • POST mode
    There is a garbled code problem. This can be solved by the setCharacterEncoding() method

Request domain

  • Request domain: you can share data within the request range again.

Request object operation shared data method

Return valueMethod nameexplain
voidsetAttribute(String name,Object value)Store data to the request domain object
ObjectgetAttribute(String name)Gets the data in the request domain object by name
voidremoveAttribute(String)Request data in domain object through name overflow

Request forwarding

  • Request forwarding: after a request from the client arrives, it is found that other servlets are needed to realize the function

  • characteristic

The browser address bar will not change
Data in the domain object is not lost
The response body of the Servlet responsible for forwarding will be lost before and after forwarding
The forwarding destination responds to the client

Return valueMethod nameexplain
RequestDispatchergetRequestDispatcher(String name)Get request scheduling object
voidforward(ServletRequest req,ServletResponse resp)Realize forwarding

Request contains

  • The request includes: functions in other servlets can be combined to respond to the client

  • characteristic

The browser address bar will not change
Data in the domain object is not lost
The contained Servlet response header will be lost

Return valueMethod nameexplain
RequestDispatchergetRequestDispatcher(String name)Get request scheduling object
voidinclude(ServletRequest req, ServletResponse resp)Implementation includes

Topics: Java http mvc