Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280181

Spring MVC forwarding to controller with different HTTP method

I have login controller methods like so:

@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 log-in attempt. However, it fails when the log-in attempt fails because Spring's forward uses the current request with the same HTTP method. So because I used a POST to send my username/password (which caused log-in to fail), the forward will also use POST to go to the handler method for /home, home(), which is expecting a GET.

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

This is on Spring 3.2.1.

Upvotes: 4

Views: 8166

Answers (1)

GriffeyDog
GriffeyDog

Reputation: 8386

Do a redirect instead:

return "redirect:/home";

If you need Model attributes to be available after the redirect, you can use flash attributes.

Upvotes: 4

Related Questions