案例來說明
1 @RequestMapping("user/add") 2 public String add(@RequestParam("name") String name, 3 @RequestParam("age") int age){ 4 System.out.println(name+","+age); 5 return "hello"; 6 }
測試1
當我們請求路徑為:http://localhost:8080/springmvc-1/user/add?name=caoyc&age=18
輸出結果:caoyc,18
測試2
當我請求路徑為:http://localhost:8080/springmvc-1/user/add?age=18
輸出結果:有異常出現。意思是說必須要有該參數
解決方案:在@RequestParam標簽中添加一個required=false,表示該屬性不是必須的
1 @RequestParam(value="name",required=false)
輸出結果:null,18
測試3
當我請求路徑為:http://localhost:8080/springmvc-1/user/add?name=caoyc
同樣出現上面的異常
那么根據上面的方法設置
1 @RequestParam(value="age",required=false) int age
結果再運行。還是拋出異常
這里也說到很明白,大概意思是說不能講一個null的空值賦給age。應該使用包裝類型
那么我們將代碼改成這樣:
1 @RequestParam(value="age",required=false) Integer age
結果正確輸出:caoyc,null
這里還有另外一種改法:給參數指定一個默認值
1 @RequestParam(value="age",required=false,defaultValue="0") int age
結果輸出:caoyc,0
【總結】對應@RequestParam基本類型的參數我們最好都使用包裝類型