springMvc前後端傳值

在SpringMVC後臺控制層獲取參數的方式主要有兩種,一種是request.getParameter("name"),另外一種是用註解@RequestParam直接獲取。這裏主要講這個註解 

一、基本使用,獲取提交的參數 
後端代碼: 
Java代碼  收藏代碼
  1. @RequestMapping("testRequestParam")    
  2.    public String filesUpload(@RequestParam String inputStr, HttpServletRequest request) {    
  3.     System.out.println(inputStr);  
  4.       
  5.     int inputInt = Integer.valueOf(request.getParameter("inputInt"));  
  6.     System.out.println(inputInt);  
  7.       
  8.     // ......省略  
  9.     return "index";  
  10.    }     


前端代碼: 
Html代碼  收藏代碼
  1. <form action="/gadget/testRequestParam" method="post">    
  2.      參數inputStr:<input type="text" name="inputStr">    
  3.      參數intputInt:<input type="text" name="inputInt">    
  4. </form>  


前端界面: 
 

執行結果: 
test1 
123 

可以看到spring會自動根據參數名字封裝進入,我們可以直接拿這個參數名來用 

二、各種異常情況處理 
1、可以對傳入參數指定參數名 
Java代碼  收藏代碼
  1. @RequestParam String inputStr  
  2. // 下面的對傳入參數指定爲aa,如果前端不傳aa參數名,會報錯  
  3. @RequestParam(value="aa") String inputStr  

錯誤信息: 
HTTP Status 400 - Required String parameter 'aa' is not present
 

2、可以通過required=false或者true來要求@RequestParam配置的前端參數是否一定要傳 
Java代碼  收藏代碼
  1. // required=false表示不傳的話,會給參數賦值爲null,required=true就是必須要有  
  2. @RequestMapping("testRequestParam")    
  3.     public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)  


3、如果用@RequestMapping註解的參數是int基本類型,但是required=false,這時如果不傳參數值會報錯,因爲不傳值,會賦值爲null給int,這個不可以 
Java代碼  收藏代碼
  1. @RequestMapping("testRequestParam")    
  2.    public String filesUpload(@RequestParam(value="aa", required=true) String inputStr,   
  3.         @RequestParam(value="inputInt", required=falseint inputInt  
  4.         ,HttpServletRequest request) {    
  5.       
  6.     // ......省略  
  7.     return "index";  
  8.    }  


解決方法: 
    “Consider declaring it as object wrapper for the corresponding primitive type.”建議使用包裝類型代替基本類型,如使用“Integer”代替“int”
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章