如何将通用对象发布到Spring控制器?

ste*_*oss 6 java spring spring-mvc

我想创建一个显示表单的网站.表单的字段取决于请求参数(以及表单支持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";
    }

}
Run Code Online (Sandbox Code Playgroud)

相应的视图如下所示:

<!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>
Run Code Online (Sandbox Code Playgroud)

以下是显示表单字段的示例片段:

<!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>
Run Code Online (Sandbox Code Playgroud)

查找的bean将是这样的:

public class MyExampleBean {

    private String firstName;

    private String lastName;

    // Getters & setters

}
Run Code Online (Sandbox Code Playgroud)

表单正确呈现,但我如何在控制器中收到表单?我如何验证提交的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;
}
Run Code Online (Sandbox Code Playgroud)

Spring创建了一个新实例,Object但提交的值将丢失.那么我该如何完成这项任务呢?

Ser*_*sta 4

如果您只想处理有限数量的 bean,则可以为每个 bean 使用一种方法,将所有方法委托给一个可以完成这项工作的@RequestMapping私有方法。您可以在此处找到示例。

如果您希望能够动态接受 bean,则必须手动执行Spring自动执行的操作:

  • 仅使用请求而不使用模型属性
  • PathVariable通过名称在注册表中查找 bean
  • 明确地进行绑定

但希望 Spring 提供 as helpers 的子类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;
}
Run Code Online (Sandbox Code Playgroud)