springmvc @modelAttribute

在了解@modelAttribute前,我们首先来了解一下
model,modelMap,ModelAndView的区别
model:Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类
modelMap:键值对的map对象

public ModelMap addAttribute(String attributeName, Object attributeValue) {
        Assert.notNull(attributeName, "Model attribute name must not be null");
        this.put(attributeName, attributeValue);
        return this;
    }

ModelAndView:一个视图容器,简单点说就是Model+view

下面我们来看@modelAttribute
@modelAttribute可以放在方法体前,也可放在方法体中

方法体前
@ModelAttribute的目的是让该方法在访问requestmapping之前先被调用

@ModelAttribute
    public void testmodelattribute(@RequestParam("pet") int abc, Model model){
        model.addAttribute("attributeName", abc);
    }

隐式赋值,将返回值用model.addAttribute方法将该对象以键值对的形式存起来,key为类型名

@ModelAttribute
public Account addAccount(@RequestParam String number) {
    return accountManager.findAccount(number);
}

@ModelAttribute如果指定了属性名,且在方法体上存在返回值,则该返回值相当于key=attributeName,value = user

@ModelAttribute("attributeName")  
        public String addAccount(User user) {  
           return user;  
        }

@ModelAttribute可以写在requestMapping之前,不过返回值不是视图名,而是属性值,相当于在request中封装了key=attributeName,value=val,视图名会以”/helloWorld.do”转换为逻辑视图helloWorld来获取

@RequestMapping(value = "/helloWorld.do")  
        @ModelAttribute("attributeName")  
        public String test() {  
           return "val";  
        }  

方法体中
假如我们初始化一个model,并时期拥有值,我们可以通过@ModelAttribute(”user”)写在方法体中为其赋值,如下:

public class HelloWorldController {  

        @ModelAttribute("user")  
        public User addAccount() {  
           return new User("xiaoming","123456");  
        }  

        @RequestMapping(value = "/helloWorld")  
        public String helloWorld(@ModelAttribute("user") User user) {  
           system.out.println(user.getName())//xiaoming 
           return "helloWorld";  
        }  
    }

从Form表单或URL参数中获取值(可加可不加)

public class HelloWorldController {  
        @RequestMapping(value = "/helloWorld")  
        public String helloWorld(@ModelAttribute User user) {  
           system.out.println(user.getName())//xiaoming 
           return "helloWorld";  
        }  
    }

由于我们由表单获取的值可能会出现转化时失败,产生异常,这时我们可以做相关的校验,加入BindingResult 这个对象即可

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {

    if (result.hasErrors()) {
        return "petForm";
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章