我在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>
两个班级:
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;
...
}
我想要做的是使用表单中的数据通过NewStudent
将其发送到@ModelAttribute
类以验证给定数据并获取国家/地区列表,但我还想保存数据到数据库所以我想从表单发送数据到Entity
类。这可能吗?有没有办法在Form和@ModelAttribute
类中使用多个Controller
注释或以任何不同的方式来修复它?
答案 0 :(得分:0)
也许有不同的选择来解决这个问题,但我以这种方式解决了这个问题:
我将验证注释移到了实体类,如下所示:
@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;
然后将countryList
从NewStudent
移至Controller
类,并使用addAttribute将国家/地区列表从Controller
发送到View
。