Read HTTP request [HttpServletRequest]

1. Understand the method

System.out.println("Request protocol name:"+req.getProtocol());
System.out.println("Request method:"+req.getMethod());
System.out.println("Application context path/App Name:"+req.getContextPath());
System.out.println("Resource path/servletPath: "+req.getServletPath());
System.out.println("The key in the request header is Host Value of:"+req.getHeader("Host"));

Output result:

2.getParamter

Get value through key: 1 queryString 2. Form format, body 3 Form data format is a simple type

1. Get the data in url QueryString

Front end code:

<h3>get with query string</h3>
<!-- Access path of current page:/[contextPath Application context path]/request.html,
Need to jump to/[contextPath]/request -->
<!-- You can also directly url Enter the same value after link jump url Absolute path to access -->
<a href="request?username=abc&password=123">get</a>

Display results:

Backend code:

//1.queryString access path: request? username=abc&password=123
System.out.println("username: "+req.getParameter("username"));
System.out.println("password: "+req.getParameter("password"));

Back end output:

Click the get link and the url changes to:

Note: when http requests, the url will be encoded, and the Chinese, spaces and special characters in queryString need to be decoded

Demo: the request method is not set for form submission. The default is get. The control in the form will take name as the key,
Enter the selected content as a value and set it to queryString to achieve the same effect as the above
Front end code:

<form action="request">
    <input type="text" name="username" placeholder="enter one user name">
    <br>
    <input type="password" name="password" placeholder="Input password">
    <br>
    <input type="submit" value="Submit">
</form>

The community version is displayed normally in Chinese, but we should pay attention to the possibility of garbled code when writing code

2. Get the form format in the body

Front end code:

<h3>Form format:/request</h3>
<form action="request" method="post">
    <input type="text" name="username" placeholder="enter one user name">
    <br>
    <input type="password" name="password" placeholder="Input password">
    <br>
    <input type="submit" value="Submit">
</form>

Display results:

Backend code:

//2. Form format: the data in the body is in the same format as queryString
//Note: the content in the body also has a coding format, which needs to be set before it can be displayed normally. There will be garbled code when Chinese is not input
req.setCharacterEncoding("utf-8");//Set the encoding format of body parsing
System.out.println("username: "+req.getParameter("username"));
System.out.println("password: "+req.getParameter("password"));

After submitting, you will find that the method is not allowed:

So we need to support the post method without changing the doGet method. What should we do?

//Both get and post methods are supported
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req,resp);//If the logic is the same, call the doGet method
}

Back end output:

fiddler packet capture result:

3. Obtain the data of simple data type in form data

Front end code:

<h3>form-data Format:/form-data-servlet</h3>
<form action="form-data-servlet" enctype="multipart/form-data" method="post">
    <input type="text" name="username" placeholder="enter one user name">
    <br>
    <input type="password" name="password" placeholder="Input password">
    <br>
    <input type="submit" value="Submit">
</form>

At the same time, modify the backend here:

Back end output after submitting results:

fiddler packet capture result:

Key points: http request data, storage location

  • url queryString
  • body (multiple types)

3.getPart

Obtain the uploaded file in form data format
If the uploaded file is directly obtained by getParameter(), it cannot be obtained:


The file uploaded in form data needs to be obtained through getPart, but getParameter cannot obtain it

In fact, simple type data can also be obtained by using getPart, but it is complicated to call Part object to obtain content
(1) Can read: read through the input stream of the Part object

Part head=req.getPart("head");
//Get the binary data of the uploaded file and convert it into string for printing
InputStream is = head.getInputStream();//Get the input stream (which contains data)
//Input stream available returns the length of the data contained
byte[] bytes = new byte[is.available()];
//From the input stream, read the data into byte [] and the byte array object has these data
is.read(bytes);
System.out.println(new String(bytes,"utf-8"));

Printed binary data:

(2) You can also directly save the files uploaded by the client in the local server (do not read, save directly)
Note that the code above cannot be used to read and then save

//Understand: getSubmittedFileName is the name of the uploaded file
//Note: if this file already exists in this path, an error will be reported
head.write("D://"+head.getSubmittedFileName());

After success, you will find the picture just saved in the corresponding directory

4.getInputStream

Get the data of the request body (which is included in the input stream). No matter what format, it can be obtained as long as it is in the body
It's just a form format. It's not necessary to use this method to get it (troublesome, you have to parse multiple groups of key value pairs inside)
Common scenarios: json format

Front end code:

<body>
    <h3>ajax Submit json format</h3>
    <input type="text" id="ajax_username" placeholder="enter one user name">
    <br>
    <input type="password" id="ajax_password" placeholder="Input password">
    <br>

    <button onclick="ajaxSubmit()">Submit</button>
</body>
<script>
    function ajaxSubmit(){
        let username = document.querySelector("#ajax_username");
        let password = document.querySelector("#ajax_password");
        let json = {
            username: username.value,//The key is username and the value is the value attribute of the object
            password: password.value,

        };
        ajax({
            url: "ajax-json-servlet",
            method: "post",
            //String in json format on body
            contentType: "application/json",
            //JSON.stringify serializes a json object into a string in json format
            body: JSON.stringify(json),
            callback: function(status,resp){
                alert("Back end returned content: "+resp);
            },
        });
    }
    //ajax functions encapsulated earlier
    function ajax(args){//var ajax = function(){}
        let xhr = new XMLHttpRequest();
        //Set callback function
        xhr.onreadystatechange = function(){
            //4: Callback after the client receives the response
            if(xhr.readyState == 4){
                // The callback function may need to use the content of the response as an incoming parameter
                args.callback(xhr.status,xhr.responseText);
            }
        }
        xhr.open(args.method,args.url);
        // If the content type attribute has content in args, set the content type request header
        if(args.contentType){//js, in addition to judging the boolean value, you can also judge strings, objects, etc. if there is a value, it is true
            xhr.setRequestHeader("Content-Type",args.contentType);
        }
        //If the body request body is set in args, call send(body)
        if(args.body){
            xhr.send(args.body);
        }else{//If not set, call send()
            xhr.send();
        }
    }
</script>

Backend code:

@WebServlet("/ajax-json-servlet")
public class AjaxJsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//Get the request body data and set the code first
        //json is a typical scenario using this api
        InputStream is = req.getInputStream();
        //The length of the body has been identified in the content length of the request header
        int len = req.getContentLength();//It can also be obtained through getheader ("content length"), but the returned string is relatively troublesome
        byte[] bytes = new byte[len];
        is.read(bytes);
        System.out.println("Acquired json data: "+new String(bytes,"utf-8"));
    }
}

Back end output result:

fiddler packet capture display:

In fact, it is not convenient for us to get the whole json string. For example, we need to judge whether the account password is correct

Common methods: using a third-party library, you can convert a json string into a java object and a java object into a json string (useful when responding)

Front end code:

@WebServlet("/ajax-json-servlet")
public class AjaxJsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        InputStream is = req.getInputStream();
        User user = mapper.readValue(is,User.class);
        System.out.println("Acquired json String converted user object: "+user);
    }

    //Static inner class: it is contained in two classes {} and used the same as ordinary classes
    //To convert a json string into a java object, the name of a key needs to be the same as the name of a member variable (as well as the type)
    static class User{
        private String username;
        private String password;

        @Override
        public String toString() {
            return "User{" +
                    "username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }

        //Then provide getter and setter methods
        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;
        }
    }
}

Back end output:

Generally, the json string is converted to a user-defined type, but it should be noted that the key in json must have the corresponding member variable name in the java type, otherwise an error will be reported

Keywords: Java Front-end Web Development http

Added by blacksharkmedia on Wed, 23 Feb 2022 11:57:16 +0200