How to change response to HTTP OPTIONS request in Spring MVC 2.5 application?

This sounds like a trivial question, but for some reason I cannot understand it.

I have a Spring MVC application. I do not support any http methods other than GET and POST. I have the following settings in all my beans controllers:

<property name="supportedMethods" value="GET,POST"/>

However, the OPTIONS request sent to my application sends a response that shows all http methods as allowed.

How do I change the OPTIONS response to only show the GET and POST methods? I know that I can do this in the servlet by overriding the method doOptions, but I'm not sure about the Spring MVC application. Should I expand DispatcherServletand redefine doOptions?

The application uses Spring mvc 2.5.6 with SimpleFormController-based controllers and xml-based configuration.

+3
source share
3 answers

I think you could call WebContentGenerator#setSupportedMethods, which receives as an input parameter an array of strings containing the supported methods. WebContentGeneratoris the base class for spring 2.x controllers, so you just need to call this method while building your controller, which will undoubtedly extend it. You can also use the WebContentGenerator constructor, which receives the string varargs (supported methods) as an input parameter.

Unfortunately, the method doOptionsin the class FrameworkServletcalls the super.doOptions(request, response);class HttpServlet. The output of this method is based on the declared methods in the servlet, something like this:

Method[] methods = getAllDeclaredMethods(this.getClass());

for (int i = 0; i < methods.length; i++) {
    Method m = methods[i];

    if (m.getName().equals("doGet")) {
        ALLOW_GET = true;
        ALLOW_HEAD = true;
    }
    if (m.getName().equals("doPost"))
        ALLOW_POST = true;
    if (m.getName().equals("doPut"))
        ALLOW_PUT = true;
    if (m.getName().equals("doDelete"))
        ALLOW_DELETE = true;
}

DispatcherServlet ( FrameworkServlet) : doPut, doDelete, doGet, doPost .., doOptions , . , DispatcherServlet.

+1

: OPTIONS.

( @Controller) RequestMethod.OPTIONS . ,

  ... stuff ...  
  @RequestMapping(RequestMethod.OPTIONS)  
  public String processOptions()
  {
  ... stuff ...
  }
+2

, , , , , .

@RequestMapping (RequestMethod.OPTIONS) , DispatcherServlet , , FrameworkServlet, , HttpServlet, , , , doXXX . super.doOptions(...) :

if (this.dispatchOptionsRequest) {
     processRequest(request, response);
}

setDispatchOptionsRequest (boolean), dispatchOptionsRequest true. DispatcherServlet OPTIONS .

, OPTIONS . , DispatcherServlet , http OPTIONS .

, HttpServletResponse Spring . reset(), Allow .

(. patter FrameworkServlet HTTP TRACE setDispatchTraceRequest, , @RequestMapping (RequestMethod.TRACE)).

+1

Source: https://habr.com/ru/post/1795819/


All Articles