1. 程式人生 > >使用SpringMVC註解@RequestParam(value="XXX",required=false)時需要注意的問題

使用SpringMVC註解@RequestParam(value="XXX",required=false)時需要注意的問題

錯誤描述:

@RequestMapping(value = "/index")
	public String index(@RequestParam(value = "action", required = false)
	String action, @RequestParam(value = "notIncludeTypeId", required = false)
	int notIncludeTypeId){
    // .... 省略程式碼
}

      當可選引數“notIncludeTypeId”為空時,系統出現如下錯誤: 

Optional int parameter 'notIncludeTypeId' is not present 
but cannot be translated into a null value due to being declared as a primitive type. 
Consider declaring it as object wrapper for the corresponding primitive type.

錯誤原因:

    當可選引數“notIncludeTypeId”不存在時,Spring預設將其賦值為null,但由於notIncludeTypeId已定於為基本型別int,所以賦值失敗!

解決方法:

    “Consider declaring it as object wrapper for the corresponding primitive type.”建議使用包裝型別代替基本型別,如使用“Integer”代替“int”