java后端请求过滤options方式,亲测有效

前端每次发出post 请求时,浏览器会默认请求2次,一次是options类型,一次是真实的请求,为了避免这种情况发生,需在后端过滤器中拦截下options请求,代码如下:

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class MethodFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getMethod().equals("OPTIONS")) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

配置文件中:

server:
  port: 8080
  tomcat:
    port-header: HEAD,PUT,DELETE,TRACE,COPY,SEARCH,PROPFIND

验证过其他方式,但是没有过滤成功,以上代码是测试通过的,特此记录。

你可能感兴趣的:(java,spring,boot,拦截options)