SpringMVC 中在任意地方取得 HttpServletRequest
和 HttpServletResponse
在 web.xml 中注册
RequestContextListener
(SpringMVC 4 不需要这一步)1
2
3
4
5<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>获取
HttpServletRequest
和HttpServletResponse
1
2
3
4
5
6public static String testRequestAndResponse() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
return request.getParameter("name");
}