碰到一个奇葩问题,就是访问表单html页面报错。
注意两个地方:
1、路径输入http://localhost:8080/web/person访问页面的时候,方法要带参数PersonForm2 person,不然会报错。原因,还没仔细查资料,大概是因为渲染页面中,没有找到对应的object对象。
2、html页面中th:object="${personForm2}",这个需要你所实例化bean的名字(首字母小写)。
@Controller @RequestMapping("/web") public class WebController extends WebMvcConfigurerAdapter { @GetMapping("/person") public String showForm(PersonForm2 person) { return "form2"; } @PostMapping("/addPerson") public String addPerson(@ModelAttribute("person") PersonForm2 person, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", "addPerson success: " + person != null ? person.getName() : "" + "!"); return "redirect:/results"; } }
<html> <body> <h3>Add Person</h3> <form action="#" th:action="@{/web/addPerson}" th:object="${personForm2}" method="post"> <p>Name: <input type="text" th:field="*{name}" /></p> <p>Age: <input type="text" th:field="*{age}" /></p> <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p> </form> </body> </html>