Spring MVC - Using java.util.Optional as handler method parameter

[Updated: Jun 22, 2017, Created: Jun 21, 2017]

Spring supports JDK 1.8's java.util.Optional as a method parameter type as an alternative to using 'required' element of some of the annotations. Let's understand that with an example.

Without java.util.Optional

In this example, we are going to use @RequestParam:

@Controller
public class EmployeeController {

  @RequestMapping("/employee")
  @ResponseBody
  public String getEmployeeByDept (@RequestParam("dept") String deptName) {
      return "test response for dept: " + deptName;
  }
    .............
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

If we make the request without 'dept' query param, 400 Bad Request error will be returned:

One way to avoid above error (given that dept is really an optional param from business logic perspective) is to use 'required=false' of @RequestParam.

@Controller
public class EmployeeController {
    .............
  @RequestMapping("/employee2")
  @ResponseBody
  public String getEmployeeByDept2 (@RequestParam(value = "dept", required = false)
                                              String deptName) {
      return "test response for dept: " + deptName;
  }
    .............
}

Using java.util.Optional

As Spring always tries to align the framework with standard JSE/JEE API, it now supports (since 4.3) java.util.Optional as an alternative to using 'required' element:

@Controller
public class EmployeeController {
    .............
  @RequestMapping("/employee3")
  @ResponseBody
  public String getEmployeeByDept3 (@RequestParam("dept") Optional<String> deptName) {
      return "test response for dept: " + (deptName.isPresent() ? deptName.get() :
                "using default dept");
  }
}

Other supported annotations

Other than @RequestParam, @RequestHeader and @MatrixVariable can also be used with java.util.Optional.

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Optional Example Select All Download
  • optional-as-handler-param-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also