5

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 "";
}
Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
karolinski
  • 577
  • 1
  • 6
  • 18

2 Answers2

3

Include an HttpServletResponse parameter and call sendRedirect(String).

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

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
3

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

Community
  • 1
  • 1
Lucky
  • 16,787
  • 19
  • 117
  • 151
  • @OrangeDog seems it won't working either. As spring doesn't redirect to another page on json requests. Updated an alternative solution. – Lucky Apr 25 '16 at 14:11
  • Who said it was an async request? – OrangeDog Apr 25 '16 at 14:13
  • I assumed the OP is using ajax call to login the user and redirect to some success page. Anyway whether or not he uses ajax, it can only be done is JS as the other posts suggests. – Lucky Apr 25 '16 at 14:18