简体   繁体   中英

spring modelandview redirect not working in jquery ajax call

I am returing modelview attrbute form below controller

@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");

i have jquery ajax call which invokes this controller, when successful login i want to user to take another page, but my response comes to the same page instead of redirecting to another page.

help needed

EDIT - I am using URL based view resolver and Apache tiles for view rendering

Assuming I'm understanding your problem, the redirect will take place within the context of the AJAX call - so the JQuery AJAX code will follow the redirect and receive the response it gets back from /another controller here . This won't trigger a full page refresh but the response will be available by the JQuery AJAX code for rendering in the current page.

To change the whole page on successful login, you may be better to not use AJAX for this screen.

Alternatively, you could return some indicator to tell JQuery to redirect. For example:

@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");

And then have some Javascript in same page that looks for the presence of redirectUrl and triggers a full page redirect if present.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM