【问题标题】:Selectively Binding a Property in Spring MVC在 Spring MVC 中选择性地绑定一个属性
【发布时间】:2010-11-07 21:22:31
【问题描述】:

我有一个页面,上面有一个表单,用户可以在其中保存或删除 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;
    }
}

【问题讨论】:

  • 给出:spring 版本和示例代码

标签: java spring spring-mvc


【解决方案1】:

您可以使用name 属性区分不同的提交按钮,并使用@RequestMappingparams 属性将这些按钮发起的请求路由到不同的处理程序方法。例如,在 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 的解决方法)。

【讨论】:

    【解决方案2】:

    您可以使用@InitBinder。

    @InitBinder
        public void setAllowedFields(WebDataBinder dataBinder) {
            dataBinder.setDisallowedFields("id");
        }
    

    herehere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多