强制Spring在HEAD请求中返回状态200

时间:2016-09-29 07:28:06

标签: java spring controller servlet-filters

我需要制作一个能够捕获所有HEAD请求的过滤器,并在其上返回状态200。

正如我所做的那样,我需要创建一个过滤器来捕获每个HEAD请求,这样做就完成了,并且每次请求都会返回200,这是一个问题。

我的意思是过滤器捕获请求并能够使用它做一些事情,但我不需要请求,但是响应将是200.那么我还能做什么?

public class HttpHeadFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    if (isHttpHead(httpServletRequest)) {
        chain.doFilter(new ForceHeadToOkStatusWrapper (httpServletRequest), response);
    } else {
        chain.doFilter(request, response);
    }
}

public void destroy() {
}

private boolean isHttpHead(HttpServletRequest request) {
    return "HEAD".equals(request.getMethod());
}

private class ForceHeadToOkStatusWrapper extends HttpServletRequestWrapper {
    public ForceGetRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    //somethig here
}
}

1 个答案:

答案 0 :(得分:0)

最后,我创建了一个拦截器:

public class HttpHeadInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

      if (isHttpHead(request)) {
          response.setStatus(HttpStatus.SC_OK);
          return false;
      }
      return true;
  }

  private boolean isHttpHead(HttpServletRequest request) {
      return HttpMethod.HEAD.equals(request.getMethod());
  }

}

并将其添加到WebMvcConfigurerAdapter:

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new HttpHeadInterceptor());
}

它运作顺畅)