Actions to specify default values when @ PathVariable is null

  • 2021-08-28 20:16:18
  • OfStack

Specifies the default value when @ PathVariable is null,

You can specify multiple matching paths, and then set the parameters that are not necessary. The example is as follows


@RequestMapping(value = {"/timeline/{uid}", "/timeline/{uid}/{size}"})
public ModelAndView getTimeline(@PathVariable(value="uid" ) String articleUserId,
@PathVariable(value="size" , required = false) Integer size,
ModelAndView modelAndView) {
if(size == null) size = 50;
// Logic 
}

It can be handled for the following two URL

http://www.leixingke.com/article/timeline/leixing

http://www.leixingke.com/article/timeline/leixing/100

Added: @ PathVariable is set to null (required=false)

When learning springMVC recently, after learning @ PathVariable, I found that @ PathVariable has an required attribute, so I set it to false, and found that the access request reported an error.

At first, my code was like this:


 @RequestMapping(value={"/user/{id}/{name}"})
 public User getUser(@PathVariable(value="id",required=false) Integer id,@PathVariable(value="name",required=false) String name ){
 System.out.println("--------------:"+id+","+name);
 User user=new User(id,name);
 return user;
 }

After discovering the above article, change the method to the following:


 /**
 * http://localhost:8080/helloWorld/user/1/zhangsan
 * http://localhost:8080/helloWorld/user/1
 * http://localhost:8080/helloWorld/user
 * @param id
 * @param name
 * @return
 */
 @RequestMapping(value={"/user/{id}/{name}","/user/{id}","/user"})
 public User getUser(@PathVariable(value="id",required=false) Integer id,@PathVariable(value="name",required=false) String name ){
 System.out.println("--------------:"+id+","+name);
 User user=new User(id,name);
 return user;
 }

The reason is that the addresses are different, and multiple address mappings need to be configured.


Related articles: