2011-09-07 123 views
3

我的表單由一個Item組成,並且有一個「數量」。當我輸入一封信時,我希望它回來時發生錯誤。我試圖在我的屬性文件中「typeMismatch」,但它不起作用。Spring MVC number validation with typeMismatch

的Servlet:

<context:component-scan base-package="com.cat.jra.petstore.server.controller" /> 
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" p:viewClass="org.springframework.web.servlet.view.tiles2.TilesView" /> 
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="labels" /> 
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" p:definitions="/WEB-INF/tiles/tiles-defs.xml" /> 

表:

<div class="label"><fmt:message key="product.quantity.label"/></div> 
      <div class="input"><form:input path="quantity" size="10"/> <form:errors path="quantity" /></div> 

labels.properties

typeMismatch.quantity=Please enter a number, stupid... 
typeMismatch.item.quantity=dude... 
typeMismatch.java.lang.Integer=more dude... 
typeMismatch=markiscool 

控制器

@Controller 
@RequestMapping("/inventory/*") 
public class InventoryController { 
@RequestMapping(value = "save", method = RequestMethod.POST) 
    public String addItem(ModelMap map, Item item) { 
     System.out.println("addItem"); 

     return "redirect:list"; 
    } 
} 

彈簧消息告訴我們把正是在屬性文件:

拒絕值[W]代碼 [typeMismatch.item.quantity,typeMismatch.quantity,typeMismatch.java.lang.Integer,typeMismatch

我在做什麼錯?祕訣是什麼?

回答

1

它看起來像你沒有觸發驗證。如果您使用的是springframework的驗證,你需要像下面這樣:

@Controller 
@RequestMapping("/inventory/*") 
public class InventoryController { 

@Autowired 
private Validator inventoryValidator; 

@RequestMapping(value = "save", method = RequestMethod.POST) 
public String addItem(ModelMap map, Item item, 
     BindingResult result) { 

    System.out.println("addItem"); 

    inventoryValidator.validate(item, result); 
    if (results.hasErrors()) { 
     return *name of data entry page* 
    } else { 
     return "redirect:list"; 
    } 
} 
} 

如果你正在嘗試使用基於註解Hibernate的驗證,我建議在看這個頁面:

http://codemunchies.com/2010/07/spring-mvc-form-validation-with-hibernate-validator/