@ModelAttribute用法
@ModelAttribute用法详解
1 用在方法上方式一
package com.sz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
@ModelAttribute
public void init(Model model){
model.addAttribute("girl","菲菲");
}
@RequestMapping("/m1")
public String m1(Model model) {
System.out.println(model.containsAttribute("girl"));
System.out.println(model.containsAttribute("girl2"));
return "msg";
}
}
// 结果为 true false
逻辑上任何具体请求处理之前先执行init方法,也就是说在model当中一定会存在init当中添加的内容。
2. 作为方法上方式二
package com.sz.controller;
import com.sz.pojo.Girl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
@ModelAttribute("girl")
public Girl init(Model model){
Girl g = new Girl();
g.setAge(28);
g.setName("菲菲");
return g;
}
@RequestMapping("/m1")
public String m1(Model model) {
System.out.println(model.containsAttribute("girl"));
System.out.println(model.containsAttribute("girl2"));
return "msg";
}
}
//结果为true false
3. 用在方法参数签名
package com.sz.controller;
import com.sz.pojo.Girl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/m2")
public String m2(@ModelAttribute("girl") Girl girl,Model model) {
System.out.println(model.containsAttribute("girl"));
System.out.println(model.containsAttribute("girl2"));
System.out.println(girl.getName() + girl.getAge());
return "msg";
}
}
// 结果为true false
4. 用在方法签名上并且使用路径变量绑定
@RequestMapping("/m2/{age}/{name}")
public String m2(@ModelAttribute Girl girl ,Model model ) {
System.out.println(model.containsAttribute("girl"));
System.out.println(model.containsAttribute("girl2"));
System.out.println(girl.getName() + girl.getAge());
return "msg";
}
// true
// false
// fifi28