4

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.

1 Answer 1

4

Do a redirect instead:

return "redirect:/home";

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

Sign up to request clarification or add additional context in comments.

4 Comments

Redirect works for POST/REDIRECT/GET. Is there anything similar for POST/REDIRECT/POST or GET/REDIRECT/POST? Or any other method than GET in the last step?
The last step in your description is the GET to /home. This looks like a standard POST/REDIRECT/GET to me.
No it is, I'm just curious if you can do the opposite.
I believe a redirect always results in a GET, so no.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.