我的表单由一个项目组成,并且具有“数量”。当我输入一封信时,我希望它回来时出错。我在我的属性文件中尝试了“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";
}
}
spring消息告诉我们要在属性文件中放入什么:
拒绝价值[w];代码 [typeMismatch.item.quantity,typeMismatch.quantity,typeMismatch.java.lang.Integer,typeMismatch
我做错了什么?什么是秘诀?
答案 0 :(得分:1)
看起来你没有触发验证器。如果您使用的是Springframework Validator,则需要以下内容:
@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/