SpringMVC學習--數據回顯


  • 簡介

  表單提交失敗需要再回到表單頁面重新填寫,原來提交的數據需要重新在頁面上顯示。

  • 簡單數據類型

  對於簡單數據類型,如:Integer、StringFloat等使用Model將傳入的參數再放到request域實現顯示。

1 @RequestMapping(value="/editItems",method={RequestMethod.GET})
2     public String editItems(Model model,Integer id)throws Exception{
3         //傳入的id重新放到request域
4         model.addAttribute("id", id);
5 }

 

  • POJO類型

  springmvc默認支持pojo數據回顯,springmvc自動將形參中的pojo重新放回request域中,requestkeypojo的類名(首字母小寫),如下:

 

1 @RequestMapping("/editItemSubmit")
2     public String editItemSubmit(Integer id,ItemsCustom itemsCustom)throws Exception{
3 }

 

  springmvc自動將itemsCustom放回request,相當於調用下邊的代碼:model.addAttribute("itemsCustom", itemsCustom);

  頁面中的從“itemsCustom”中取數據。

  如果key不是pojo的類名(首字母小寫),可以使用@ModelAttribute完成數據回顯。

  @ModelAttribute作用如下:

  1、綁定請求參數到pojo並且暴露為模型數據傳到視圖頁面

  此方法可實現數據回顯效果。

1 // 商品修改提交
2     @RequestMapping("/editItemSubmit")
3     public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustom itemsCustom){
4 }

  如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成數據回顯。

  2、將方法返回值暴露為模型數據傳到視圖頁面

 

 1 //商品分類
 2     @ModelAttribute("itemtypes")
 3     public Map<String, String> getItemTypes(){
 4         
 5         Map<String, String> itemTypes = new HashMap<String,String>();
 6         itemTypes.put("101", "數碼");
 7         itemTypes.put("102", "母嬰");
 8         
 9         return itemTypes;
10     }

 

  商品類型:

1 <select name="itemtype">
2     <c:forEach items="${itemtypes }" var="itemtype">
3         <option value="${itemtype.key }">${itemtype.value }</option>        
4     </c:forEach>
5 </select>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM