我有一个 Spring 2.5 带注释的控制器,其中有一个用 @RequestMapping(method=RequestMethod.GET) 注释的方法,它执行一些逻辑来填充模型。
我还有一个用 @RequestMapping(method=RequestMethod.POST) 注释的方法来执行请求。这个方法有一个@ModelAttribute注解的参数,里面包含了我自己的表单pojo,我们称之为MyForm。我还有一个 MyForm 的初始化方法,也用 @ModelAttrribute 注释。现在到目前为止一切都按预期工作:在 POST 请求中,表单数据绑定到 MyForm,我可以处理它。
问题是我希望能够通过传入(GET)请求参数来预填充表单。因为我有 MyForm 的 @ModelAttribute 方法,所以我在我的模型中得到了一个 MyForm 实例,但它不会被填充,除非我专门将它用作我的 GET 方法的参数。
为什么我必须这样做,是否可以以不同的方式在我的表单上强制数据绑定以获取 GET 请求?我现在只是传入参数,但是因为它已经在模型中,所以我不必对它做任何事情,从而导致丑陋的未使用方法参数。
[编辑:一些代码示例来说明]
在获取请求时不填充表单的控制器:
@Controller
public class MyController {
@ModelAttribute("myForm")
public MyForm createForm() {
return new MyForm();
}
@RequestMapping(method=RequestMethod.GET)
public void handlePage(Model model) {
//Do some stuff to populate the model....
}
@RequestMapping(method=RequestMethod.POST)
public void processForm(@ModelAttribute("myForm") MyForm myForm) {
//Process the form
}
}
当我更改 handlePage 方法的方法签名时,它会在获取请求中填充...
@RequestMapping(method=RequestMethod.GET)
public void handlePage(Model model, @ModelAttribute("myForm") MyForm myForm) {
//Do some stuff to populate the model....
}