我是Spring Boot的新手,我正在努力创建一个应用程序的正面连接到后面。
我使用过这个网站https://spring.io/guides/gs/validating-form-input/ 研究一个简单的例子,它工作得很好。它使用名称'名称'和'年龄'对于两个字段,getAge和getName等用于getter和setter。
此代码有效:
HTML表单:
<html>
<body>
<form action="#" th:action="@{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" /></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
Person java class
public class PersonForm {
@NotNull
@Size(min=2, max=30)
private String name;
@NotNull
@Min(18)
private Integer age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "Person(Name: " + this.name + ", Age: " + this.age + ")";
}
}
控制器
@Controller
public class WebController extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
@GetMapping("/")
public String showForm(PersonForm personForm) {
return "form";
}
@PostMapping("/")
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
我只是将变量的名称更改为以下内容:(2个字符串而不是int和字符串)。当我尝试查看页面时显示以下错误:执行处理器期间出错&org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor&#39; (形式:33)
第33行有&#34;个:字段=&#34; * {testcolumn}&#34; &#34;在上面。
是否有某些命名惯例,您可能必须遵循百里香?我找不到有关它的信息。感谢
人员类:
@NotNull
@Size(min=2, max=30)
private String testcolumn;
@NotNull
private String testcolumntwo;
public String getTestcolumn() {
return this.testcolumn;
}
public void setTestcolumn(String testcolumn) {
this.testcolumn = testcolumn;
}
public String getTestcolumntwo() {
return testcolumntwo;
}
public void setTestcolumntwo(String testcolumntwo) {
this.testcolumntwo = testcolumntwo;
}
public String toString() {
return "Person(Name: " + this.testcolumntwo + ", Age: " + this.testcolumntwo + ")";
}
HTML表单:
<form action="#" th:action="@{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{testcolumn}" /></td>
<td th:if="${#fields.hasErrors('testcolumn')}" th:errors="*{testcolumn}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{testcolumntwo}" /></td>
<td th:if="${#fields.hasErrors('testcolumntwo')}" th:errors="*{testcolumntwo}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>