@PathVariable为空时指定默认值的操作

@PathVariable为空时指定默认值,

可以指定多个匹配路径,然后设置参数非必要的,就可以了,例子如下

@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;
//逻辑
}

对于下面两种URL都是可以处理的

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

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

补充:@PathVariable设置为空的问题(required=false)

最近学习springMVC的时候,学到@PathVariable后,发现@PathVariable有个required属性,于是将其设置为false,发现访问请求时报错。

刚开始我的代码是这样的:

 @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;
 }

后面发现上面的文章,将方法改成如下就可以了:

 /**
 * 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;
 }

原因就是地址是不一样的,需要配置多个地址映射。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持呐喊教程。如有错误或未考虑完全的地方,望不吝赐教。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。