When I configure my RequestMapping
s in Spring MVC, I'd like to automatically generate the proper Allow
header when the OPTIONS
method is used.
For example, with this controller:
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.GET)
ResponseEntity<String> getTest() {
return new ResponseEntity<>("test", HttpStatus.OK);
}
}
Right now if I do an OPTIONS
request to that URL I get a 405, method not allowed. Instead I'd like it to automatically respond with
Allow: GET, OPTIONS
and 204 - No content
I've got one idea adding an interceptor like so:
@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
});
}
Does this functionality exist without me writing a custom interceptor? If not, how might I solve the TODO
and lookup what annotations exist on the same URL the OPTIONS
call had happened on?
@RequestMapping
doesn't exist so the interceptor only passed through the/error
URL – Transvestite