数据回显

简单数据类型
对于简单数据类型,如: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的类名(首字母小写),如下:

controller方法:

//商品信息修改提交
//在需要校验的pojo前加@Validated,在其后加BindingResult bindingResult接收校验错误信息,他们是配对出现的
//指定使用分组校验value={ValidGroup1.class}
//@ModelAttribute("items")指定pojo回显到页面的request的key
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,HttpServletRequest request,Integer id,@ModelAttribute("items")
@Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult,
MultipartFile items_pic) throws Exception{```

jsp页面:



   
   
   ">
   
   


```


如果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 getItemTypes(){

    Map itemTypes = new HashMap();
    itemTypes.put("101", "数码");
    itemTypes.put("102", "母婴");
    
    return itemTypes;
}```

页面:
商品类型:

```

你可能感兴趣的:(数据回显)