1. 通过静态方法获取
1
2
3
4
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

HttpServletRequest request = servletRequestAttributes.getRequest();
HttpServletResponse response = servletRequestAttributes.getResponse();
  1. 通过参数直接获取,在方法上加上参数,Springboot就会自动绑定,可以直接使用。
    如果有多个参数,把这两个加到后面即可。
1
2
3
4
@GetMapping(value = "/test")
public String test(String str,
HttpServletRequest request,HttpServletResponse response) {
}
  1. 注入到类,这样就不用每个方法都写了
1
2
3
4
5
6
7
8
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;

@GetMapping(value = "/test")
public String test() {
}