springmvc获取HttpServletRequest对象
spring mvc在普通类中获取HttpServletRequest对象需要做2个步骤:
1、在web.xml文件中加如下配置
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener </listener-class>
</listener>
在RequestContextListener类中有如下代码,其中红色标注的为关键代码:
public class RequestContextListener implements ServletRequestListener {
...
...
...
public void requestInitialized(ServletRequestEvent requestEvent) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException("");
}
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(attributes);
}
...
...
...
}
public class ServletRequestAttributes extends AbstractRequestAttributes {
...
...
...
private final HttpServletRequest request;
...
...
...
/**
* Create a new ServletRequestAttributes instance for the given request.
* @param request current HTTP request
*/
public ServletRequestAttributes(HttpServletRequest request) {
Assert.notNull(request, "Request must not be null");
this.request = request;
}
}
2、在普通类中获取对象
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();