2011-09-07 154 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/