luksmir luksmir - 2 months ago 15
Java Question

@RequestParam in Spring MVC handling optional parameters

Is it possible for a spring controller to handle both kind of requests?

1) http://localhost:8080/submit/id/ID123432?logout=true
2) http://localhost:8080/submit/id/ID123432?name=sam&password=543432

If I define a single controller of the kind:

@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,
public String showLoginWindow(@PathVariable("id") String id,
@RequestParam(value = "logout", required = false) String logout,
@RequestParam("name") String username,
@RequestParam("password") String password,
@ModelAttribute("submitModel") SubmitModel model,
BindingResult errors) throws LoginException {...}

the HTTP Request with "logout" is not accepted.

If I define two controllers to handle each request separately, Spring complains with the exception "There is already 'Controller' bean method ... mapped".


You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.