springMVC获取request和response (2014-12-06 12:32:27)转载▼
分类: springMVC
1.参数
例如:
@RequestMapping(“/test”) @ResponseBody public void saveTest(HttpServletRequest req, HttpServletResponse resp){ } 这样的话如果要用ajax每次都要将response作为参数传递,不方便使用
2.加入监听器,然后再controller里面获取
(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(); 这种我试了会报类型转换错误,获取到的response为null,获取是哪里写错了
3.注解(现在用的) 在BaseController中加入:
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
@ModelAttribute
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
this.request = request;
this.response = response;
this.session = request.getSession();
}
说明:ModelAttribute的作用
1)放置在方法的形参上:表示引用Model中的数据
2)放置在方法上面:表示请求该类的每个Action前都会首先执行它,也可以将一些准备数据的操作放置在该方法里面。