SpringMVC学习--数据回显

时间:2023-03-09 06:00:45
SpringMVC学习--数据回显
  • 简介

  表单提交失败需要再回到表单页面重新填写,原来提交的数据需要重新在页面上显示。

  • 简单数据类型

  对于简单数据类型,如: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);
}
  • POJO类型

  springmvc默认支持pojo数据回显,springmvc自动将形参中的pojo重新放回request域中,request的key为pojo的类名(首字母小写),如下:

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

  springmvc自动将itemsCustom放回request,相当于调用下边的代码:model.addAttribute("itemsCustom", itemsCustom);

  页面中的从“itemsCustom”中取数据。

  如果key不是pojo的类名(首字母小写),可以使用@ModelAttribute完成数据回显。

  @ModelAttribute作用如下:

  1、绑定请求参数到pojo并且暴露为模型数据传到视图页面

  此方法可实现数据回显效果。

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

  如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成数据回显。

  2、将方法返回值暴露为模型数据传到视图页面

 //商品分类
@ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){ Map<String, String> itemTypes = new HashMap<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>