从 http DELETE 类型的方法重定向到 GET 类型的方法

Ale*_*gak 4 java spring-mvc

我使用类型为“DELETE”的 jquery ajax 发送我的请求。在服务器端,我有适当的处理方法,如下所示:

   @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@RequestParam("hotel") String hotelCode, @PathVariable Long id, Model model){
        //delete operation
        return "redirect:/HotelTaxesAndCharges?hotel="+hotelCode;
    }
Run Code Online (Sandbox Code Playgroud)

我想在删除后将调用重定向到的方法如下所示

@RequestMapping(method = RequestMethod.GET)
public String getAll(@RequestParam("hotel") String hotelCode, Model model){
    //logic
    return 'getAll';
}
Run Code Online (Sandbox Code Playgroud)

so when i call delete method during execution I'm getting error "you can redirect to JSP using only GET PUT or HEAD methods". I found solution using HiddenHttpMethodFilter, but result code looks little messy and I need to send request using POST and adding additional parameter (_method) to requst with custom request type.

So my question is there any other solution for DELETE/REDIRECT/GET transformation.

SORRY FOR BAD ENGLISH

UPDATE 在此处输入图片说明

so you can that it redirects using delete too. And if I change everything from delete to post I get this:

在此处输入图片说明

Ser*_*sta 6

即使不是您需要的,发生的情况也是正常的:

  • 您从 ajax 提交 DELETE 请求
  • Spring 控制器接收它并回答“重定向:/.../Hotel...”
  • Spring ViewResolver 发送带有代码 302 和正确位置标头的重定向响应
  • 浏览器使用先例方法和新位置(302 正常)发出 DELETE(当您期望获取时)
  • Spring DispatcherServlet 收到一个DELETE /.../Hotel...when @RequestMappingis for method=GET
  • Spring DispatcherServlet 正确声明没有定义控制器并发出错误

您的wireshark痕迹证实了所有这些

它在您发送 POST 请求时有效,因为为了与 HTTP 1.0 兼容,所有主要浏览器都使用 GET 进行 POST 后的重定向,例如状态为 303

有一个直接的解决方法:除了 GET 之外,还允许重定向 URL 的方法接受 DELETE。不是很贵,但也不是很好。

您还可以在客户端管理重定向:只需发送一个 200 代码将被 ajax 接收,然后让 ajax 进行重定向

最后一个解决方案是使用 303 代码,该代码明确要求浏览器独立于以前的方法发出 GET。您可以通过让控制器请求将 HttpServletResponse 作为参数并返回 null 来对其进行硬编码。然后手动添加Location标题和 303 状态代码。

但是您也可以InternalResourceViewResolver通过将其 redirectHttp10Compatible 属性设置为 false 来配置返回 303 代码而不是 302。您只需在 servlet 应用程序上下文中声明一个 bean,Spring 就会使用它。但是您失去了与不支持 HTTP 1.1 和 303 状态代码的旧浏览器的兼容性。