thymeleaf配合@Valid注解进行表单校验出现400的报错,求助!

Spike_Li 2019-02-15 10:55:30
entity如下:
@Component
public class Customer {
@Size(min = 3,max = 16,message = "{name.size}")
private String name;

@Range(min = 1,max = 150,message = "{age.size}")
private int age;

public Customer() {
}

public Customer(@Size(min = 3, max = 16) String name, @Range(min = 1, max = 150) int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Controller如下
@Controller
@RequestMapping("/customer2")
public class SignUpController2 {
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String displayCustomerForm(Model model) {
model.addAttribute("customer", new Customer());
return "templates/registerForm";
}

@RequestMapping(value = "/sign",method = RequestMethod.POST)
public String signUp(@Valid Customer customer, Model model, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "templates/registerForm";
}else {
model.addAttribute("Customer",customer);
return "templates/success";
}
}
}

表单HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
label.error{
color:red;
}
input.error{
background:yellow
}
</style>
</head>
<body>
<!--th:object 代表命令对象也就是表单要绑定的对象,跟spring form表单绑定标签中commandName 绑定对象类似
当请求跳转到该页面需要相应的传一个带有key为user的对象,key默认为该对象类型的小写字母开头
th:action 代表要提交的表单链接, url格式为 @{}-->
<form th:object="${customer}" method="POST" th:action="@{/customer2/sign.html}">
<!--th:if 用来判断表单是否验证有误,有错误则显示出来无错则不显示-->
<div th:if="${#fields.hasErrors('*')}">
<ul>
<!--th:each遍历错误并通过ul列表显示出来-->
<li th:each="err:${#fields.errors('*')}" th:text="${err}">输入有误</li>
</ul>

</div>
<!--判断该字段是否验证有误,有错误则显示相应的css,该css可自定义-->
<label th:class="${#fields.hasErrors('name')}?'error'">Customer name:</label>
<input type="text" th:field="*{name}" th:class="${#fields.hasErrors('name')}?'error'">
<!--th:if 判断如果该字段验证错误,则展示span标签及错误信息,如果无错则不展现-->
<span th:if="${#fields.hasErrors('name')}" th:text="${#fields.errors('name')}"></span>
<br/>
<label th:class="${#fields.hasErrors('age')}?'error'">Customer age:</label>
<input type="text" th:field="*{age}" th:class="${#fields.hasErrors('age')}?'error'">
<span th:if="${#fields.hasErrors('age')}" th:text="${#fields.errors('age')}"></span>

<input type="submit" value="提交"/>
</form>

提交正确数据可以正常跳转,但提交错误的数据会报错400,不会出现错误信息,求助高手帮我看看。
...全文
56 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧