一尘不染

如何在Spring Boot中处理HTTP OPTIONS请求?

spring

看来我应该这样做:

通过将其设置为dispatchOptionsRequest来配置dispatcherServlet true

但是,考虑到我没有XML配置,或者DispatcherServlet代码中没有任何各种初始化程序类(此答案提到),该怎么做?

在一个@RestController类中,我有一个像这样的方法,当前不会被调用。

@RequestMapping(value = "/foo", method = RequestMethod.OPTIONS)
public ResponseEntity options(HttpServletResponse response) {
    log.info("OPTIONS /foo called");
    response.setHeader("Allow", "HEAD,GET,PUT,OPTIONS");
    return new ResponseEntity(HttpStatus.OK);
}

Spring Boot 1.2.7.RELEASE; 一个简单的设置与Spring REST指南并没有太大区别 。


阅读 2010

收藏
2020-04-14

共1个答案

一尘不染

选项1:Spring Boot属性(仅适用于Spring Boot 1.3.0+)
从Spring Boot 1.3.0开始,可以使用以下属性配置此行为:

spring.mvc.dispatch-options-request=true

选项2:自定义 DispatcherServlet
DispatcherServlet在Spring Boot中由定义DispatcherServletAutoConfiguration。你可以DispatcherServlet在配置类中的某个位置创建自己的bean,而不是在自动配置中使用它:

@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setDispatchOptionsRequest(true);
    return dispatcherServlet;
}

但是请注意,定义你的DispatcherServletbean将禁用自动配置,因此你应该手动定义在autoconfiguration类中声明的其他bean,即ServletRegistrationBeanfor DispatcherServlet

选项3: BeanPostProcessor

你可以创建BeanPostProcessor将bean初始化之前将dispatchOptionsRequest属性设置为的实现true。Yoy可以将其放在你的配置类中:

@Bean
public DispatcherServletBeanPostProcessor dispatcherServletBeanPostProcessor() {
    return new DispatcherServletBeanPostProcessor();
}

public static class DispatcherServletBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DispatcherServlet) {
            ((DispatcherServlet) bean).setDispatchOptionsRequest(true);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

选项4: SpringBootServletInitializer

如果你有SpringBootServletInitializer应用程序,则可以执行以下操作来启用OPTIONS调度:

public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.getServletRegistration(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
                .setInitParameter("dispatchOptionsRequest", "true");
    }
}

但是,这仅在将应用程序作为WAR部署到Servlet容器中时才有效,因为SpringBootServletInitializer使用main方法运行Spring Boot应用程序时不会执行代码。

2020-04-14