原文 http://blog.csdn.net/z295304557/article/details/24771281
1.通过注解获取(很简单,推荐):
public class Hello {
@Autowired
HttpServletRequest request; //这里可以获取到request
}
2.在web.xml中配置一个监听:
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
java代码:
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
3.直接在参数中传递(此方法不好用,不建议使用):
public String hello(HttpServletRequest request)
4.如果有Struts:
HttpServletRequest request = ServletActionContext.getRequest();
我自己写了个BaseController控制器类,只要继承这个类的控制器都可以直接获取request和获取到参数
BaseController.java
package com.pzhu.jams.cmt.controller; import java.io.Serializable; import java.util.Enumeration; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.ModelAttribute; public class BaseController implements Serializable { private HashMap<Object,Object> params = new HashMap(); protected Logger logger = Logger.getLogger(BaseController.class); protected HttpServletRequest request; protected HttpServletResponse response; protected HttpSession session; @ModelAttribute public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) throws Exception{ this.request = request; this.response = response; this.session = request.getSession(); } public HashMap getParams() { params.clear(); Enumeration names = request.getParameterNames(); if(names != null){ while(names.hasMoreElements()){ String name = (String) names.nextElement(); String value = request.getParameter(name); params.put(name, value); } } HashMap ps = new HashMap<Object,Object>(params); params.clear(); return ps; } }
相当于是采用的第三种获取request的方法