2013-07-11 15 views
0

我正在使用spring mvc。在控制器中,我想將參數作爲Java Bean Order訂購。 Order bean有幾個參數,其中一個是dueDate(java.util.Date)。如何避免綁定爲java bean時彈簧mvc中的400錯誤

@RequestMapping("/toAddOrder") 
public ModelAndView addOrder(Order order, BindingResult bindingResult){ 
    return new ModelAndView("redirect:toViewOrder"); 
} 

@InitBinder 
protected void initBinder(
     WebDataBinder binder) throws ServletException { 
    binder.registerCustomEditor(byte[].class, 
      new ByteArrayMultipartFileEditor()); 

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
      dateFormat.setLenient(false); 
      binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); 
} 

問題是,如果在提交表單給控制器之前沒有爲dueDate設置值。然後會遇到錯誤。 BAD_REQUEST,因爲dueDate爲空或「」。

所以,我想知道,如何避免這個問題? 我能找到的解決方案如下。 1. js檢查提交表單之前。 2.沒有綁定的順序,從獲取參數HttpServletRequest請求

我發現最後2個解決方案的額外問題。 如果Order Bean有太多參數,那麼我需要編寫長代碼來獲取和設置值,這可能會在未來增加我的負擔。

+0

我認爲它應該幫助http://stackoverflow.com/questions/11118023/how-to-allow-null-date-in-spring-3-mvc/12476932#12476932 – mokshino

+0

我已經解決了這個問題。但我遇到了新問題。 –

回答

0

我已經解決了這個問題。因爲我是Spring MVC的新手。我嘗試了幾種方法。 但我認爲如果您遇到同樣的問題,遵循方法可能會有所幫助。

添加在你的控制器

@InitBinder 
protected void initBinder(WebDataBinder binder) throws ServletException { 
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
      dateFormat.setLenient(false); 
      binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); 
} 

但我見到了新的問題。

如果我提交表單中的值「」。我總是得到error.code typeMismatch

我已經在message.properties文件

#bean level error message 
typeMismatch.order.dueDate = order.dueDate format not match "YYYY-MM-DD" 

#global type not match message 
typeMismatch = data type not match 

但是,當我在頁面的頭打印錯誤訊息,我總是得到的代碼typeMismatch的ConfigEd但不typeMismatch.order.dueDate

<#if error?has_content> 
    <#list error.allErrors as item> 
     <@spring.message "${item.code?if_exists}"/><br/> 
    </#list> 
</#if> 

任何人都知道如何解決這個問題?

相關問題