MockHttpServletRequest未将URL传递给链中的下一个过滤器

时间:2011-10-13 21:17:12

标签: servlets spring-mvc spring-security request

我正在尝试实现一个使用MockHttpServletRequest向请求对象添加标头的过滤器。我想使用该标头进行预身份验证。这是过滤器类..

public class MockAuthFilter implements Filter{

   private FilterConfig filterConfig = null;
   private static String loggedInUserName = "myId";
   private static String httpRequestHeaderName = "SM_ID";
   private Logger logger = Logger.getLogger(MockAuthFilter.class);

   @Override
   public void destroy() {
     this.filterConfig = null;
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

      if(this.filterConfig.getServletContext() == null){}

      HttpServletRequest httpRequest = (HttpServletRequest) request;        
      MockHttpServletRequest mRequest = new MockHttpServletRequest(this.filterConfig.getServletContext());
      if(mRequest.getHeader(httpRequestHeaderName)==null ||
            !mRequest.getHeader(httpRequestHeaderName).equalsIgnoreCase(loggedInUserName))
        mRequest.addHeader(httpRequestHeaderName, loggedInUserName);

      mRequest.setMethod("GET");
      mRequest.setRequestURI(httpRequest.getRequestURL().toString());
      logger.debug("**********************exiting doFilter() method*****************");
      chain.doFilter(mRequest, response);
     }

@Override
public void init(FilterConfig config) throws ServletException {
    this.filterConfig = config;
}

}

但是当请求到达Spring Security过滤器链中的下一个过滤器时,没有填充url。我在日志文件中看到以下行..

  [2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [com.app.filter.MockAuthFilter:doFilter:55] - **********************exiting doFilter() method*****************
  [2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [com.app.filter.MockAuthFilter:doFilter:55] - **********************exiting doFilter() method*****************
  [2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [org.springframework.security.web.util.AntPathRequestMatcher:matches:103] - Checking match of request : ''; against '/static/**'
   [2011-10-13 16:52:35,114] [DEBUG] [http-8080-1][org.springframework.security.web.util.AntPathRequestMatcher:matches:103] - Checking match of request : ''; against '/static/**'

正如您所看到的,请求对象中没有传递给AntPathrequestMatcher的匹配方法的URL。 我在chain.doFilter()方法之前检查了mockrequest对象,它在requestURI字段中包含url值。如果这里的URI和URL不一样,我应该在这里做些什么更改,以便在请求对象中维护url ..

1 个答案:

答案 0 :(得分:2)

  1. 不要那样使用MockHttpServletRequest。它用于测试,而不是用于生产代码。在过滤器中包装请求和/或响应以便稍后修改其行为的适当方法是使用HttpServletRequestWrapperHttpServletResponseWrapper
  2. 如果您只想添加标题,为什么还要尝试换行或删除原始请求?只需在传入请求中使用addHeader()
  3. 尝试更改请求方法并在过滤器中请求URI时可能会产生意外后果,并且几乎肯定不会按照您的预期执行操作。当请求到达您的过滤器时,已根据请求的原始状态构建过滤器链。现在改变它不会影响它最终的结果。