赞
踩
SpringMVC框架中,获得request对象的几种方式
1.最简单的方式(注解法)
1
2
|
@Autowired
private
HttpServletRequest request;
|
2.最麻烦的方法
a.在web.xml中配置一个监听
<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>
b.之后再程序里可以用下面的代码来获得
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
3.最直接的方法
1
|
public
String hello(HttpServletRequest request,HttpServletResponse response)
|
springMVC4中获取request和response对象有以下两种简单易用的方法:
1、在control层获取
在control层中获取HttpServletRequest和HttpServletResponse对象有以下两种简单方式:
1)通过方法参数直接在action类中获取
- @Controller
- class Action{
- @RequestMapping("/path")
- public String getReqAndRes(HttpServletRequest request, HttpServletResponse response){
- /** 相关业务代码 此时可以直接使用request response对象 */
- }
- }
2)利用spring web提供的@ModelAttribute注解
@ModelAttribute放在类方法的参数前面表示引用Model中的数据
@ModelAttribute放在类方法上面则表示该Action类中的每个请求调用之前都会执行该方法,因此在此方法里面可以做一些请求预处理,利用此特性就可以抽象出一个基本Action类,然后所有的Action类都继承自这个基本Aciton类,在基本Action类里面获取相应的request、response、session对象:
- public class BaseAction{
-
- 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();
- }
-
- /** 其他业务代码 */
- }
-
- 2、通过spring提供的RequestContextHolder在非contrller层获取request和response对象
- HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
- HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
- HttpServletResponse response = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
- ServletContext context = ContextLoader.getCurrentWebApplicationContext().getServletContext();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。