开发者

Spring MVC number validation with typeMismatch

My form consists of an Item and has a "quantity". When I enter a letter I want it to come back with an error. I have attempted the "typeMismatch" in my properties file, but it doesn't work.

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" />

Form:

 <div class="label"><fmt:message key="product.quantity.label"/></div>
            <div class="input"><form:input path="quant开发者_Go百科ity" 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

@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";
    }
}

The spring message tells us exactly what to put in the properties file:

rejected value [w]; codes [typeMismatch.item.quantity,typeMismatch.quantity,typeMismatch.java.lang.Integer,typeMismatch

What am I doing wrong? What is the secret sauce?


It looks like you aren't triggering a validator. If you are using the Springframework Validator, you would need something like the following:

@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";
    }
}
}

If you are trying to use the Hibernate annotation-based validation, I would recommend looking at this page:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜