1.最简单的方式(注解法)
@Autowired private HttpServletRequest request;
2.最麻烦
a. 在web.xml中配置一个监听
<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>
b.之后在程序里可以用
//request: HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); //request: ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest(); //response: ServletWebRequest servletWebRequest = (ServletWebRequest) RequestContextHolder.getRequestAttributes(); HttpServletResponse response= servletWebRequest.getResponse();
3.最直接的方法
public String hello(HttpServletRequest request,HttpServletResponse response)
4.方法里获得
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
spring获得servletContext
//servletContext: WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContext servletContext = webApplicationContext.getServletContext();
Struts2中获取request对象
HttpServletRequest request = ServletActionContext.getRequest();