在Spring Boot应用程序中禁用HTTP OPTIONS方法 [英] Disable HTTP OPTIONS method in spring boot application

查看:1463
本文介绍了在Spring Boot应用程序中禁用HTTP OPTIONS方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在spring boot应用程序上开发了rest API.API仅接受GET和POST,但是在使用OPTIONS方法请求时,API会响应200状态(而不是405).我用谷歌搜索了这个问题,但是没有一个解决方案是基于springboot的.

I had developed rest API on spring boot application. The APIs accept only GET , and POST , but on requesting using OPTIONS method , API responding 200 status (instead of 405). I googled this issue , but none of the solution was springboot based .

响应:

Allow: OPTIONS, TRACE, GET, HEAD, POST
Public: OPTIONS, TRACE, GET, HEAD, POST

需要禁用OPTIONS方法.

Need to disable OPTIONS method.

推荐答案

先前的答案仅适用于tomcat,因此添加我的也是.您可以通过例如使用标准的servlet过滤器来禁用方法交叉容器:

Previous answer is for tomcat only, so adding mine as well. You can disable the method cross-container by, for example, using a standard servlet filter:

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); 
        } 
    }
} 

注意:假设此类由Spring组成.如果没有,您可以使用其他注册方法,详情请参见在此处.

Note: it is assumed that this class is componentscanned by Spring. If not, you can use other registration methods as detailed in here.

这篇关于在Spring Boot应用程序中禁用HTTP OPTIONS方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆