1. 程式人生 > >如何在 Springboot 獲取 http request和 http response 的幾種方式

如何在 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
}