Spring MVC 07 - @ModelAttribute

@ModelAttribute 可以理解为Spring MVC中M - Model的载体,后台服务器将要用于展示的数据放入@ModelAttribute中,@ModelAttribute会将这些数据在页面中进行展示

1. @ModelAttribute在方法中使用

承接上一篇,@RequestParam回传的studentName和studentHobby是学生的属性,我们新建一个实体类Student.java

package com.haha;

public class Student {
private String studentName;
private String studentHobby;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
}

如果可以让实体类直接在页面和后台之间传输,免去@RequestParam一个个获取参数而后把参数放入实体的过程,可以让代码更简洁清晰,@ModelAttribute就可以实现这个功能,在这个时候,StudentAdmissionController,java代码应当如下:

package com.haha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentAdmissionController{
   
   @RequestMapping(value="/admissionForm.html",method = RequestMethod.GET)
   public ModelAndView getAdmissionForm(){
      ModelAndView model = new ModelAndView("AdmissionForm");
      return model;
   }

   @RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
   public ModelAndView submitAdmissionForm(@ModelAttribute("student1") Student student1){

       ModelAndView model = new ModelAndView("AdmissionSuccess");
       model.addObject("headerMessage","Hello, everyone");
       model.addObject("student1",student1);
       return model;
   }
}

可以在浏览器中输入url验证效果

猜你喜欢

转载自blog.csdn.net/u013537471/article/details/53015518