Spring WebMVC Optional @PathVariable

Lokesh Gupta

Learn to make a path variable optional in Spring WebMVC application using different approaches with help of @PathVariable annotation.

1. When We Need an Optional @PathVariable

The problems are generally when we try to perform more than one task in a method (which is not recommended). E.g. we may have a method in Spring MVC controller which can be used to create a new record or edit an existing record – based on the presence of 'id' attribute of record.

@RequestMapping(path = {"/edit/{id}"})
public String createOrUpdateEmployee(@PathVariable("id") Long id, Employee employee) throws RecordNotFoundException 
{
  if(id == null) {
    //create
  } else {
    //update
  }
}

Though above code looks simple and right, but it is not. In runtime, it will give error if we try to hit URL : /edit.

/edit/123
/edit/1000
 
/edit   -   ERROR !!

So essentially, we cannot skip the id parameter and it shall never be null.

2. How to Make an Optional Path Variable

2.1. Using @PathVariable(required = false) – Spring 4.3.3

The @PathVariable annotation allows the boolean attribute required to indicate if a path variable is mandatory or optional. Remember to store the value of the parameter in the Java 8 Optional class.

@RequestMapping(path = {"/edit/{id}"})
public String editEmployeeById(@PathVariable(required = false) Optional<Long> id) 
    throws RecordNotFoundException 
{
  if(id.isPresent()) {
    //update
  } else {
    //create
  }
}

2.2. Using Java 8 Optional Parameter Type and Multiple Mappings

In earlier versions of Spring, we could use multiple path mappings in @RequestMapping annotation. In the given example, we have to use /edit and /edit/{id} both in handler mappings.

@RequestMapping(path = {"/edit", "/edit/{id}"})
public String editEmployeeById(@PathVariable Optional<Long> id) throws RecordNotFoundException 
{
  if(id.isPresent()) {
    //update
  } else {
    //create
  }
}

Now all URLs are mapped and will work.

/edit/123
/edit/1000
 
/edit   -   WORKS NOW !!

3. Conclusion

Though it is a very simple and obvious solution, it makes sense and helps when we get into this situation. Drop me your comments related to how to make path variable optional in spring boot.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode