基于SpringMVC中的路徑參數(shù)和URL參數(shù)實例
1、SpringMVC中的路徑參數(shù)就是指在路徑中添加參數(shù),用于實現(xiàn)偽靜態(tài)是很好的。
2、路徑參數(shù)實現(xiàn)方式(一個Controller方法)
@RequestMapping(value="/page/{name}/{age}",method=RequestMethod.GET)
public String getName(ModelMap map,@PathVariable("name") String name,@PathVariable("age") int age)
{
map.addAttribute("name",name);
map.addAttribute("age",age);
return "name";
}
3、創(chuàng)建name.jsp文件
<%@page pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<div>
名字:${name}<br/>
年齡:${age}
</div>
</body>
</html>
4、在瀏覽器請求這個controller
http://localhost:8080/page/xiaoming/18
需要注意的是,我這里使用的編輯器是IDEA旗艦版

5、在controller中接受請求參數(shù)的實現(xiàn)(controller)
@RequestMapping(value="/result",method=RequestMethod.GET)
public String resultParam(ModelMap map,@RequestParam String name,@RequestParam int age)
{
map.addAttribute("name",name);
map.addAttribute("age",age);
return "result";
}
6、創(chuàng)建result.jsp文件
<%@page pageEncoding="UTF-8">
<html>
<head>
<meta charset="UTF-8">
<title>測試</title>
</head>
<body>
名字:${name}<br/>
年齡:${age}
</body>
</html>
6、在瀏覽器中請求這個controller
http://localhost:8080/result?name=xiaoming&age=20

補充:spring mvc 之可選路徑參數(shù)
在spring mvc中,注解@PathVariable可以獲得路徑參數(shù),但如果我想讓路徑參數(shù)可選呢?
@GetMapping({"/get/{offset}/{count}","/get/{offset}","/get/{offset}","/get"})
public void getGoods(@PathVariable(required = false) Integer offset,@PathVariable(required = false) Integer count){
System.out.println("offset:"+offset+"\ncount:"+count+"\n");
}
此時在這個例子中,offset和count都是可選的了,但是count存在時offset必須存在。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
skywalking分布式服務(wù)調(diào)用鏈路追蹤APM應(yīng)用監(jiān)控
這篇文章主要為大家介紹了skywalking分布式服務(wù)調(diào)用鏈路追蹤APM應(yīng)用監(jiān)控的功能使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-03-03
Java實現(xiàn)學(xué)生管理系統(tǒng)詳解
這篇文章主要為大家詳細介紹了Java實現(xiàn)學(xué)生管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-10-10
使用filter實現(xiàn)url級別內(nèi)存緩存示例
這篇文章主要介紹了使用filter實現(xiàn)url級別內(nèi)存緩存示例,只需要一個靜態(tài)類,在filter中調(diào)用,也可以全部寫到filt里面??梢愿鶕?jù)查詢參數(shù)分別緩存,需要的朋友可以參考下2014-03-03
Java使用路徑通配符加載Resource與profiles配置使用詳解
這篇文章主要介紹了Java使用路徑通配符加載Resource與profiles配置使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06

