欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-04-13 09:14:26|栏目:JAVA代码|点击:

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

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

上一篇:Java Socket编程实现简单的问候服务

栏    目:JAVA代码

下一篇:springboot+idea+maven 多模块项目搭建的详细过程(连接数据库进行测试)

本文标题:@PathVariable为空时指定默认值的操作

本文地址:http://www.codeinn.net/misctech/100413.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有