Servlet API get request data

1. The way of constructing HTTP request

1.1 Use Postman to construct requests
import javax.jws.WebService;
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.net.HttpCookie;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: snutyx
 * Date: 2023-03-19
 * Time: 17:07
 */
@WebServlet("/method")
public class MethodServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("doGet()");
        resp.getWriter().write("doGet()");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("doPost");
        resp.getWriter().write("doPost()");
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("doPut()");
        resp.getWriter().write("doPut()");
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("doDelete()");
        resp.getWriter().write("doDelete()");

    }
}

  • Start the tomcat server

image-20230319172429104

  • The startup is successful, and the construction request
    • Construct get request

image-20230319172524204

return response

image-20230319172553288

image-20230319172621476

image-20230319172635839

image-20230319172650911

image-20230319172708936

image-20230319172731520

image-20230319172745826

Postman is a very useful tool for us in the backend development process. The backend mainly implements some http interfaces in the company. The frontend sends corresponding requests, and the backend is verified and tested through postman.

1.2 Use ajax to construct requests
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- 使用这个页面来构造 ajax 请求 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>
        $.ajax({
      
      
            type:'get',
            //相对路径的写法 : url : 'method',
            //绝对路径的写法 :
            url: '/hello_servlet/method',
            success:function(body,status){
      
      
                console.log(body);
            }
        });
    </script>
</body>
</html>

image-20230319174930761

image-20230319174952915

Similarly, to construct a post request, you only need to modify the corresponding type.

When writing tomcat code, every modification requires restarting the server

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- 使用这个页面来构造 ajax 请求 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>
        $.ajax({
      
      
            type:'post',
            //相对路径的写法 : url : 'method',
            //绝对路径的写法 :
            url: '/hello_servlet/method',
            success:function(body,status){
      
      
                console.log(body);
            }
        });
    </script>
</body>
</html>

image-20230319175057815

image-20230319175113387

二 . HttpServletRequest API

  • common method
method describe
String getProtocol() Returns the name and version of the requested protocol.
String getMethod() Returns the name of the HTTP method of the request, for example, GET, POST, or PUT.
String getRequestURI() From the protocol name up to the query string of the first line of an HTTP request, returns the portion of the request's URL.
String getContextPath() Returns the portion of the request URI that indicates the request context.
String getQueryString() Returns the query string contained in the request URL following the path.
Enumeration getParameterNames() Returns an enumeration of String objects containing the names of the parameters included in this request.
String getParameter(String name) Returns the value of the request parameter as a string, or null if the parameter does not exist.
String[] getParameterValues(String name) Returns an array of String objects containing the values ​​of all the given request parameters, or null if the parameter does not exist.
Enumeration getHeaderNames() Returns an enum containing all header names included in this request.
String getHeader(String name) Returns the value of the specified request header as a string.
String getCharacterEncoding() Returns the name of the character encoding used in the request body.
String getContentType() Returns the MIME type of the request body, or null if the type is not known.
int getContentLength() Returns the length of the request body in bytes, provided the input stream, or -1 if the length is unknown.
InputStream getInputStream() Used to read the body content of the request. Returns an InputStream object.

Use the HttpServletRequest API to simply get the content of an HTTP request

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.util.Enumeration;

/**
 * 测试 HttpServlet 中的相关 api 
 */
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 这里是设置响应的 content-type. 告诉浏览器, 响应 body 里的数据格式是啥样的.
        resp.setContentType("text/html");

        // 搞个 StringBuilder, 把这些 api 的结果拼起来, 统一写回到响应中.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(req.getProtocol());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());
        stringBuilder.append("<br>");
        stringBuilder.append("<br>");
        stringBuilder.append("<br>");
        stringBuilder.append("<br>");

        // 获取到 header 中所有的键值对
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
    
    
            String headerName = headerNames.nextElement();
            stringBuilder.append(headerName + ": " + req.getHeader(headerName));
            stringBuilder.append("<br>");
        }

        resp.getWriter().write(stringBuilder.toString());
    }
}

Response result:

image-20230319182056724

Use api to realize front-end and back-end interaction

image-20230319184957393

Using the getParameter() method, you can get the key-value pairs in the query string in the GET request, and you can also get the key-value pairs in the body constructed by the form form in the POST request

1. Pass the query string via GET request

Pass the data, studentId and classId to the backend through the frontend

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;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: snutyx
 * Date: 2023-03-19
 * Time: 18:43
 */
@WebServlet("/getParameter")
public class GetParameterServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 预期浏览器会发一个形如 /getParameter?studentId=10&classId=20 请求.
        // 借助 req 里的 getParameter 方法就能拿到 query string 中的键值对内容了.
        // getParameter 得到的是 String 类型的结果.
        String studentId = req.getParameter("studentId");
        String classId = req.getParameter("classId");
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write("学生ID = "+studentId+"班级ID = "+ classId);
    }
}

When the querystring of the set url is empty:

image-20230319185151461

When query string is not empty

image-20230319185341047

The query string key-value pair here will be automatically processed by tomcat into a Map structure, and the value can be obtained through the key at any time later. If the key does not exist in the query string, null will be returned.

2. POST request form form parameter (body)
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- 这里的 action 指的是路径,规定当提交表单时向何处发送表单数据。
               method 规定用于发送 form-data 的 HTTP 方法 -->
    <form action="postParameter" method="post">
        <input type="text" name="studentId">
        <input type="text" name="classId">
        <input type="submit" value="提交">
    </form>
</body>
</html>

image-20230319191153084

At this time, after clicking submit, a post request is constructed. The body of the post request is the content in the form. At this time, the request message can be completely displayed by capturing the packet with Fiddler

Because we have not written postParameter at this time, the page at this time displays 404

image-20230319192149460

image-20230319192234209

The action in the form determines the path, the method determines the type of the http request, the name in the input determines the key in the key-value pair in the body, and the submitted content determines the value in the key-value pair in the body;

image-20230319192715518

Content-type determines that this is a request composed of a form form.

Backend PostParameter code:

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;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: snutyx
 * Date: 2023-03-19
 * Time: 19:29
 */
@WebServlet("/postParameter")
public class PostParameterServlet  extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String studentId = req.getParameter("studentId");
        String classId = req.getParameter("classId");
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write("学生Id = "+ studentId+"班级Id = "+ classId);
    }
}

image-20230319193653258

3. The data transfer parameter (body) of the JSON format of the Post request

JSON is a very mainstream data format, and it is also a key-value pair structure. Get the requested stream object by using getInputStream(), then store the stream object in a byte array, and finally construct it into a string and print it out.

import sun.awt.windows.WBufferStrategy;

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.InputStream;

@WebServlet("/postparameter2")
public class PostParameter2Servlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        此方法用来处理 body 为 json 格式的数据。
//        直接把 req 对象里的 body  完整的读取出来
//        使用 getInputStream 来获取 body 的内容并返回一个流对象
//        流对象中的字节数目取决于 content-length
          int length = req.getContentLength();
          byte[] buffer = new byte[length];
//      读取操作
        InputStream inputStream = req.getInputStream();
//        读取到的字节传入 buffer  数组当中
        inputStream.read(buffer);
//        把字节数组构造成 string 打印出来
        String body = new String(buffer,0,length,"utf8");
        System.out.println("body =  "+body);
        resp.getWriter().write(body);
    }
}

Here we can use ajax to construct the request, and we can also use postman to construct the request, process the json format in the body of the post request, and finally return the response.

  • Use the postman structure to specify the post request, and the body is the json data

image-20230404195552816

Use fiddler to capture packets, and the format of the obtained request message is as follows

The request arrives at tomcat, and tomcat parses it into a req object. In the servlet code, req.getInputStream() reads the content of the body, converts the content of the body into a string, writes it into the body of the response, and returns it to the client, which is displayed in the browser.

The console prints the content of the body and returns a response to the client (postman)

image-20230404201609281

image-20230404201508914

There are some differences between using data in json format and passing parameters in form form, but the three methods are basically equivalent.

//form 表单传参
studentId=20 && classId=10
//json 格式的传参
{
    
    
   "studentId" : 20,
   "classId" : 10
}

However, when transferring data through json, the server only reads out the entire body, and does not process it in the way of key-value pairs, and cannot obtain value through key. The form form can obtain value through key. At this time, it is necessary to introduce the first Three libraries to parse the json format, such as jackson, gson, etc.

  • Introduce jackson to parse json format

Introduce third-party libraries through maven, search for jackson in the central warehouse, and find Jackson DataBind

image-20230404203455410

Select the appropriate version, here we choose 2.14.1

image-20230404203701606

Copy the following content between the pom.xml and the structure, and then perform a manual refresh, waiting for loading and configuration.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>

After the configuration is complete, rewrite the relevant code of the server,

import com.fasterxml.jackson.databind.ObjectMapper;
import sun.awt.windows.WBufferStrategy;

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.InputStream;
// 创建一个 student 类 , 属性名字需要和 json 中的key 一致
// 也可以写为  private ,但是需要提供 getter and setter 方法	
class Student{
    
    
    public int studentId;
    public int classId;
}

@WebServlet("/postparameter2")
public class PostParameter2Servlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
y);
//         使用 jackson 涉及到的核心对象 。
        ObjectMapper objectMapper = new ObjectMapper();
//         readvalue  就是把一个json 格式的字符串转化为 Java 对象
        Student student = objectMapper.readValue(req.getInputStream(),Student.class);
        System.out.println(student.studentId+ "," + student.classId);

//        返回响应
        resp.getWriter().write("studentId: "+student.studentId+","+"classId: "+student.classId);

    }
}

The core code of the above code is to convert a string in json format into a java object and give it relevant properties.

image-20230405100953380

  • Use req.getInputStream () to get the string in json format
  • Create a student instance based on the second parameter object.
  • Through this class object, the Student object can be constructed by means of the reflection mechanism inside readValue, and the string on the tree can be processed into a map key-value pair structure.
  • Traverse all key-value pairs, and assign the corresponding value to the corresponding field of the student according to the name of the key in the key-value pair
  • Return the student instance

Use the postman construct to specify a post request

image-20230405103605795

The console prints student related attributes

image-20230405103827797

The response is successful, and the value of value is obtained through key

image-20230405103735409

What happens if the properties in the json format are not included in the implementing class?

The response is as follows: Server-side parse error because there is an undefined property.

image-20230405143413767

Guess you like

Origin blog.csdn.net/m0_56361048/article/details/130759973