多个@ModelAttribute

Multiple @ModelAttribute

我在 JSP 文件中有 Spring MCV 表格:

<form:form action="confirm" modelAttribute="newStudent">
  <b>Personal info:</b><hr>
  <table>
    <tr>
        <td>First name:</td>
        <td>
            <form:input path="firstName" placeholder="Your first name?" />
            <form:errors path="firstName" cssClass="error"/>
        </td>
    </tr>

    <tr>
        <td>Last name:</td>
        <td>
            <form:input path="lastName" placeholder="Your second name?" />  
            <form:errors path="lastName" cssClass="error"/> 
       </td>
   </tr>
   <tr>
       <td>Country:</td>
       <td><form:select path="country">
           <form:options items="${newStudent.countryList}"/>
           </form:select></td>
   </tr>

  </table>
  <input type="submit" value="Submit"/>
</form:form>

还有两个 class:

public class NewStudent {


  //Countries List
  Map<String, String> countryList = new LinkedHashMap<>();

  public NewStudent() {
    countryList.put("US", "United States");
    countryList.put("UK", "United Kingdom");
    countryList.put("DE", "Germany");
  }

  public Map<String,String> getCountryList() {

    return countryList;
  }

/////

  @NotNull(message="Required!")
  @Size(min=3, message="At least 3 characters")
  @Pattern(regexp="[A-Za-z]+", message="Invalid name")
  private String firstName;

  @NotNull(message="Required!")
  @Size(min=3, message="At least 3 characters")
  @Pattern(regexp="[A-Za-z]+", message="Invalid last name")
  private String lastName;

  private String country;

  //setters, getters etc.
}

并且:

@Entity
@Table(name="new_students")
public class NewStudentEntity {
  @Id
  private int id;

  @Column(name="first_name")
  private String firstName;

  @Column(name="last_name")
  private String lastName;

  @Column(name="country")
  private String country;

  ...
}

我想做的是使用表单中的数据通过 @ModelAttribute 将其发送到 NewStudent class 以验证给定的数据并获取国家/地区列表,但是我还想将数据保存到数据库,所以我想将数据从表单发送到 Entity class。这可能吗?有什么方法可以在 Form 和 Controller class 中使用多个 @ModelAttribute 注释或任何不同的方法来修复它?

也许有不同的选择来解决这个问题,但我是这样解决的:

我将验证注释移动到实体 class,如下所示:

@Entity
@Table(name="new_students")
public class NewStudent {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")  
private int id;

@Column(name="first_name")
@NotNull(message="Required!")
@Size(min=3, message="At least 3 characters")
@Pattern(regexp="[A-Za-z]+", message="Invalid name")
private String firstName;

@Column(name="last_name")
@NotNull(message="Required!")
@Size(min=3, message="At least 3 characters")
@Pattern(regexp="[A-Za-z]+", message="Invalid last name")
private String lastName;

@NotNull(message="Select the country!")
@Column(name="country")
private String country;

然后将 countryListNewStudent 移动到 Controller class 并使用 addAttribute 将国家列表从 Controller 发送到 View .