如何在 Springboot 获取 http request和 http response 的几种方式

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

也很方便,有三种方式可以获取,任选其一就行。

1、通过静态方法获取,你也可以封装一个静态方法出来

@GetMapping(value = "")
public String center() {
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = servletRequestAttributes.getRequest();
    HttpServletResponse response = servletRequestAttributes.getResponse();
    //...
}

2、通过参数直接获取,只要在你的方法上加上参数,Springboot就会帮你绑定,你可以直接使用。如果你的方法有其他参数,把这两个加到后面即可。

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

3、注入到类,这样就不用每个方法都写了

@Autowired
private HttpServletRequest myHttpRequest;

@Autowired
private HttpServletResponse myHttpResponse;

@GetMapping(value = "")
public String center() {
    //refer to myHttpRequest or myHttpResponse
}

 

转自:https://www.jianshu.com/p/b1a9fb969d9a

 

你可能感兴趣的:(java,springboot)