spring modelandview redirect无法在jquery ajax调用中工作

pap*_*tty 2 javascript ajax jquery spring spring-mvc

我正在控制器下面的模型视图attrbute表格

@RequestMapping(value = "/signin", method = RequestMethod.POST)
    public @ResponseBody
    ModelAndView loginUser(@RequestParam(value = "userName") String userName,
            @RequestParam(value = "password") String password,
            ModelAndView model) {
     on success login

       return new ModelAndView("redirect:/another controller here");
     on failure login 

           return new ModelAndView("same page");
Run Code Online (Sandbox Code Playgroud)

我有调用此控制器的jquery ajax调用,当成功登录时我想让用户采取另一个页面,但我的响应来到同一页面而不是重定向到另一个页面.

需要帮助

编辑 - 我使用基于URL的视图解析器和Apache tile进行视图渲染

Wil*_*ing 6

假设我理解你的问题,重定向将在AJAX调用的上下文中发生 - 所以JQuery AJAX代码将遵循重定向并接收它从中获取的响应/another controller here.这不会触发整页刷新,但JQuery AJAX代码可以在当前页面中呈现响应.

要在成功登录时更改整个页面,最好不要在此屏幕上使用AJAX.

或者,您可以返回一些指示符来告诉JQuery重定向.例如:

@RequestMapping(value = "/signin", method = RequestMethod.POST)
    public @ResponseBody
    ModelAndView loginUser(@RequestParam(value = "userName") String userName,
        @RequestParam(value = "password") String password,
        ModelAndView model) {

     on success login
       ModelAndView modelAndView = new ModelAndView("same page");
       modelAndView.addObject("redirectUrl", "/another controller here");
       return modelAndView;

     on failure login 
       return new ModelAndView("same page");
Run Code Online (Sandbox Code Playgroud)

然后有一些Javascript在same page其中寻找存在redirectUrl并触发整页重定向(如果存在).

var redirect = '${redirectUrl}';
if (redirect) {
    window.location.replace(redirect);
}
Run Code Online (Sandbox Code Playgroud)