springmvc中获取request或者response的三种方式
程序员文章站
2022-04-23 16:54:08
...
方式一:在参数中直接获取,如下
@RequestMapping("/test") @ResponseBody public void saveTest(HttpServletRequest req, HttpServletResponse resp){ }
方式二:通过加入监听器,在任何地方通过RequestContextHodler获取,如下
1、在web.xml中添加监听,如下
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
2、在代码通过如下方式获取:
HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
方式三:使用注解方法注入,如下
@Autowired private HttpServletRequest requset; @Autowired private HttpServletResponse response;