问题描述
我参考网上这个做法<listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener>ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = reqAttr.getRequest();不能获取request,报的是reqAttr的空指针,我是在我的filter里面用的 问题补充:补充一下,框架应该用的spring mvc
解决方案
RequestContextListener按理说可以,如下是源码public class RequestContextListener implements ServletRequestListener {private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";public void requestInitialized(ServletRequestEvent requestEvent) {if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {throw new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest());}HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();ServletRequestAttributes attributes = new ServletRequestAttributes(request);request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);LocaleContextHolder.setLocale(request.getLocale());RequestContextHolder.setRequestAttributes(attributes);}你试试request.getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);能获取吗?实在不行试试org.springframework.web.filter.RequestContextFilter。