zoukankan      html  css  js  c++  java
  • @ModelAttribute 与@InitBinder

    3.4.6 @ModelAttribute 注解 Mod lAttribut 通常作用在 Controller 的某个方法上,此方法会首先被调用,

    井将方法 结果作为 Model 的属性 然后再调用对应的 Controller 处理方法。

    @ModelAttribute

    public void findUserByid (@PathVariable Long id, Model model ) {

                model . addAttribute (”user”, userService . getUserByid(id));

    }

    @GetMapping(path = ” /{ id)/get . json”)

    @ResponseBody

    public Str ng getUser (Model model) {

          System. out .println (model . containsAttri bute (” use r ”) ) ;

          return ” success”;

    }

    对于 HTTP 的请求 mod lat ibute t. on 会先调用 findUserByld 方法取得 user 并添 加到模型里。

    使用 Mode!Attribute 通常可以用来向一个 Controller 中需要的公共模型添加数据。

    如果 findUserByid 仅仅添加一个对象到 Model ,则可以改写成如下形式

    @ModelAttribute

    public User findUserByid(@PathVariab l e Long id) {

    return userService . getUserByid(id) ;

    }

    这样 返回的对象自动添加到 Model 中,相当于调用 model.addA ribute(user)

     Controller 中用注解@InitBind 声明一个方法,来自 己扩展绑定的特性,

    比如:

    @Controller public class MyFormController {

    @InitBinder

    protected void in tBinder(WebDataBinder binder) {

    binder.addCustomFormatter(new DateFormatter (” yyyy- MM-dd” ))

    };

    @ResponseBody

    @RequestMapping (” / date ” ) public void printDate(Date d ) {

    System.out printl (d)

    return;

    }

    当需要绑定到一 Date 类型的时候,如上述代码所示, 采用“归号y-MM-dd ”格式,比 如用户访 databind/date 2010-1-1  必须一这种类型访问才行

    一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰
  • 相关阅读:
    JavaScript操作符instanceof揭秘
    Linux打开txt文件乱码的解决方法
    Working copy locked run svn cleanup not work
    poj 2299 UltraQuickSort 归并排序求解逆序对
    poj 2312 Battle City 优先队列+bfs 或 记忆化广搜
    poj2352 stars 树状数组
    poj 2286 The Rotation Game 迭代加深
    hdu 1800 Flying to the Mars
    poj 3038 Children of the Candy Corn bfs dfs
    hdu 1983 Kaitou Kid The Phantom Thief (2) DFS + BFS
  • 原文地址:https://www.cnblogs.com/wangbiaohistory/p/13151932.html
Copyright © 2011-2022 走看看