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  必须一这种类型访问才行

    一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰
  • 相关阅读:
    Apache ActiveMQ消息中间件的基本使用
    struts2结合生成验证码
    Python中docstring文档的写法
    Nginx+uWSGI+Django原理
    Python垃圾回收机制详解
    Python数据库连接池实例——PooledDB
    构建高可用服务端
    Python使用multiprocessing实现一个最简单的分布式作业调度系统
    python3 分布式进程(跨机器)BaseManager(multiprocessing.managers)
    python BaseManager分布式学习
  • 原文地址:https://www.cnblogs.com/wangbiaohistory/p/13151932.html
Copyright © 2011-2022 走看看