1 數據回顯
1.1 什麼數據回顯
提交後,如果出現錯誤,將剛纔提交的數據回顯到剛纔的提交頁面。
1.2 pojo數據回顯方法
1、springmvc默認對pojo數據進行回顯。
pojo數據傳入controller方法後,springmvc自動將pojo數據放到request域,key等於pojo類型(首字母小寫)
使用@ModelAttribute指定pojo回顯到頁面在request中的key
2、@ModelAttribute還可以將方法的返回值傳到頁面
1.1.1 簡單數據類型
對於簡單數據類型,如:Integer、String、Float等使用Model將傳入的參數再放到request域實現顯示。
如下:
@RequestMapping(value="/editItems",method={RequestMethod.GET})
public String editItems(Model model,Integer id)throws Exception{
//傳入的id重新放到request域
model.addAttribute("id", id);
1.1.2 pojo類型
springmvc默認支持pojo數據回顯,springmvc自動將形參中的pojo重新放回request域中,request的key爲pojo的類名(首字母小寫),如下:
controller方法:
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Integer id,ItemsCustom itemsCustom)throws Exception{
springmvc自動將itemsCustom放回request,相當於調用下邊的代碼:
model.addAttribute("itemsCustom", itemsCustom);
jsp頁面:
頁面中的從“itemsCustom”中取數據。
如果key不是pojo的類名(首字母小寫),可以使用@ModelAttribute完成數據回顯。
@ModelAttribute作用如下:
1、綁定請求參數到pojo並且暴露爲模型數據傳到視圖頁面
此方法可實現數據回顯效果。
// 商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustomitemsCustom)
頁面:
<tr>
<td>商品名稱</td>
<td><input type="text"name="name" value="${item.name }"/></td>
</tr>
<tr>
<td>商品價格</td>
<td><input type="text"name="price" value="${item.price }"/></td>
</tr>
如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成數據回顯。
2、將方法返回值暴露爲模型數據傳到視圖頁面
//商品分類
@ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){
Map<String, String> itemTypes = newHashMap<String,String>();
itemTypes.put("101", "數碼");
itemTypes.put("102", "母嬰");
return itemTypes;
}
頁面:
商品類型:
<select name="itemtype">
<c:forEach items="${itemtypes }"var="itemtype">
<option value="${itemtype.key }">${itemtype.value }</option>
</c:forEach>
</select>