SpringBoot获取Request和Response

使用 Springboot,我们很多时候直接使用@PathVariable、@RequestParam、@Param 来获取参数,但是偶尔还是要用到 request 和 response,怎么获取呢?

有三种方式可以获取, 任选其一就行, 建议第三种

通过静态方法获取

此方法可避免 aop 对 response.getWriter() 的调用, 导致流被打开

1
2
3
4
5
6
7
@GetMapping(value = "")
public String center() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
HttpServletResponse response = servletRequestAttributes.getResponse();
//...
}

通过绑定参数获取

使用此方法 SpringBoot 会帮你做参数绑定

1
2
3
4
@GetMapping(value = "")
public String center(HttpServletRequest request,HttpServletResponse response) {
//...
}

注入到类中

1
2
3
4
5
6
7
8
9
10
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

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