HttpServletRequest和HttpServletResponse
这篇文章很奇怪,并不是这个知识点有多重要,更重要的还是让我自己感受到学习一点东西,先动手搜索再去动手做,不要总是一直在搜,然后迷失在各种各样的讲解中,当感受到迷惑的时候,不如动起手来敲两行代码来的划算。就像我们在做测试的时候,很多问题是在逐渐深入测试的时候才发现的场景,测试用例是无法覆盖所有的测试场景的,只有在动手测试的时候去发散去深入,才能更好的减少bug。废话说的有点多,来,开偷,因为我在一篇博客上看到了一个很好的图。
HttpServletRequest,request对象时请求对象,在客户端向服务器请求一次就创建一个request对象,并且存储了请求的信息。所以在表单进行提交时,我们可以通过request对象获取用户提交的信息。HttpServletResponse,在Servlet中,当用户发出请求后,接下来就是需要响应,而响应用另一个对象Response对象。
注意:是表单请求
接下来我们实验一下
package com.newcrud.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
@RestController
@RequestMapping("/request")
public class MyRequestController {
@RequestMapping(value = "/my3",method = RequestMethod.POST)
public void getUserByUserName3(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
HttpSession session=httpServletRequest.getSession();
System.out.println(session);
String name = httpServletRequest.getParameter("username");
System.out.println(name);
httpServletRequest.setCharacterEncoding("UTF-8");
String[] name2 = httpServletRequest.getParameterValues("username");
System.out.println(Arrays.toString(name2));
System.out.println(httpServletRequest.getMethod());
httpServletResponse.setHeader("hello","world");
httpServletResponse.setStatus(500);
}
}
使用非表单请求
再来看一下SpringBoot的日志,并没有获取到传递的参数
org.apache.catalina.session.StandardSessionFacade@797c73ba
null
null
POST
使用表单请求
再来看一下使用form-data来请求的日志,发现是可以获取到参数的。
org.apache.catalina.session.StandardSessionFacade@797c73ba
zhangsan
[zhangsan]
POST
我的粗略见解
HttpServletRequest类比成@PathVariable、@RequestBody、@RequestParam,都可以用来获取用户请求的参数的。但是却又更强大,比如说防止盗链的功能,后面的三个注解并没有办法完成。