@RequestParam in Spring MVC handling optional parameters

Before Java 8 and Spring 5 (but works with Java 8+ and Spring 5+ too)

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 because they are still “implicitly” 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.

Update for Java 8 and Spring 5 (and above)

You can now use the Optional class from Java 8 onwards to make the parameters optional.

@RequestMapping (value = "/path", method = RequestMethod.GET)
public String handleRequest(@RequestParam("paramName") Optional<String> variableName) {
    String paramValue = variableName.orElse("");
    // use the paramValue
}

Leave a Comment