Spring Boot 获取 HttpServletRequest 的几种方式
Spring Boot About 789 words方法一
SpringMVC
会隐式注入HttpRequest
@RestController
public class TestController {
@GetMapping("/hello")
public String helloGetPathVariable(HttpServletRequest request) {
return "OK";
}
}
方法二
通过依赖注入。
@RestController
public class TestController {
@Autowired
private HttpServletRequest request;
@GetMapping("/hello")
public String helloGetPathVariable() {
return "OK";
}
}
方法三
RequestContextHolder
:Spring
封装的ThreadLocal
。
@RestController
public class TestController {
@GetMapping("/hello")
public String helloGetPathVariable() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
return "OK";
}
}
Views: 2,377 · Posted: 2022-10-14
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...