HttpServletRequest core method and get request parameters

1. Show some important methods in HttpServletRequest

When Tomcat reads the HTTP request (string) through the Socket API, and parses the string into an HttpServletRequest object according to the format of the HTTP protocol.

Create a ShowRequest class

@WebServlet("/ShowRequest")
public class ShowRequest extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    
        StringBuilder stringBuilder = new StringBuilder();
        // 返回请求协议的名称和版本号
        stringBuilder.append(req.getProtocol()); // 协议名称: HTTP  版本号: 1.1
        stringBuilder.append("\n");
//        stringBuilder.append("<br>");

        // 放回请求的HTTP方法名称
        stringBuilder.append(req.getMethod()); // GET
        stringBuilder.append("\n");
//        stringBuilder.append("<br>");

        // 从协议名称知道HTTP请求的第一行的查询字符串中, 返回该请求的URL的一部分
        stringBuilder.append(req.getRequestURI()); // /3010/ShowRequest
        stringBuilder.append("\n");
//        stringBuilder.append("<br>");

        stringBuilder.append(req.getRequestURL()); // 返回整个地址 http://127.0.0.1:8080/0310/ShowRequest
//        stringBuilder.append("<br>");
        stringBuilder.append("\n");

        // 返回指示请求上下文的请求URI部分
        stringBuilder.append(req.getContextPath()); // /3010 -
        stringBuilder.append("\n");
//        stringBuilder.append("<br>");

        // 返回包含路径后的请求URL中的查询字符串
        stringBuilder.append(req.getQueryString()); // null 没有QueryString
        stringBuilder.append("\n");
//        stringBuilder.append("<br>");

        // 把请求的header 拼接
        // 获取到所有的headerNames
        // 枚举
        Enumeration<String> headerNames = req.getHeaderNames();
        // has XXX 判断是否有下一个
        while(headerNames.hasMoreElements()) {
    
    
            // 遍历获取到每一个header的name值
            String name = headerNames.nextElement(); // next XXX获取下一个
            // 查询header中name对应的值
            String value = req.getHeader(name);
            stringBuilder.append(name + ", " + value);
            stringBuilder.append("\n");

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

Deploy the program through smart Tomcat and access it through the URL http://127.0.0.1:8080/0310/ShowRequest in the browser, you can see the following results:

insert image description here
Since the QueryString is not set when the request is passed in, the QueryString obtained here is null

In addition, it should be noted that the newline character "\n" we set here does not always take effect correctly. At this time, because we have not set an accurate corresponding format, the browser will "guess" the response at this time when loading What type of text is it, here it is just considered to be text/plain, which can read newlines correctly.

If the response format is set to text/html, the "\n" line break will not be parsed normally

insert image description here

![Insert picture description here](https://img-blog.csdnimg.cn/6f60b9e0e02046858abc7ff58945531c.png

When changing to the newline tag corresponding to html
, the newline tag can be recognized normally

insert image description here
Therefore, when accessing through a browser, you should actively set setCOntentType("type", charset="utf8") to tell the browser what type and encoding method to parse

2. Get the parameters in the GET request

Create a GetParameterServlet class, assuming that the browser request is as follows
?studentID=10&studentName=Zhang San

@WebServlet("/getParameter")
public class GetParameterServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		String studentId = req.getParameter("studentId");
        // getparameter会自动针对urlencode 的结果进行处理
        String studentName = req.getParameter("studentName");
        System.out.println(studentId);
        System.out.println(studentName);
        resp.getWriter().write(studentId + ", " + studentName);
}

Run smart Tomcat and access the URL path through the web page as http://127.0.0.1:8080/0310/getParameter?studentId=10&studentName=Zhang San

insert image description here
In the idea window, "Zhang San" has no garbled characters

insert image description here

It means that there is a problem with the browser's parsing of QueryString at this time. The browser's parsing of urlencode is incorrect. You need to manually set the response format and tell the browser how to parse it.

insert image description here
insert image description hereWhen the response format is set, the browser can correctly identify

3. Get the parameters in the post request

In the GetParameter class just created, override the dopost method and build the request

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 通过 body 获取, 发送一个post请求
        // 预期请求的 body 里为 studentId = 10&studentName = 张三
        // 请求设置请求字符集 告诉 servlet(Tomcat)  该如何解析
        req.setCharacterEncoding("utf8");

        String studentId = req.getParameter("studentId");
        String studentName = req.getParameter("studentName");
        System.out.println(studentId);
        System.out.println(studentName);
        
        // 设置浏览器响应格式 告诉浏览器该如何解析
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(studentId + "," + studentName);
    }

Send a post request to observe the result through postman, and
insert image description here
the result is returned on the idea

insert image description here

Use fiddler to observe the packet capture results

insert image description here

4. Get the body in the post request passed in json format

Create a new class JacksonServlet and override the dopost method

Introduce Jackson dependency in the central warehouse ( central warehouse address )

insert image description here

Copy the content under maven to the pom.xml file

<!--      引入 jackson 依赖   -->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.4.1</version>
        </dependency>

Write code

class Student {
    
    

    // 这个类里的属性必须是public 或者带有 public 的getter / setter 否则json无法访问
    public int studentId;
    public String studentName;
    // 所构造的对象必须是 body 里构造的相同(名字与类型都应相同)

    // 里面的构造方法不写即为无参版本构造器 且必须为无参版本

}

@WebServlet("/json")
public class JacksonServlet extends HolleServlet{
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 从请求 body 里面获取一些参数
        // 例如格式为 {"studentId": 10 , "studentName" : 张三 }

        // 一个重要类
        ObjectMapper objectMapper = new ObjectMapper();

        // 第一个参数可以使字符串 也可以是输入流 第二个参数是一个类对象即为要解析的结果的类对象
        Student s = objectMapper.readValue(req.getInputStream(), Student.class);
                                                                 // 类对象可以解析到类里的属性
        // 1.读取输入流, 获取到需要解析的字符串
        // 2. 把字符串按照json格式解析, 得到一组键值对
        // 3. 根据类对象创建一个实例
        // 4. 遍历类对象中的属性的名字, 拿着名字去键值对中查询, 查到的value就赋值到对应的对象属性中
        // 5. 返回这个构造完成的对象

        System.out.println(s.studentId);
        System.out.println(s.studentName);

        // 两个重要方法 readValue方法, 把 json 格式数据转成 java 的对象
        // writerValueAsString方法, 把 java 对象转为 json 格式的字符串
        
        // 设置 响应时, 浏览器按照 json 格式解析
        resp.setContentType("application/json; charset=utf8");
        // 先把s对象转为json格式字符串在转为流对象
        resp.getWriter().write(objectMapper.writeValueAsString(s));

    }

}

Use postman to build a post request with a body of json

insert image description here
Response received in idea

insert image description here

Use fiddler to capture the package as follows

insert image description here

Guess you like

Origin blog.csdn.net/qq_68288689/article/details/129485052