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

时间:2013-10-15 07:52:05

标签: javascript jquery ajax 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");

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

需要帮助

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

1 个答案:

答案 0 :(得分: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");

然后在same page中添加一些Javascript,查找是否存在redirectUrl并触发整页重定向(如果存在)。

var redirect = '${redirectUrl}';
if (redirect) {
    window.location.replace(redirect);
}