我有一个页面,其上有一个表单,用户可以在其中保存或删除bean。表单支持对象具有bean作为其属性。当用户选择删除bean时,不需要绑定bean,因为JPA只需要删除bean的id。
有没有告诉Spring MVC在某些条件下不绑定表单支持对象的某些属性?如果请求是删除,我想跳过其bean属性的绑定。
编辑:我正在使用Spring 3.这是伪代码。
@Controller
public class FormController {
@RequestMapping(method = RequestMethod.POST)
public void process(HttpServletRequest request) {
String action = request.getParameter("action");
if (action.equals("SAVE")) {
// bind all parameters to the bean property of the FormObject
}
else if (action.equals("DELETE")) {
// skip the binding. manually read the bean.id parameter.
int id = Integer.valueOf(request.getParameter("bean.id"));
EntityManager entityManager = ...
Bean bean = entityManager.getReference(Bean.class, id);
entityManager.remove(bean);
}
}
public class Bean {
private int id;
}
public class FormObject {
private Bean bean;
}
}
答案 0 :(得分:4)
您可以使用name
属性区分不同的提交按钮,并使用params
@RequestMapping
属性将这些按钮启动的请求路由到不同的处理程序方法。例如,在Spring 3中:
<input type = "submit" name = "saveRequest" value = "Save" />
<input type = "submit" name = "deleteRequest" value = "Delete" />
@RequestMapping(value = "/foo", method = RequestMethod.POST,
params = {"saveRequest"})
public String saveFoo(@ModelAttribte Foo foo, BindingResult result) { ... }
// Only "id" field is bound for delete request
@RequestMapping(value = "/foo", method = RequestMethod.POST,
params = {"deleteRequest"})
public String deleteFoo(@RequestParam("id") long id) { ... }
更“RESTful”的方法是将不同的提交按钮放入method = "PUT"
和method = "DELETE"
的不同表单中,并按方法区分请求(尽管需要使用HiddenHttpMethodFilter
的解决方法)。
答案 1 :(得分:3)