2015-10-13 74 views
3

我正在开发使用Spring MVC 3注释样式控制器的应用程序。在某些场合,我需要根据会话变量或其他条件添加/修改某些字段值。使事情复杂化,如果某些条件匹配,则字段可能具有固定值,如果不匹配,则读取用户输入。问题是:有一种方法可以在绑定之后修改表单,但在使用spring mvc 3进行验证之前进行修改?正是有了SimpleFormController(onBind方法)很简单,但在Spring MVC中,我不能找到一种方法3.Spring MVC 3.如何在绑定之后但在验证之前修改表单

一个例子:

一)我初始化我的形式的粘合剂。添加一个验证器,设置允许的字段列表,并添加)通用属性编辑器的列表

@InitBinder(value = COMMAND_NAME) 
@Override 
public void initBinder(final WebDataBinder binder, final HttpServletRequest httpServletRequest) { 
    binder.setValidator(reenvioAsientoValidator); 
    binder.setAllowedFields(ReenvioAsientoForm.getListaCamposPermitidos()); 
    .... Add some custom property editors for booleans, integers .... 
} 

b创建模型对象

@ModelAttribute(value = COMMAND_NAME) 
public ReenvioAsientoForm rellenaModelo(final HttpServletRequest httpServletRequest) { 

    final ReenvioAsientoForm form = new ReenvioAsientoForm();  
    ... Add some field values, which cannot be modified by user ... 
    return form; 
} 

三)结合发生了:它可以修改任何字段位于allowedFields列表中。即使那些我在阶段b)

d)这是我不能做的事。我需要设置/修改表单的某些字段。不能在创建模型阶段完成,因为这些字段是allowedFields名单(根据不同的条件,他们可以是只读或接受用户输入)

E)发生了验证

F)控制器POST方法被调用

@RequestMapping(value = URI_REENVIO_ASIENTO, method = RequestMethod.POST) 
public ModelAndView submit(@Valid @ModelAttribute(COMMAND_NAME) final ReenvioAsientoForm form, final BindingResult result, HttpServletRequest request) { 
    ..... 
} 

出头的我已经试过:

内验证
  1. 修改,验证之前:这是一个可能的解决方案,但我觉得讨厌,因为... e我正在使用验证器来实现它不是有意的。另外它只在表单验证时才有效。
  2. 使用CustomPropertyEditor。这样我可以检查条件并在绑定期间设置值。问题在于仅当请求中存在属性时才会触发活页夹。如果有好歹总是启动它,这将是一个很好的解决方案

回答

3

最简单的解决方法是避免使用@Valid触发验证。

@Autowired 
Validator validator; 

@RequestMapping(value = URI_REENVIO_ASIENTO, method = RequestMethod.POST) 
public ModelAndView submit(@ModelAttribute(COMMAND_NAME) final ReenvioAsientoForm form, final BindingResult result, HttpServletRequest request) { 
    // here comes the custom logic 
    // that will be executed after binding and before validation 

    // trigger validation 
    validator.validate(form, result); 

    // handle validation result and return view name 
    ... 
} 

见春JIRA相关的问题和解释,这种钩/注解将无法实施 - @MVC should provide an "onBind" hook prior to automatic validation

+0

Tha you。我宁愿为后缀绑定分离的方法,但取消验证可能是最简单的方法。我还会看看您发布的有关RequestMappingHandlerAdapter的jira线程中提供的提示 – Rober2D2

相关问题