• @ModelAttribute 注解及 POJO入参过程


    一、modelattribute注解

    @ModelAttribute注解的方法有两种,一种无返回值,一种有返回值,方法的可以用@RequestParam注解来获取请求的参数,如果不获取参数,可以不用此注解

    1)无返回值,用Map中的对象放入ImpliciteModel中,key就是map中存储的key.

        @ModelAttribute
        public void setUser(@RequestParam(value="name",required=false) String name, Map<String,Object> map)
        {
            Address ad=new Address();
            ad.setCity("beijing");
            ad.setProvince("china");
            User u=new User();
            u.setAge(15);
            u.setAddress(ad);
            if(name.equals("xp")){
                u.setWork("huajia");
            }
            else {
                u.setWork("gongchengshi");
            }
            map.put("user", u);
            System.out.println(u);
        }

    2)有返回值   把返回值对象放入ImpliciteModel中,key就是ModelAttribute定义的key:"user"

        @ModelAttribute("user")
        public User setUser(@RequestParam(value="name",required=false) String name)
        {
            Address ad=new Address();
            ad.setCity("beijing");
            ad.setProvince("china");
            User u=new User();
            u.setAge(15);
            u.setAddress(ad);
            if(name.equals("xp")){
                u.setWork("huajia");
            }
            else {
                u.setWork("gongchengshi");
            }
            System.out.println("用户"+u);
            return u;
        }

    总结:   @ModelAttribute("user")指定key为"user"时,若方法有返回值,则返回值会以指定的key,放入ImpliciteModel中;若方法没有返回值,但是方法中有相同key的map,则存入ImpliciteModel中key的为map中存的对象,若没有相同key的map,则存入ImpliciteModel中key对应的对象为null.若方法有返回值且方法中也有相同key的map,则以map对象优先。

                 @ModelAttribute没有指定key时,只能用Map将对象存入ImpliciteModel中。

    ImpliciteModel中的对象,可以认同为Request域中对象。

    二、 POJO入参过程

    1,检查implicite中是否存在相同key(默认为pojo类名小写,可以用@modelattribute指定)的值,有则传入,并用请求的参数值替换对应的值。

    2,若implicite中没有,则检查sessionattribute中是否相同key的值,有则同一,没有则抛异常(可以通过配置,避免异常)。

    3,若1、2中都没有,则通过反射创建对象,并用请求的参数值替换对应的值。最后再把对象存入implicite中。

  • 相关阅读:
    [Ramda] Getter and Setter in Ramda & lens
    [Angular2 Router] Index router
    [TypeScript] Using Interfaces to Describe Types in TypeScript
    [RxJS] ReplaySubject with buffer
    [Ramda] Declaratively Map Predicates to Object Properties Using Ramda where
    [Ramda] Pluck & Props: Get the prop(s) from object array
    [Ramda] Complement: Logic opposite function
    [TypeScript] Distinguishing between types of Strings in TypeScript
    [NodeJS] Use Now alias for custom sub-domains
    [CSS3] Create a fixed-fluid-fixed layout using CSS calc()
  • 原文地址:https://www.cnblogs.com/tyhj-zxp/p/5578136.html
Copyright © 2020-2023  润新知