Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @PathVariable return null if it's not found?

Is it possible to make the @PathVariable to return null if the path variable is not in the url? Otherwise I need to make two handlers. One for /simple and another for /simple/{game}, but both do the same just if there is no game defined i pick first one from a list however if there is a game param defined then i use it.

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET) public ModelAndView gameHandler(@PathVariable("example") String example,             HttpServletRequest request) { 

And this is what I get when trying to open page /simple:

Caused by: java.lang.IllegalStateException: Could not find @PathVariable [example] in @RequestMapping

like image 478
Rihards Avatar asked Mar 30 '11 23:03

Rihards


People also ask

What does @PathVariable annotation do?

The @PathVariable annotation is used to extract the value of the template variables and assign their value to a method variable.

Is @PathVariable required?

Using @PathVariable required attribute From Spring 4.3. 3 version, @PathVariable annotation has required attribute, to specify it is mandatorily required in URI. The default value for this attribute is true if we make this attribute value to false, then Spring MVC will not throw an exception.

Can PathVariable be optional?

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.

What does @PathVariable do in Spring MVC?

@PathVariable is a Spring annotation which indicates that a method parameter should be bound to a URI template variable. If the method parameter is Map<String, String> then the map is populated with all path variable names and values. It has the following optional elements: name - name of the path variable to bind to.


1 Answers

They cannot be optional, no. If you need that, you need two methods to handle them.

This reflects the nature of path variables - it doesn't really make sense for them to be null. REST-style URLs always need the full URL path. If you have an optional component, consider making it a request parameter instead (i.e. using @RequestParam). This is much better suited to optional arguments.

like image 84
skaffman Avatar answered Sep 24 '22 20:09

skaffman