好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

@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://HdhCmsTestleixingke测试数据/article/timeline/leixing

http://HdhCmsTestleixingke测试数据/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

查看更多关于@PathVariable为空时指定默认值的操作的详细内容...

  阅读:33次