Spring MVC 07 - @ModelAttribute

@ModelAttribute can be understood as the carrier of M-Model in Spring MVC. The background server puts the data to be displayed into @ModelAttribute, and @ModelAttribute will display the data on the page.

1. @ModelAttribute is used in the method

Following the previous article, the studentName and studentHobby returned by @RequestParam are the attributes of the student. We create a new entity class 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;
}
}

If the entity class can be directly transferred between the page and the background, without the process of @RequestParam getting parameters one by one and then putting the parameters into the entity, the code can be more concise and clear, @ModelAttribute can achieve this function, at this time, StudentAdmissionController, the java code should be as follows:

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;
   }
}

You can enter the url verification effect in the browser

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325988347&siteId=291194637