【发布时间】:2015-06-03 09:28:25
【问题描述】:
我想创建一个显示表单的网站。 表单的字段取决于请求参数(以及表单支持 bean)。 这是我呈现不同形式的控制器:
@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";
}
}
对应的视图如下所示:
<!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
}
表单已正确呈现,但我如何才能在控制器中接收回表单? 以及如何验证提交的 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 的新实例,但提交的值丢失了。
那么我该如何完成这个任务呢?
【问题讨论】:
-
看起来是范围问题,是否有参数告诉您想要该表单的会话范围?
-
我没有在表单上设置范围。
标签: java spring spring-mvc