从Ajax Spring MVC控制器方法执行普通重定向 [英] Performing a normal redirect from an ajax Spring MVC controller method

查看:88
本文介绍了从Ajax Spring MVC控制器方法执行普通重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring MVC控制器方法.

I have a Spring MVC controller method.

我希望这种方法:

  • 如果存在验证错误,请返回一个JSon @ResponseBody(在Ajax中)
  • 如果没有验证错误,请执行到指定URL的普通重定向

假设我有一个名为myObject的javabean对象,我尝试了以下操作:

Assuming I have a javabean object called myObject, I tried the following:

@RequestMapping(value = "/new", method = RequestMethod.POST)
@ResponseBody
public MyJavabeanObject myMethod(@RequestBody MyJavabeanObject myObject, BindingResult bindingResult, Model model,
        RedirectAttributes redirectAttributes, HttpServletResponse response) throws IOException {

    if (bindingResult.hasErrors()) {
        //adding error message to javabean
        return myObject;
    }

    response.sendRedirect("/success");
    return null;
}

任何人都可以让我知道我试图实现的目标是否可能吗?

Can anyone please let me know if what I am trying to achieve is at all possible?

推荐答案

您所描述的将起作用.您的方法用@ResponseBody注释.因此,将分派特定的HandlerMethodReturnValueHandlerRequestResponseBodyMethodProcessor来处理返回的对象并将其写入响应.

What you have will work as you describe it. Your method is annotated with @ResponseBody. Because of that a specific HandlerMethodReturnValueHandler, RequestResponseBodyMethodProcessor, will be dispatched to handle to returned object and write it to the response.

如果您没有收到错误,则直接发送自己的重定向并返回null.当处理程序方法的返回值为null时,Spring的DispatcherServlet假定您自己处理生成的响应.

If instead you don't get errors, you send the redirect yourself directly and return null. When the returned value of your handler method is null, Spring's DispatcherServlet assumes that you handle generating the response yourself.

您唯一需要担心的是AJAX处理程序如何期望响应.在一种情况下,它将获取JSON,在另一种情况下,它将获取/success返回的内容.

The only thing you have to worry about here is how your AJAX handler expects the response. In one case it'll get JSON, in the other it'll get whatever /success returns.

注意:如果您希望重定向从AJAX请求重定向整个浏览器页面,则此操作将无效.您需要做的是在AJAX处理程序中添加一个特殊情况,通过设置window.location或相关内容来更改浏览器页面本身.

Note: if you expected the redirect to redirect the whole browser page from an AJAX request, this won't work. What you will need is to have a special case in your AJAX handler that will perform the browser page change itself by setting the window.location or something related.

这篇关于从Ajax Spring MVC控制器方法执行普通重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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