How does @RequestParam in Spring handle Guava's Optional?

Anders picture Anders · Nov 27, 2013 · Viewed 60.6k times · Source
@RequestMapping(value = "/contact.html", method = RequestMethod.POST)
public final ModelAndView contact(
        @RequestParam(value = "name", required = false) Optional<String> name) {

How does Spring's @RequestMapping handle an Optional from Guava library if the parameter value is not required and nothing is sent?

Will it be:

  • Set to null
  • Set to Optional.absent()

Can Optional.fromNullable(T) be used to accept the request?

Answer

Xaerxess picture Xaerxess · Nov 27, 2013

EDIT (October 2015): Spring 4 handles java.util.Optional (from Java 8) out of the box and guarantees that Optional itself is not null, but original question was about Guava's com.google.common.base.Optional which usage as @RequestParam is highly discouraged in this specific case (because it can be null).

ORIGINAL ANSWER (about Guava's Optional):

Don't do that, just use String and let Spring handle null in its way.

Optional<T> is supposed to be used as return value and rarely as a parameter. In this particular case Spring will map missing "name" parameter to null, so even if after implementing custom property editor you'll finish with null check:

@RequestMapping("foo")
@ResponseBody
public String foo(@RequestParam(required = false) final Optional name) {
  return "name: " + (name == null ? "null" : name.get());
}

which is completely unnecessary (and missuses Optional), because it can be achieved with:

@RequestMapping("foo")
@ResponseBody
public String foo(@RequestParam(required = false) final String name) {
  return "name: " + (name == null ? "null" : name);
}