方式一,在Contoler类绑定ModelAttribute注解
Java代码
Java代码
@ModelAttribute
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
方式二:在参数中直接获取,如下
Java代码
- @RequestMapping("/test")
- @ResponseBody
- public void saveTest(HttpServletRequest req, HttpServletResponse resp){
- }
方式三:通过加入监听器,在任何地方通过RequestContextHodler获取,如下
1、在web.xml中添加监听,如下
Java代码
- org.springframework.web.context.request.RequestContextListener
2、在代码通过如下方式获取:
Java代码
Java代码
- HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
- HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
3、也可通过注解方式获取:
Java代码
- @Autowired
- private HttpServletRequest requset;
- @Autowired
- private HttpServletResponse response;