Spring可以在OPTIONS方法上自动生成"允许"标题吗?

che*_*tts 6 java spring spring-mvc http-options-method

当我RequestMapping在Spring MVC中配置我的s时,我想Allow在使用该OPTIONS方法时自动生成正确的头.

例如,使用此控制器:

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.GET)
    ResponseEntity<String> getTest() {
        return new ResponseEntity<>("test", HttpStatus.OK);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我OPTIONS对该URL 发出请求,我会得到405,方法不允许.相反,我希望它能自动回复

Allow: GET, OPTIONS204 - No content

我有一个想法添加拦截器,如下所示:

@Override 
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new HandlerInterceptor() {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if("OPTIONS".equalsIgnoreCase(request.getMethod())){
                response.setHeader("Allow", "GET, OPTIONS");
                response.setStatus(204);
                //TODO figure out the @Controller and what possible methods exist
                return false;
            }
            return true;
        }
        //Deleted excess methods for brevity
    });
}
Run Code Online (Sandbox Code Playgroud)

没有我编写自定义拦截器,这个功能是否存在?如果没有,我如何解决TODO并查找OPTIONS调用发生在同一URL上的注释?

che*_*tts 5

延伸Sotiros和jhadesdev的答案.如果使用Java Config(如在Spring Boot中),您可以通过配置如下配置DispatchServlet来启用OPTIONS请求@Bean:

@Bean
public DispatcherServlet dispatcherServlet() {
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.setDispatchOptionsRequest(true);
    return servlet;
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个静态助手,接受HttpMethods varargs,如下所示:

public static ResponseEntity<Void> allows(HttpMethod... methods) {
    HttpHeaders headers = new HttpHeaders();
    Set<HttpMethod> allow = new HashSet<>();
    for(HttpMethod method: methods){
        allow.add(method);
    }
    headers.setAllow(allow);

    return new ResponseEntity<>(headers, HttpStatus.NO_CONTENT);
}
Run Code Online (Sandbox Code Playgroud)

这使得创建我自己的OPTIONS映射变得如此简单:

@RequestMapping(method = RequestMethod.OPTIONS)
ResponseEntity<Void> getProposalsOptions() {
    return allows(HttpMethod.GET, HttpMethod.OPTIONS);
}
Run Code Online (Sandbox Code Playgroud)

虽然我认为Spring MVC可以OPTIONS自动提供响应,但你不能通过一个Interceptor,但可能通过自定义DispatcherServlet.

编写自己的OPTIONS响应的好处是,OPTIONS在某些情况下根据用户的角色定制是有意义的.例如,API的未经身份验证的用户可能会收到,Allow GET, OPTIONS但管理员会获得完整的API Allow GET, PUT, DELETE, OPTIONS您可以根据在OPTIONS拨打电话时检查用户的角色来自定义响应.