问题描述
<form th:action="@{/save}" method="post">
<label>用户姓名:<input type="text" name="name"/><font color="red" th:errors="${users.name}"></font></label><br/>
<label>用户密码:<input type="password" name="password"/><font color="red" th:errors="${users.password}"></font></label><br/>
<label>用户年龄:<input type="text" name="age"/><font color="red" th:errors="${users.age}"></font></label><br/>
<button>提交</button>
</form>
org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring4.processor.SpringErrorsTagProcessor' (template: "addUser" - line 9, col 65)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117) ~[thymeleaf-3.0.2.RELEASE.jar:3.0.2.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.2.RELEASE.jar:3.0.2.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.2.RELEASE.jar:3.0.2.RELEASE]
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'users' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:307) ~[thymeleaf-spring4-3.0.2.RELEASE.jar:3.0.2.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:258) ~[thymeleaf-spring4-3.0.2.RELEASE.jar:3.0.2.RELEASE]
at org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:227) ~[thymeleaf-spring4-3.0.2.RELEASE.jar:3.0.2.RELEASE]
解决办法:
方法1,在跳转到添加页面添加users对象
/*
* 解决异常方式,可以在跳转页面的方法注入一个Users对象
* 注意:由于springmvc会将该对象放到Model中传递,
* key的名称会使用该对象驼峰式的命名规则来做为key
* 所以参数的变量名需要与对象的名称相同,将首字母小写
*/
@RequestMapping("/addUser")
public String showPage(Users users) {
return "addUser";
}
方法2,修改controller和html
@RequestMapping("/addUser")
public String showPage(@ModelAttribute("aa") Users users) {
return "addUser";
}
<form th:action="@{/save}" method="post">
<label>用户姓名:<input type="text" name="name"/><font color="red" th:errors="${aa.name}"></font></label><br/>
<label>用户密码:<input type="password" name="password"/><font color="red" th:errors="${aa.password}"></font></label><br/>
<label>用户年龄:<input type="text" name="age"/><font color="red" th:errors="${aa.age}"></font></label><br/>
<button>提交</button>
</form>
@RequestMapping("/save")
public String saveUser(@ModelAttribute("aa") @Valid Users users,BindingResult result) {
System.out.println(users);
if(result.hasErrors()) {
return "addUser";
}
return "ok";
}
建议都用方法1