Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: Redirect in @ResponseBody

I want to redirect to another .jsp in spring mvc method. I don't want to use javascripts methods like: window.location.replace(url).

My method:

@RequestMapping(value= "loginUser", method=RequestMethod.POST)
public @ResponseBody String loginUser (@RequestParam("name") String name,   @RequestParam("password") String password){ 

   return "";
}
like image 484
Karol Bilicki Avatar asked Apr 25 '16 12:04

Karol Bilicki


2 Answers

You can't do the redirect from Spring when your request expects json response. You can set a parameter for redirect so that when you enter the success block you can check the parameter to redirect using window.location.reload();. For example, from a similar post, check this answer,

Redirect on Ajax Jquery Call

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
});

You can alternatively add a response header for redirect like response.setHeader("REQUIRES_AUTH", "1") and in jQuery success,

success:function(response){ 
        if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
            window.location.href = 'login.htm'; 
        }
        else {
            // Process the expected results...
        }
    }

Refer the similar question: Spring Controller redirect to another page

like image 128
Lucky Avatar answered Sep 18 '22 15:09

Lucky


Include an HttpServletResponse parameter and call sendRedirect(String).

Or, don't use @ResponseBody at all, and return the model/view you want to use.

like image 42
OrangeDog Avatar answered Sep 17 '22 15:09

OrangeDog