Spring MVC redirect to controller using different HTTP method

I have logic controller methods:

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    // do stuff with locale and model
    // return an html page with a login form
    return "home";
}

@RequestMapping(value = "/account/login", method = RequestMethod.POST)
public String login(Model model, /* username + password params */){
    try {
        // try to login
        // redirect to account profile page
        return "redirect:/account/profile";
    } catch (LoginException e) {
        // log
        // here I want to reload the page I was on but not with a url /account/login
        // possibly using a forward
        model.addAttribute("error", e.getMessage());
        return "forward:/home";
    }
}

      

The above code works on successful login attempt. However, it fails if the login attempt fails as Spring is forward

using the current request with the same HTTP method. Therefore, since I have used POST to send my user name / password (which led to the entrance of failure in the system), forward will also use the POST method to move to the handler to /home

, home()

which expects GET.

Is there a way in Spring to redirect to another controller method with a different HTTP method while saving the current model (since I want to show an error message)?

This is in Spring 3.2.1.

+3


source to share


1 answer


Do redirect

instead:

return "redirect:/home";

      



If you need attributes Model

to be available after redirection, you can use flash attributes .

+3


source







All Articles