如何防止Spring MVC进行重定向? [英] How can I prevent Spring MVC from doing a redirect?

查看:91
本文介绍了如何防止Spring MVC进行重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理更新实体的AJAX请求。我真的不需要它返回任何东西。问题是Spring MVC坚持将重定向发送到同一个URL(显然正在进行后重定向获取),浏览器尽职尽责。

I want to handle an AJAX request that updates an entity. I don't really need it to return anything. The problem is that Spring MVC insists on sending a redirect to the same URL (apparently doing its post-redirect-get thing), which the browser dutifully follows.

怎么能我有一个Spring MVC控制器方法刚刚完成并返回一些东西而不发送重定向?在网上搜索只会导致无法讨论如何进行重定向,而不是如何避免重定向。

How can I have a Spring MVC controller method just complete and return something without sending a redirect? Searching on the web only leads to countrless discussions of how to do a redirect, not how to avoid one.

这是对的PUT请求http: // localhost:9090 / pex / api / testrun / f0a80b46-84b1-462a-af47-d1eadd779f59e 带有这些标题:

Host: localhost:9090
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Length: 20
Content-Type: application/json
Referer: http://localhost:9090/pex/api/testrun/f0a80b46-84b1-462a-af47-d1eadd779f59e/visualizations/common-api?slas=lp,internal,external
X-Requested-With: XMLHttpRequest
Connection: keep-alive
Authorization: Basic xxxx

响应的状态代码为302 Found,没有正文内容和这些标题:

The response has status code "302 Found", no body content and these headers:

Content-Language: "de"
Content-Length: "0"
Location: "http://localhost:9090/pex/api/testrun/f0a80b46-84b1-462a-af47-d1eadd779f59e"
Server: "Jetty(6.1.10)"
access-control-allow-origin: "*"

这是服务器端代码:

@RequestMapping(value = "/api/testrun/{testrunId}", method = RequestMethod.PUT, consumes = "application/json")
@ResponseBody
public Testrun updateOverview(@PathVariable("testrunId") final String testrunId, @RequestBody final String body) {
    return testrunService.updateOverview(testrunId, body);
}

以下是进行AJAX调用的Javascript代码:

Here's the Javascript code that makes the AJAX call:

$(document).ready(function() {
    $("#update_name_form").submit(function (e) {
        update_testrun($("#name"));
        return false;
    });
}
function update_testrun(element) {
    var name = element.attr('name');
    var new_value = element.val().trim();
    var data = {};
    data[name] = new_value;
    $.ajax({url: config.urls.api.testrun + testrun.id,
            type: "PUT",
            contentType: "application/json",
            data: JSON.stringify(data),
            error: function(jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
            },
            success: function (data, textStatus, jqXHR) {
                    testrun.overview[name] = new_value;
            }
    });
}


推荐答案

Spring MVC构建于Servlet API之上。因此,任何有权访问 HttpServletResponse 的组件理论上都可以将它用于 sendRedirect(String) 或手动设置响应代码。 (我说理论上因为在进行这些调用时必须尚未提交响应。)

Spring MVC is built on top of the Servlet API. As such, any component that has access to the HttpServletResponse can theoretically use it to sendRedirect(String) or set the response code manually. (I say theoretically because the response must not have yet been committed when those calls are made.)

通常,在Spring MVC应用程序中,一个 @Controller 可以收到 HttpServletResponse (或 ServletResponse )在 @RequestMapping 方法中作为参数

Typically, in a Spring MVC application, a @Controller can receive the HttpServletResponse (or ServletResponse) in a @RequestMapping method as an argument.

A HandlerInterceptor 作为 DispatcherServlet 的请求处理生命周期的一部分接收它三次。

A HandlerInterceptor receives it three times as part of the DispatcherServlet's request handling lifecycle.

任何已注册的Servlet 过滤器 实例也可以在Spring的 ServletResponse /docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html> DispatcherServlet 自过滤器在servlet之前执行。

Any registered Servlet Filter instances also have access to the ServletResponse before (and after) Spring's DispatcherServlet since filters act before servlets.

Spring尝试将所有这些依赖项隐藏到Servlet API中,以使编程Web服务器更容易。因此,它提供了导致重定向的其他方法。这些主要取决于支持的处理程序方法返回类型。更具体地说,我们关心 String 查看 ModelAndView ,和 ResponseEntity

Spring tries to hide all these dependencies to the Servlet API to make programming web server easier. It therefore provides other ways to cause a redirect. These mostly depend on the supported handler method return types. More specifically, we care about String, View, ModelAndView, and ResponseEntity.

以下是所有默认情况:

当您返回字符串,Spring将使用 ViewResolver 解析 查看 基于 String 值,该值标识了视图。 Spring的 UrlBasedViewResolver 将检测字符串中的前缀> a 重定向:前缀查看名称并将其视为发送重定向响应。它将创建一个 RedirectView (部分内容实际上是在 ViewNameMethodReturnValueHandler 中完成的,但 UrlBasedViewResolver 创建查看),它将负责使用 HttpServletResponse 进行重定向。

When you return a String, Spring will use a ViewResolver to resolve a View based on the String value, which identifies the name of the view. Spring's UrlBasedViewResolver will detect a redirect: prefix in String view names and consider it as an indication to send a redirect response. It will create a RedirectView (part of this is actually done in ViewNameMethodReturnValueHandler, but UrlBasedViewResolver creates the View) which will be in charge of doing the redirect with the HttpServletResponse.

这是一个实现细节,但Spring的默认 ViewResolver 类的大部分都是这样做的。

This is an implementation detail, but most of Spring's default ViewResolver classes do this.

使用 查看 ,您可以自己创建并返回 RedirectView 。您还可以实现自己的 View 类来执行相同的操作。 Spring将使用适当的 HandlerMethodReturnValueHandler 来处理它。

With View, you can simply create and return a RedirectView yourself. You can also implement your own View class that will do the same. Spring will use the appropriate HandlerMethodReturnValueHandler to handle it.

使用 ModelAndView ,它是一个混合使用前两个选项,因为您可以提供视图名称或查看本身。

With ModelAndView, it's a mix of the two previous options since you can provide either a view name or a View itself.

使用 ResponseEntity 因为你控制整个响应,它会变得更有趣。也就是说,您可以设置状态代码,标题,正文,一切。因此,您需要做的就是将状态代码设置为302并将 Location 标头与要重定向到的URL放在一起。

With ResponseEntity it gets more interesting since you control the whole response. That is, you can set a status code, headers, body, everything. All you need to do is therefore set the status code to 302 and put a Location header with the URL to redirect to.

最后,您在中有类似的行为 @ExceptionHandler 方法(具有类似的返回类型),您也可以将它们与 @ResponseStatus 并手动修改标题。

Finally, you have similar behavior in @ExceptionHandler methods (with similar return types) which you can also mix with @ResponseStatus and modifying the headers manually.

这些都是基本情况,但由于Spring MVC几乎完全可定制,因此还有其他组件需要注意。这些是 HandlerMethodArgumentResolver HandlerMethodReturnValueHandler HandlerAdapter HandlerExceptionResolver ExceptionHandler ,以及更多。请注意,你很少会玩这些,而Spring附带的那些几乎可以完成整个工作。

These are all the basic cases, but since Spring MVC is almost completely customizable, there are other components to be aware of. These are HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler, HandlerAdapter, HandlerExceptionResolver and ExceptionHandler, and more. Note that you'll rarely play with these and those that come with Spring pretty much do the whole job.

这篇关于如何防止Spring MVC进行重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆