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 "";
}
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
Include an HttpServletResponse
parameter and call sendRedirect(String)
.
Or, don't use @ResponseBody
at all, and return the model/view you want to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With