基于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)文章
利用Java代碼實現(xiàn)區(qū)塊鏈技術(shù)
這篇文章主要介紹了利用Java代碼實現(xiàn)區(qū)塊鏈技術(shù),區(qū)塊鏈的應(yīng)用范圍幾乎無窮無盡,關(guān)于區(qū)塊鏈?zhǔn)侨绾芜\作的,下文來看看具體的內(nèi)容介紹吧,需要的朋友可以參考一下2022-04-04關(guān)于protected修飾符詳解-源于Cloneable接口
這篇文章主要介紹了protected修飾符詳解-源于Cloneable接口,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Java中String.format的使用方法總結(jié)
這篇文章主要介紹了Java中String.format的用法總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-03-03Java Scanner對象中hasNext()與next()方法的使用
這篇文章主要介紹了Java Scanner對象中hasNext()與next()方法的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10