springmvc 05 @ModelAttribute注解

可参考

http://blog.csdn.net/hejingyuan6/article/details/49995987

被@ModelAttribute注释的方法会在此Handler每个方法执行前被执行
@ModelAttribute修饰void返回值的方法

testModelAttributeVoid
    @ModelAttribute
    public void modelAttributeVoid(
            @RequestParam(value="username") String username
            ,Model model){
        model.addAttribute("username", username);//model中数据会被被放到request域中
    }
    
    @RequestMapping("/testModelAttributeVoid")
    public String testModelAttributeVoid(){
        return MODELATTRIBUTE;
    }
username:${requestScope.username}

@ModelAttribute修饰返回Object的方法

testModelAttributeObject
    @ModelAttribute(value="myEmp")//指定model key
    public Emp modelAttributeObject(){
        Emp emp = new Emp(1,"George","boy");
        return emp;
        
        /*在@ModelAttribute没有指明key的情况下,return一个对象
         * 那么model==该对象,且model的key==类首字母小写
         * 如"emp"*/
    }
    
    @RequestMapping("/testModelAttributeObject")
    public String testModelAttributeObject(){
        return MODELATTRIBUTE;
    }
<%--    emp:${requestScope.emp} --%>
    emp:${requestScope.myEmp}

@ModelAttribute 对象合并

    testModelAttributeCombine

    @ModelAttribute(value="myEmp2")//指定model key
    public Emp modelAttributeCombine(){
        Emp emp = new Emp(1,"George","boy");
        return emp;
    }
    
    @RequestMapping("/testModelAttributeCombine")
    public String testModelAttributeCombine(
            @ModelAttribute(value="myEmp2") Emp emp){
        emp.setName("Murphy");
        return MODELATTRIBUTE;
        /* 在目标方法中获取的emp是被
         * @ModelAttribute修改且key为myEmp2的model数据*/
    }
    emp2:${requestScope.myEmp2}
//emp2:Emp(id=1, name=Murphy, sex=boy)

你可能感兴趣的:(springmvc 05 @ModelAttribute注解)