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;

@Controller
public 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 name
price.required=Please enter a price
productiondate.required=Please enter a production date
productiondate.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\u5B57
price.required=\u8BF7\u8F93\u5165\u4EF7\u683C
productiondate.required=\u8BF7\u8F93\u5165\u751F\u4EA7\u65E5\u671F
productiondate.invalid=Invalid production date. Please ensure the production date is not later than today.
##productname.required=Please enter a product name
typeMismatch.price=\u683C\u5F0F\u4E0D\u6B63\u786E
typeMismatch.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="/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="/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="/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>

效果截图

时间: 2024-10-12 19:48:22

spring-Formatter(格式化器)-validator(验证器)-错误信息定制的相关文章

spring MVC 使用 hibernate validator验证框架,国际化配置

spring mvc使用hibernate validator框架可以实现的功能: 1. 注解java bean声明校验规则. 2. 添加message错误信息源实现国际化配置. 3. 结合spring form中的errors标签展现错误信息. 优势: 代码简洁. 实现: 1. 使用hibernate validator 至少要引入两个jar包: hibernate-validator-5.3.4.Final.jar , validation-api-1.1.0.Final.jar 2. JS

vue学习记录:vue引入,validator验证,数据信息,vuex数据共享

最近在学习vue,关于学习过程中所遇到的问题进行记录,包含vue引入,validator验证,数据信息,vuex数据共享,传值问题记录 1.vue 引入vue vue的大致形式如下: <template> </template> <script> </script> <style> </style> 要引入其他vue ,需要 import <template> <div> <Header></

[oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

form后台生成form里面的Input标签,以及设置Input的属性 # 需求 后台生成form里面的input标签,并设置input标签的属性, class RegisterForm(Form): email = fields.EmailField() password = fields.CharField() password2 = fields.CharField() code = fields.CharField() avatar = fields.FileField(widget=w

How to create XML validator(验证器;验证程序) from XML schema

In order to check XML data for validity we have to prepare its schema XSD-file. This file will be loaded by a JAXP package to a Schema objects instance. Then we'll use Schema to produce Validator which can then be used to validate any document with t

非空验证提示错误信息

//html页面 <div class="maxtop"> <a name="anchor_legalPersonName"></a> <div class="title">学校法人姓名</div> <div> <div id="text_red" class="red"></div> <div> &

Spring MVC -- 验证器

输入验证是Spring处理的最重要Web开发任务之一.在Spring MVC中,有两种方式可以验证输入,即利用Spring自带的验证框架,或者利用JSR 303实现.本篇博客将介绍这两种输入验证方法. 本篇博客用两个不同的示例分别介绍这两种方式:spring-validator和jsr303-validator. 一 验证概览 Converter和Formatter作用于字段级.在MVC Web应用中,它们将String类型转换或格式化成另一种Java类型,如java.time.LocalDat

5款最好的免费在线网站CSS验证器

这里是一个名单, 5免费在线CSS验证器的网站.这些网站让你验证你的CSS代码的自由,没有任何麻烦.你可以选择上传文件,验证CSS添加URL,或简单的复制和粘贴完整的CSS代码.好的方面是,这些网站不仅指出了代码中的错误,但他们也建议的方法可以解决. 所有这些网站都是很有用的学习者以及季节性的CSS的CSS码编码器.验证按照万维网联盟(W3C) 规则.让我们开始与这些网站: 1.W3C CSS Validator 我将开始列表与W3C本身即 W3C CSS验证器CSS验证器验证程序检查CSS代码

vue-validator(vue验证器)

官方文档:http://vuejs.github.io/vue-validator/zh-cn/index.html github项目地址:https://github.com/vuejs/vue-validator 单独使用vue-validator的方法见官方文档,本文结合vue-router使用. 安装验证器 不添加自定义验证器或者无需全局使用的公用验证器,在main.js中安装验证器,使用 CommonJS 模块规范, 需要显式的使用 Vue.use() 安装验证器组件. import

Ripple(瑞波币)validator-keys-tool 配置验证器

目录 Ripple(瑞波币)validator-keys-tool配置验证器 验证器密钥工具指南 验证器密钥 验证器令牌(Validator Keys) public_key撤销 签名 Ripple(瑞波币)validator-keys-tool配置验证器 验证器密钥工具指南 本指南介绍了如何设置validator,以便在rippled.conf 或服务器受到威胁时不必更改其公钥. 一个validator使用一对公钥/私钥.validator由公钥标识.应严保管私钥.它用于: 签署令牌,ripp