@Bean("person")
@Before
public Person createPerson(){
return new Person();
}
@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
...
}
在给定的例子中,@ModelAttribute将创建一个由你(@ModelAttribute("Testing") Test test) as Testing指定的名称的属性,Test是bean Test是bean的引用,并且Testing将在模型中可用,以便你可以进一步在jsp页面上使用它来检索存储在你ModelAttribute中的值。
@RequestMapping("/showForm")
// `Model` is used to pass data between controllers and views
public String showForm(Model theModel) {
// attribute name, value
theModel.addAttribute("student", new Student());
return "form";
}
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent) {
System.out.println("theStudent :"+ theStudent.getLastName());
return "form-details";
}
//@ModelAttribute("student") Student theStudent
//Spring automatically populates the object data with form data
//all behind the scenes
< p >步骤1:
请求被发送,我们的方法showForm()运行,一个模型,一个临时bean,被设置为student并被转发到表单: theModel.addAttribute("student", new Student()); < / p >
< p >步骤2:
表单属性modelAttribute="student"定义了在表单提交时,模型将更新学生并保存表单的所有参数
< p >步骤3:
在表单提交时,使用参数@ModelAttribute("student") Student theStudent调用processForm()方法:在带有modelAttribute="student"的表单中保存的值被提取并分配给Student对象中的字段
< p >步骤4:
然后我们使用它作为我们出价,就像在页面上显示它等,就像我做的
@Controller //Not @RestController
public class StudentController {
@ModelAttribute(name = "attribute1")
public int assignAttribute1() {
return 123454321
} // Think it as "model.attribute1 = 123454321"
@GetMapping(/students)
public String getStudentView() {
return "student";
}
}
<div> 123454321 </div> // th:text is a command of
//THymeleaf, and says to substitute the text
// between the tags with the attribute "attribute1"
// of our model passed to this view.