@PathVariable為空時(shí)指定默認(rèn)值的操作
@PathVariable為空時(shí)指定默認(rèn)值,
可以指定多個(gè)匹配路徑,然后設(shè)置參數(shù)非必要的,就可以了,例子如下
@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;
//邏輯
}
對(duì)于下面兩種URL都是可以處理的
http://www.leixingke.com/article/timeline/leixing
http://www.leixingke.com/article/timeline/leixing/100
補(bǔ)充:@PathVariable設(shè)置為空的問(wèn)題(required=false)
最近學(xué)習(xí)springMVC的時(shí)候,學(xué)到@PathVariable后,發(fā)現(xiàn)@PathVariable有個(gè)required屬性,于是將其設(shè)置為false,發(fā)現(xiàn)訪問(wèn)請(qǐng)求時(shí)報(bào)錯(cuò)。
剛開(kāi)始我的代碼是這樣的:
@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;
}
后面發(fā)現(xiàn)上面的文章,將方法改成如下就可以了:
/**
* 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;
}
原因就是地址是不一樣的,需要配置多個(gè)地址映射。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
詳解Java編程中static關(guān)鍵字和final關(guān)鍵字的使用
這篇文章主要介紹了詳解Java編程中static關(guān)鍵字和final關(guān)鍵字的使用,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
Java設(shè)計(jì)通用的返回?cái)?shù)據(jù)格式過(guò)程講解
現(xiàn)在很多的項(xiàng)目server端返回client端的數(shù)據(jù)多數(shù)以JSON格式返回,同時(shí)結(jié)合其它需要,通常加一下?tīng)顟B(tài)碼和信息之類(lèi),給前端處理帶來(lái)很大的方便,這篇文章就用Java設(shè)計(jì)了通用的返回?cái)?shù)據(jù)格式,感興趣的同學(xué)可以參考下文2023-05-05
Spring 使用 feign時(shí)設(shè)置header信息的操作
這篇文章主要介紹了Spring 使用 feign時(shí)設(shè)置header信息的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
java利用反射實(shí)現(xiàn)動(dòng)態(tài)代理示例
這篇文章主要介紹了java利用反射實(shí)現(xiàn)動(dòng)態(tài)代理示例,需要的朋友可以參考下2014-04-04
說(shuō)說(shuō)Spring中為何要引入Lookup注解
這篇文章主要給大家介紹了關(guān)于Spring中為何要引入Lookup注解的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
java Bean與json對(duì)象間的轉(zhuǎn)換實(shí)例講解
在本篇文章里小編給大家整理的是關(guān)于java Bean與json間的轉(zhuǎn)換的實(shí)例內(nèi)容,有需要的朋友們吧可以學(xué)習(xí)參考下。2020-01-01

