Spring

 how to disable http options method type in rest api's

praveen buya's profile image
praveen buya posted May 31, 2019 09:00 PM

i have a rest api of method type post , and if i am invoking that rest api with method type options i am not getting exception like 405 method not supported , it simply say 200 ok with no response body

Daniel Mikusa's profile image
Daniel Mikusa

Can you provide some more details? What version of Spring Boot are you using? How do you have your service app set up?

Daniel Mikusa's profile image
Daniel Mikusa

OK, so Spring Web will handle this for you by default. See the default behavior here.

 

https://docs.spring.io/spring/docs/4.3.24.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-head-options

 

If you want to customize how HTTP OPTIONS requests are handled, you can do that with the standard RequestMethod mapping and a method=RequestMethod.OPTIONS. For example, you could set a custom response status code or define a custom way to set the header.

 

Ex:

@Controller @RequestMapping("/") public class WebController {   @RequestMapping(method = RequestMethod.GET) @ResponseBody public String index() { return "Hello World!\n"; } @RequestMapping(method = RequestMethod.OPTIONS) public void options(HttpServletResponse resp) throws IOException { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } }

This is *not* defined across your app though. If you want to customize across the whole app you can add a filter like this.

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

The @Component will make this a bean & because it implements the Servlet Filter interface Spring Boot will automatically enable the filter for you.

 

Hope that helps!

praveen buya's profile image
praveen buya

Hi Daniel,

 

we are using

 

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>1.5.10.RELEASE</version>

        <relativePath />

    </parent>

 

And one of our rest end point is using below annotation

 

@PostMapping(value = "/abc", produces = { "application/json" }, consumes = { "application/json" })

 

And this is deployed on PCF

 

 

praveen buya's profile image
praveen buya

Thanks Daniel, this helps a lot