When SpringMVC data binding, the problem of one-to-one correspondence between form input values and entity data types

A small mistake in SpringMVC data binding made me doubt my life. Write it down quickly so that you don't make the same mistake again.

Model

public class Student{
    private String name;
    private Long id;
    private Integer age;

    // getter & setter
    ...
}

Controller

@Controller
public class StudentController {

   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute Student student, ModelMap model) {      
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());
      return "result";
   }
}

Form

<form:form method="post" action="addStudent">
   <table>
    <tr>
        <td><label >名字:</label></td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td><label >年龄:</label>
        <td><form:input path="age" /></td>
    </tr>
    <tr>
        <td><label >编号:</label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit form"/>
        </td>
    </tr>
</table>  
</form:form>

When filling out the form, the content of the number cannot be converted into the id of the entity class, and a 400 error will be reported at this time. If the id type of the entity class is changed to String, and the input content can be converted to String, it can be submitted normally; according to the id type Long given above, the value of this field can only be filled with a value, and the filled value can be converted to a Long type. No 400 error will be reported.

Since the form data is submitted in the form of a string, the background will convert the string value into the corresponding object type value according to the object type of the data binding, and if the string value is converted incorrectly, a 400 error will be raised. Therefore, the value filled in when filling out the form must be correctly converted into the corresponding type value of the entity, and there must be a one-to-one correspondence between them to be submitted normally.

The general solution to this problem is to check the validity of the form data and add validation.

Guess you like

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