首页 > 代码库 > spring-Formatter(格式化器)-validator(验证器)-错误信息定制

spring-Formatter(格式化器)-validator(验证器)-错误信息定制

项目结构

技术分享技术分享

package app07a.controller;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import app07a.domain.Product;import app07a.validator.ProductValidator;@Controllerpublic class ProductController {    private static final Log logger = LogFactory            .getLog(ProductController.class);    @RequestMapping(value = "/product_input")    public String inputProduct(Model model) {        model.addAttribute("product", new Product());        return "ProductForm";    }    @RequestMapping(value = "/product_save")    public String saveProduct(@ModelAttribute Product product,            BindingResult bindingResult, Model model) {        logger.info("product_save");        System.out.println("prod save");        ProductValidator productValidator = new ProductValidator();        productValidator.validate(product, bindingResult);        if (bindingResult.hasErrors()) {            FieldError fieldError = bindingResult.getFieldError();            logger.info("Code:" + fieldError.getCode() + ", field:"                    + fieldError.getField());            return "ProductForm";        }        // save product here        model.addAttribute("product", product);        return "ProductDetails";    }}
package app07a.domain;import java.io.Serializable;import java.util.Date;public class Product implements Serializable {    private static final long serialVersionUID = 748392348L;    private String name;    private String description;    private Float price;    private Date productionDate;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }    public Float getPrice() {        return price;    }    public void setPrice(Float price) {        this.price = price;    }    public Date getProductionDate() {        return productionDate;    }    public void setProductionDate(Date productionDate) {        this.productionDate = productionDate;    }    }
package app07a.formatter;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;import org.springframework.format.Formatter;public class DateFormatter implements Formatter<Date> {    private String datePattern;    private SimpleDateFormat dateFormat;    public DateFormatter(String datePattern) {        this.datePattern = datePattern;        dateFormat = new SimpleDateFormat(datePattern);        dateFormat.setLenient(false);    }    @Override    public String print(Date date, Locale locale) {        return dateFormat.format(date);    }    @Override    public Date parse(String s, Locale locale) throws ParseException {        try {            return dateFormat.parse(s);        } catch (ParseException e) {            // the error message will be displayed when using <form:errors>            throw new IllegalArgumentException(                    "invalid date format. Please use this pattern\""                            + datePattern + "\"");        }    }}
package app07a.validator;import java.util.Date;import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;import app07a.domain.Product;public class ProductValidator implements Validator {    @Override    public boolean supports(Class<?> klass) {        return Product.class.isAssignableFrom(klass);    }    @Override    public void validate(Object target, Errors errors) {        Product product = (Product) target;        ValidationUtils.rejectIfEmpty(errors, "name", "productname.required");        ValidationUtils.rejectIfEmpty(errors, "price", "price.required");        ValidationUtils.rejectIfEmpty(errors, "productionDate", "productiondate.required");                Float price = product.getPrice();        if (price != null && price < 0) {            errors.rejectValue("price", "price.negative");        }        Date productionDate = product.getProductionDate();        if (productionDate != null) {            // The hour,minute,second components of productionDate are 0            if (productionDate.after(new Date())) {                System.out.println("salah lagi");                errors.rejectValue("productionDate", "productiondate.invalid");            }        }    }}
productname.required.product.name=Please enter a product nameprice.required=Please enter a priceproductiondate.required=Please enter a production dateproductiondate.invalid=Invalid production date. Please ensure the production date is not later than today.##productname.required=Please enter a product name
productname.required.product.name=\u8BF7\u8F93\u5165\u4EA7\u54C1\u7684\u540D\u5B57price.required=\u8BF7\u8F93\u5165\u4EF7\u683Cproductiondate.required=\u8BF7\u8F93\u5165\u751F\u4EA7\u65E5\u671Fproductiondate.invalid=Invalid production date. Please ensure the production date is not later than today.##productname.required=Please enter a product nametypeMismatch.price=\u683C\u5F0F\u4E0D\u6B63\u786EtypeMismatch.productionDate=\u65F6\u95F4\u683C\u5F0F\u4E0D\u6B63\u786E

两个配置文件,文件名字在截图里有,然后上面的java类也有名字对应就可以了

配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd             http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd">    <context:component-scan base-package="app07a.controller" />    <context:component-scan base-package="app07a.formatter" />    <mvc:annotation-driven conversion-service="conversionService" />    <mvc:resources mapping="/css/**" location="/css/" />    <mvc:resources mapping="/*.html" location="/" />    <bean id="viewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/" />        <property name="suffix" value=".jsp" />    </bean>         <bean id="messageSource"             class="org.springframework.context.support.ReloadableResourceBundleMessageSource">        <property name="basenames" >            <list>                <value>classpath:i18n_zh_CN</value>                <value>classpath:i18n_en_US</value>                            </list>                </property>    </bean>         <bean id="conversionService"        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">        <property name="formatters">            <set>                <bean class="app07a.formatter.DateFormatter">                    <constructor-arg type="java.lang.String" value="MM-dd-yyyy" />                </bean>            </set>        </property>    </bean></beans>

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head><meta charset="utf-8" /><title>Add Product Form</title><style type="text/css">@import url("<c:url value="http://www.mamicode.com/css/main.css"/>");</style></head><body><div id="global"><a>中文测试</a><form:form commandName="product" action="product_save" method="post">    <fieldset>        <legend>Add a product</legend>        <p class="errorLine">            <form:errors path="name" cssClass="error"/>        </p>        <p>            <label for="name">*Product Name: </label>            <form:input id="name" path="name" tabindex="1"/>        </p>        <p>            <label for="description">Description: </label>            <form:input id="description" path="description" tabindex="2"/>        </p>        <p class="errorLine">            <form:errors path="price" cssClass="error"/>        </p>        <p>            <label for="price">*Price: </label>            <form:input id="price" path="price" tabindex="3"/>        </p>        <p class="errorLine">            <form:errors path="productionDate" cssClass="error"/>        </p>        <p>            <label for="productionDate">*Production Date: </label>            <form:input id="productionDate" path="productionDate" tabindex="4"/>        </p>        <p id="buttons">            <input id="reset" type="reset" tabindex="5">            <input id="submit" type="submit" tabindex="6"                 value="Add Product">        </p>    </fieldset></form:form></div></body></html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head><title>View Product</title><style type="text/css">@import url("<c:url value="http://www.mamicode.com/css/main.css"/>");</style></head><body><div id="global">    <h4>${message}</h4>    <p>        <h5>Details:</h5>        Product Name: ${product.name}<br/>        Description: ${product.description}<br/>        Price: $${product.price}    </p></div></body></html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head><title>Save Product</title><style type="text/css">@import url("<c:url value="http://www.mamicode.com/css/main.css"/>");</style></head><body><div id="global">    <h4>The product has been saved.</h4>    <p>        <h5>Details:</h5>        Product Name: ${product.name}<br/>        Description: ${product.description}<br/>        Price: $${product.price}    </p></div></body></html>

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"         xmlns="http://java.sun.com/xml/ns/javaee"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>            org.springframework.web.servlet.DispatcherServlet        </servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/config/springmvc-config.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>        </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

效果截图

技术分享

 

spring-Formatter(格式化器)-validator(验证器)-错误信息定制