Search code examples
javaspringspring-mvcspring-annotations

Spring MVC 'forward' not works with @PostMapping and @GetMapping Annotations for same URI


I have used @PostMapping and @GetMapping for /login endpoint as shown below,

For /login page after a validation failure, if I forward to the same /login page with error messages, it's not working and throws method not supported error with 405 status.

When I switch the @PostMapping first and @GetMapping next, /login page itself not loaded(refer Before section).

I have fixed this with the normal RequestMapping params(forward and normal login) but wanted to understand the internal mechanisms more on these annotations, how it works.

Before:

@GetMapping(value = "/login")
@PostMapping(value = "/login")
public ModelAndView getLoginPage() {
    ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
    return modelAndView;
}

After:

@RequestMapping(value = "/login", method = { GET, POST })
public ModelAndView getLoginPage() {
    ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
    return modelAndView;
}

Solution

  • @GetMapping, etc. is just an alias for the appropriate @RequestMapping. So you essentially have 2 @RequestMappings. In that case, the 2nd one is ignored. In your after block, you are doing it correctly and have multiple mappings in a single @RequestMapping.