得到HttpServletRequest的三种方式
方式一:Controller方法参数
在Controller的方法参数上写上HttpServletRequest,这样每次请求过来得到就是对应的HttpServletRequest。

@GetMapping(“/test”)
public void test(HttpServletRequest request) {}
方式二:从RequestContextHolder上下文获取
@GetMapping(“/test”)
public void test(HttpServletRequest request) {
// 从请求上下文里获取Request对象
ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.
cast(RequestContextHolder.getRequestAttributes());
HttpServletRequest contextRequest = requestAttributes.getRequest();

}
方式三:依赖注入@Autowired
@Autowired
HttpServletRequest req;

@GetMapping(“/test”)
public void test(HttpServletRequest request) {}

原文:https://blog.csdn.net/hzau_itdog/article/details/108851270

Comments are closed.

Post Navigation