我在Spring引导中注册了一个Filter,并试图从请求中获取和Header,但获取null。

@Component
@Order(1)
public class ExampleFilter implements Filter {


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

         HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         //null**
         final String header = httpServletRequest.getHeader(HEADER);
     }




 @GetMapping(value = "example")
 public ResponseEntity<Example> example( @RequestHeader(HEADER) String header) {
      ... the header is NOT null
 }

最佳答案

请在这里检查我的例子

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomFilter implements Filter {

public CustomFilter() {
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Enumeration<String> headerNames = httpRequest.getHeaderNames();

    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            System.out.println("Header: " + name + " value:" + httpRequest.getHeader(name));
        }
    }


    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}
}

09-10 07:00
查看更多