我正在使用 thymeleaf 和 Spring 。我想实现post请求。
我的 Controller 类是
public class URLController {
@RequestMapping(value = "index")
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
@RequestMapping(value = "/")
public String index(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
@PostMapping("/result")
public String result(@ModelAttribute Employee employee){
System.out.print(employee.getName());
return "result";
}
}
html 页面是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index page</title>
</head>
<body>
<form action="#" th:action="@{/result}" modelAttribute="employee" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>name: <input type="text" th:field="*{name}" /></p>
<p>phone: <input type="text" th:field="*{phone}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
没有与 id 字段绑定(bind)。
最佳答案
在 HTML 中,您需要对模型属性使用正确的语法。 Spring 提示找不到该属性 id
因为您提供字符串 employee
,而不是对象。
modelAttribute="employee" --> th:object="${employee}"
此外,您还可以合并到:
@Controller //please add this
public class URLController {
@GetMapping({"/", "/index"})
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
@PostMapping("/result")
public String result(@ModelAttribute Employee employee){
System.out.print(employee.getName()); //use a logger instead
return "result"; //may want to return a different page name for clarity
}
}
如果您将 HTML 标记更改为:
,您的 IDE 不会提示: <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
最后,您可能想使用 tel
电话字段的输入类型。这样做将允许为移动用户显示自定义键盘。
关于java - 错误:Neither BindingResult nor plain target object for bean name 'id' available as request attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019769/