2015-10-13 42 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

相關問題