hellzone
hellzone

Reputation: 5246

How to redirect from spring ajax controller?

I have a controller with @ResponseBody annotation. What I want to do is if this user doesn't exists process user's Id and return a json object. If exists redirect to user page with userInfo. Below code gives ajax error. Is there any way to redirect to user page with userInfo?

    @RequestMapping(value = "/user/userInfo", method = {RequestMethod.GET})
    @ResponseBody
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

       if(...){
          .....//ajax return
       }else{
          modelMap.addAttribute("userInfo", userInfoFromDB);
          return "user/user.jsp";
       }

    }

Upvotes: 1

Views: 3153

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149185

Well, this method is annotated with @ResponseBody. That means that the String return value will be the body of the response. So here you are just returning "user/user.jsp" to caller.

As you have full access to the response, you can always explicitely do a redirect with response.sendRedirect(...);. It is even possible to explicitely ask Spring to pass userInfoFromDB as a RedirectAttribute through the flash. You can see more details on that in this other answer from me (this latter is for an interceptor, but can be used the same from a controller). You would have to return null to tell spring that the controller code have fully processed the response. Here it will be:

...
}else{
    Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request);
    flash.put("userInfo", userInfoFromDB);
    response.redirect(request.getContextPath() + "/user/user.jsp");
    return null;
}
...

The problem is that the client side expects a string response that will not arrive and must be prepared to that. If it is not, you will get an error client side. The alternative would then be not to redirect but pass a special string containing the next URL:

...
}else{
    Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request);
    flash.put("userInfo", userInfoFromDB); // prepare the redirect attribute
    return "SPECIAL_STRING_FOR_REDIRECT:" + request.getContextPath() + "/user/user.jsp");
}

and let the javascript client code to process that response and ask for the next page.

Upvotes: 2

Related Questions