生活随笔
收集整理的這篇文章主要介紹了
SpringMVC注解@RequestParam全面解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在SpringMVC后臺控制層獲取參數的方式主要有兩種,一種是request.getParameter("name"),另外一種是用注解@RequestParam直接獲取。這里主要講這個注解?
一、基本使用,獲取提交的參數?
后端代碼:?
Java代碼??
@RequestMapping("testRequestParam")???????public?String?filesUpload(@RequestParam?String?inputStr,?HttpServletRequest?request)?{????????System.out.println(inputStr);????????????int?inputInt?=?Integer.valueOf(request.getParameter("inputInt"));??????System.out.println(inputInt);????????????????return?"index";?????}?????
前端代碼:?
Html代碼??
<form?action="/gadget/testRequestParam"?method="post">?????????參數inputStr:<input?type="text"?name="inputStr">?????????參數intputInt:<input?type="text"?name="inputInt">????</form>??
前端界面:?
?
執行結果:?
test1?
123?
可以看到spring會自動根據參數名字封裝進入,我們可以直接拿這個參數名來用?
二、各種異常情況處理?
1、可以對傳入參數指定參數名?
Java代碼??
@RequestParam?String?inputStr??@RequestParam(value="aa")?String?inputStr??
錯誤信息:?
HTTP Status 400 - Required String parameter 'aa' is not present?
2、可以通過required=false或者true來要求@RequestParam配置的前端參數是否一定要傳?
Java代碼??
@RequestMapping("testRequestParam")????????public?String?filesUpload(@RequestParam(value="aa",?required=true)?String?inputStr,?HttpServletRequest?request)??
3、如果用@RequestMapping注解的參數是int基本類型,但是required=false,這時如果不傳參數值會報錯,因為不傳值,會賦值為null給int,這個不可以?
Java代碼??
@RequestMapping("testRequestParam")???????public?String?filesUpload(@RequestParam(value="aa",?required=true)?String?inputStr,???????????@RequestParam(value="inputInt",?required=false)?int?inputInt??????????,HttpServletRequest?request)?{??????????????????return?"index";?????}??
解決方法:?
????“Consider declaring it as object wrapper for the corresponding primitive type.”建議使用包裝類型代替基本類型,如使用“Integer”代替“int”
轉載于:https://www.cnblogs.com/zkycode/p/6272731.html
總結
以上是生活随笔為你收集整理的SpringMVC注解@RequestParam全面解析的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。