zoukankan      html  css  js  c++  java
  • Spring 数据绑定

    Spring Web MVC 提供Model、Map或ModelMap让我们能去暴露渲染视图需要的模型数据。

    一:通常在action 中的 控制方法中,将方法形参作为model,来接收页面值
    页面:
    jsp:         <input type="text"  name="username" />  
          <input type="text"  name="password"  />

    action:    public ModelAndView (.., ..,  User user ){}      对象User{ username,password}

    二: 页面传值 支持  对象图导航式 传值
    jsp: <input type="text"  name="userExt.userAge" />   对象User{username,password,userExt}  
    对象 UserExt{ userAge,List<String> likes}
    action: public ModelAndView (.., ..,  User user ){}    userExt.userAge 会传入到user中

    多个同名参数  可用List 来接收参数


    三:关于model 接收展示的一个点
    @RequestMapping(value = "/mergeModel")
    public ModelAndView mergeModel(Model model) {
    model.addAttribute("a", "a");//①添加模型数据
    ModelAndView mv = new ModelAndView("success");
    mv.addObject("a", "update");//②在视图渲染之前更新③处同名模型数据
    model.addAttribute("a", "new");//③修改①处同名模型数据
    //视图页面的a将显示为"update" 而不是"new"
    return mv;
    }
    如果model中的对象属性名相同,最终以ModelAndView中的添加属性为最终覆盖

    四:@ModelAttribute()
    1、可以接收页面数据
    2、可以初始化页面展示的数据模型:
    @ModelAttribute("cityList")
     public List<String> cityList() {
     return Arrays.asList("北京", "山东");
     }
    如上代码会在执行功能处理方法之前执行,并将其自动添加到模型对象中,
    在功能处理方法中调用Model 入参的 containsAttribute("cityList")将会返回true

          3、可以注解返回的命令对象别名
    public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)

    返回值的model名称会覆盖 参数中的model名称

          4、匿名绑定参数
    public String test4(@ModelAttribute UserModel user, Model model) 或
           
    public String test5(UserModel user, Model model) 
    匿名返回model 时  UserModel 默认为userModel
           
    public @ModelAttribute List<String> test6() 或
           
    public @ModelAttribute List<UserModel> test7()
           
    对于集合类型(Collection接口的实现者们,包括数组),生成的模型对象属性名为“简单类名(首字母小写)”+“List”,
           
    如List<String>生成的模型对象属性名为“stringList”,List<UserModel>生成的模型对象属性名为“userModelList”

    五: 关于model 中存储的List/Map 类型的数据 的展现方式
    public String showUsers(ModelMap model){
    model.addAttribute("list"  users);
    } 
    页面中直接用El的方式拿值即可,${requestScope.list[0]}

    六:关于绑定在session 的数据
    @SessionAttributes(value = {"user"}) //①
    public class SessionAttributeController{
    @ModelAttribute("user") //②
    public UserModel initUser()

    }

    @SessionAttributes(value = {"user"}) 标识将2中的user  保存到 session 中 

  • 相关阅读:
    [计算机视觉]算法
    [python]python中**是什么
    ubuntu16.04增大swap空间
    conda查看某个安装包的依赖项
    conda install -c anaconda
    conda安装指定版本的指定包
    ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/
    [ubuntu]卸载老版并安装最新版firefox
    使用anaconda创建tensorflow环境后如何在jupyter notebook中使用
    [python]numpy.mean()用法
  • 原文地址:https://www.cnblogs.com/leonkobe/p/3545786.html
Copyright © 2011-2022 走看看