服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - @PathVariable为空时指定默认值的操作

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

2021-08-14 12:18csdnluolei Java教程

这篇文章主要介绍了@PathVariable为空时指定默认值的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

@PathVariable为空时指定默认值,

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

?
1
2
3
4
5
6
7
@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,发现访问请求时报错。

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

?
1
2
3
4
5
6
@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;
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 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;
}

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

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

原文链接:https://blog.csdn.net/csdnluolei/article/details/107041110

延伸 · 阅读

精彩推荐