1. 程式人生 > >Spring MVC 數據回顯

Spring MVC 數據回顯

shm 路徑 reac sdn scu 模型 查詢 表單 search

springmvc 的數據回顯

原創 2015年08月02日 11:39:00

1 數據回顯

1.1 什麽數據回顯

提交後,如果出現錯誤,將剛才提交的數據回顯到剛才的提交頁面。

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

1.2 pojo數據回顯方法

1、springmvc默認對pojo數據進行回顯。

pojo數據傳入controller方法後,springmvc自動將pojo數據放到request域,key等於pojo類型(首字母小寫)

修改信息editItems()方法中的標識是 model.addAttribute("itemsCustom",itemsCustom);

editItems.jsp頁面接收的標識為 <input type="hidden"name="id" value="${itemsCustom.id}"/>

提交修改的方法 public String editItemsSubmit(Modelmodel,HttpServletRequest request,Integer id,@Validated(value={ValidGrouop1.class}) ItemsCustom itemsCustom,BindingResult bindingResult)throws Exception

三者一致方可自動回顯

使用@ModelAttribute指定pojo回顯到頁面在request中的key

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

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

@ModelAttribute("item") 中的item 對應ItemsCustom itemsCustom 的itemsCustom 為itemsCustom的別名,用於保持和頁面的"${item.name }" 中的item 一致實現數據回顯

// 商品修改提交

@RequestMapping("/editItemSubmit")

public String editItemSubmit(Model model , @ModelAttribute("item") ItemsCustom itemsCustom)

頁面:

<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還可以將方法的返回值傳到頁面

在商品查詢列表頁面,通過商品類型查詢商品信息。

在controller中定義商品類型查詢方法,最終將商品類型傳到頁面。

//商品分類

//itemTypes表示最終將方法的返回值放在request中的key

@ModelAttribute("itemtypes")

public Map<String, String>getItemTypes(){

Map<String,String> itemTypes = new HashMap<String,String>();

itemTypes.put("101", "數碼");

itemTypes.put("102", "母嬰");

return itemTypes;

}

頁面上可以得到itemTypes數據。

商品分類:

<select name="itemtype">

<c:forEach items="${itemtypes }" var="itemtype">

<option value="${itemtype.key}">${itemtype.value }</option>

</c:forEach>

</select>

3、使用最簡單方法使用model,可以不用@ModelAttribute

@RequestMapping("/editItemsSubmit")

public StringeditItemsSubmit(Model model

,HttpServletRequest request,

Integerid,

@ModelAttribute("items")@Validated(value={ValidGrouop1.class}) ItemsCustom itemsCustom,

BindingResultbindingResult)throwsException{

//獲取驗證錯誤信息

if(bindingResult.hasErrors())

{

//輸出錯誤信息

List<ObjectError>allerrors=bindingResult.getAllErrors();

for(ObjectError error:allerrors)

{

System.out.println(error.getDefaultMessage());

}

//錯誤信息傳遞到頁面

model.addAttribute("allErrors",allerrors);

//使用model 的方式使數據回顯

model.addAttribute("items",itemsCustom);

return "items/editItems";

}

//調用service更新商品信息,頁面需要將商品信息傳到此方法

itemsService.updateItems(id,itemsCustom);

//重定向 不用加跟路徑

//return "redirect:queryItems.action";

//頁面轉發

return "forward:queryItems.action";

}

1.3 簡單類型數據回顯

使用最簡單方法使用model。

model.addAttribute("id", id);

僅供自己查閱參考使用,如有冒犯請留言聯系

轉載自: https://blog.csdn.net/u012373815/article/details/47205657 技術分享圖片

Spring MVC 數據回顯