redirect from method with http DELETE type to method with GET type

前端 未结 1 1489
野趣味
野趣味 2021-02-10 15:40

I send my request using jquery ajax with type \"DELETE\". At server side I have approprite handle method that looks like this:

   @RequestMapping(value = \"/{id}         


        
相关标签:
1条回答
  • 2021-02-10 16:24

    What happens is normal even if it is not what you need :

    • you submit a DELETE request from ajax
    • Spring controller receives it and answers a "redirect:/.../Hotel..."
    • Spring ViewResolver sends a redirect response with code 302 and correct Location header
    • browser uses precedent method and new location (normal for 302) issuing a DELETE (when you expected a get)
    • Spring DispatcherServlet receives a DELETE /.../Hotel... when @RequestMapping is for method=GET
    • Spring DispatcherServlet correctly states that no controller is defined and issues an error

    All that is confirmed by your wireshark traces

    It works when you send a POST request, because for compatibility with HTTP 1.0, all major browsers use a GET for a redirection following a POST like if status was 303

    There is an immediate workaround : allow your method for the redirected URL to accept DELETE in addition to GET. Not very expensive, but not very nice.

    You could also manage the redirection on client side : simply send a 200 code that will received by ajax, and let ajax do the redirection

    The last solution consist in using a 303 code that explicitely ask browser to issue a GET independently of what was previous method. You can hardcode it by having your controller request take the HttpServletResponse as paremeter and return a null. You then manually add Location header and 303 status code.

    But you can also configure the InternalResourceViewResolver to return 303 codes instead of 302 by setting its redirectHttp10Compatible attribute to false. You simple declare a bean in your servlet application context and Spring will use it. But you loose compatibility with older browsers that would not support HTTP 1.1 and 303 status code.

    0 讨论(0)
提交回复
热议问题