溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在SpringMVC中配置路徑參數和URL參數

發布時間:2021-02-23 16:30:09 來源:億速云 閱讀:285 作者:Leah 欄目:開發技術

本篇文章為大家展示了如何在SpringMVC中配置路徑參數和URL參數,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

1、SpringMVC中的路徑參數就是指在路徑中添加參數,用于實現偽靜態是很好的。

2、路徑參數實現方式(一個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、創建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旗艦版

如何在SpringMVC中配置路徑參數和URL參數

5、在controller中接受請求參數的實現(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、創建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

如何在SpringMVC中配置路徑參數和URL參數

補充:spring mvc 之可選路徑參數

在spring mvc中,注解@PathVariable可以獲得路徑參數,但如果我想讓路徑參數可選呢?

  @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必須存在。

上述內容就是如何在SpringMVC中配置路徑參數和URL參數,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女