Spring MVC – Optional @PathVariable in request URI

By design, in Spring MVC, it is not possible to have optional @PathVariable value. Still, we can use multiple path mappings to simulate this effect successfully.

Please note we need to implement this solution in case where we want to @PathVariable‘s required attribute to set to false and expect variable’s value to null.

1. Usecase when need optional @PathVariable

1.1. Usecase

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 editEmployeeById(@PathVariable("id") Long id) 
		throws RecordNotFoundException 
{
	if(id == null) {
		//create
	} else {
		//update
	}
}

1.2. Problem

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. Solution

Solution is to use multiple path mappings in @RequestMapping annotation.

In given example, we have to use /edit and /edit/{id} both in handler mappings. Remember to store the value of id in Java 8 Optional class.

@RequestMapping(path = {"/edit", "/edit/{id}"})
public String editEmployeeById(@PathVariable("id") 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 very simple and obvious solution yet 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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Spring MVC – Optional @PathVariable in request URI”

  1. How would we be able to handle situation where I need two path variable and both of them can be optional ?

    Usecase: User can enter client id or user id to search for records. I would like to make this work with a single get endpoint.

    I am confused on the part where url might look – /api/client/ {no client id}/ {valid user id}

    Right now I have something like this:

    @RequestMapping(value = {"/{clientId}/{userId}", "/{clientId}", "{}/{userId}", ""}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public String getApprovedSiteByClientIdAndUserGuid(@PathVariable(required = false) Optional<String> clientId, @PathVariable(required = false) Optional<String> userId, ModelMap m) { }
    
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.