我想创建一个显示表单的网站。 表单的字段取决于请求参数(以及表单支持 bean)。 这是我的呈现不同形式的 Controller :
@Controller
public class TestController {
@Autowired
private MyBeanRegistry registry;
@RequestMapping("/add/{name}")
public String showForm(@PathVariable String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("bean", registry.lookup(name));
return "add";
}
}
相应的 View 如下所示:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<form method="post" th:action="@{|/add/${name}|}" th:object="${bean}">
<th:block th:replace="|${name}::fields|"></th:block>
<button type="submit">Submit</button>
</form>
</body>
</html>
以下是显示表单字段的示例片段:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<th:block th:fragment="fields">
<label for="firstName">First name</label><br />
<input type="text" id="firstName" th:field="*{firstName}" /><br />
<label for="lastName">Last name</label><br />
<input type="text" id="lastName" th:field="*{lastName}" />
</th:block>
</body>
</html>
查找到的bean是这样的:
public class MyExampleBean {
private String firstName;
private String lastName;
// Getters & setters
}
表单已正确呈现,但如何在 Controller 中接收表单? 我如何验证提交的 bean?我尝试了以下方法,但显然 它不能工作:
@RequestMapping(value = "/add/{name}", method = RequestMethod.POST)
public String processForm(@PathVariable String name, @Valid Object bean) {
System.out.println(bean);
return "redirect:/add/" + name;
}
Spring 创建了一个新的 Object
实例,但是提交的值丢失了。
那么我该如何完成这个任务呢?
最佳答案
如果您只想处理有限数量的 bean,您可以为每个 bean 使用一个 @RequestMapping
方法,所有方法都委托(delegate)给一个私有(private)方法来完成这项工作 em>。你可以找到一个例子 here .
如果您希望能够动态地接受 bean,您将不得不手动 Spring 自动执行的操作:
- 只使用请求而不是模型属性
- 通过
PathVariable
名称在注册表中找到 bean - 明确地进行绑定(bind)
但希望 Spring 提供 WebDataBinder
的子类作为助手:
@RequestMapping(value = "/add/{name}", method = RequestMethod.POST)
public String processForm(@PathVariable String name, WebRequest request) {
//System.out.println(bean);
Object myBean = registry.lookup(name);
WebRequestDataBinder binder = new WebRequestDataBinder(myBean);
// optionnaly configure the binder
...
// trigger actual binding of request parameters
binder.bind(request);
// optionally validate
binder.validate();
// process binding results
BindingResult result = binder.getBindingResult();
...
return "redirect:/add/" + name;
}
关于java - 如何将通用对象发布到 Spring Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616051/