SpringMVC 数据的格式化、JSR 303数据校验和国际化


这里写图片描述


1 数据的格式化

User.java

public class User {

    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
    .
    .
}

例如 User类 的属性 birth 是一个 Date 类型,必须在实体类中声明格式,否则不能从表单提交到 @Controller注解的类中对应的方法处理。

2 JSR 303数据校验

JSR 303是 Java 为 Bean 数据合法性校验提供给的标准框架,已经包含在 JavaEE6.0中、JSR 303通过在Bean 属性中标注类似 @NotNull @Max 等标准的注解指定校验规则,并通过标准的验证接口对 Bean进行验证

HIbernate Validator 是 JSR 303 的一个参考实现,除了支持所有标准的校验注解外,
它还支持一些扩展注解,下面是详细的注解列表

JSR 303中含有的注解

@Null   被注释的元素必须为 null  
@NotNull    被注释的元素必须不为 null  
@AssertTrue     被注释的元素必须为 true  
@AssertFalse    被注释的元素必须为 false  
@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@Size(max=, min=)   被注释的元素的大小必须在指定的范围内  
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内  
@Past   被注释的元素必须是一个过去的日期  
@Future     被注释的元素必须是一个将来的日期  
@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式  
------------------------------  
Hibernate Validator 附加的注解
@NotBlank(message =)   验证字符串非null,且长度必须大于0  
@Email  被注释的元素必须是电子邮箱地址  
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内  
@NotEmpty   被注释的字符串的必须非空  
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内  

3 JSR 303数据校验在Spring中使用

Spring 4.0拥有自己的数据库校验框架,同时支持JSR 303标准校验框架。
Spring 在进行数据绑定时,可同时调用校验框架完成校验工作。在SpringMVC中,可直接通过注解驱动的方式进行数据校验

Spring 的LocalValidatorFactoryBean 即实现了Spring的Validator 接口,也实现了JSR 303 的Validator 接口。
只要在Spring 容器中定义一个LocalValidatorFactoryBean ,即可将其注入到需要数据校验的 Bean中。

Spring 本身并没有提供JSR 303 的实现,所有必须将JSR 303的实现者的jar 包(HIbernate Validator jar包)导入到项目中

Maven 仓库地址:

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.3.4.Final</version>
</dependency>

<mvc:annotation-driven>会默认装配好一个LocalValidatorFactoryBean,通过在处理方法的入参上标注 @Valid 注解即可让 SpringMVC 在完成数据绑定后执行数据校验工作
在已经标注了 JSR 303 注解的表单、命令对象前标注一个@Valid,SpringMVC框架在将请求参数绑定到该入参对象后,就会调用校验框架根据注解声明的校验规则实施校验

4 校验信息如何显示

SpringMVC 除了会将表单、命令对象的校验结果保存到对应的 BindingResult 或Error对象外,还会将所有校验结果保存到“隐含模型”。
即使处理方法中的签名中没有对应于表单/命名对象的结果入参,校验结果也会保存在“隐含对象”中。

(比如User的IDCard没有指定校验的注解,可以它要求是Float型,输入String型数据,发生类型错误也会保存到隐含对象中输出)

隐含模型中的所有数据最终将通过HttpServletRequest的属性列表暴露个JSP视图对象,因此在JSP中可以获取错误信息
在JSP页面上可通过下面的标签显示

<form:errors path="*" /> 显示表单所有错误
<form:errors path="user* /> 显示所有以user为前缀的属性对应的错误
<form:errors path="username"/> 显示特定表单对象属性的错误

5 国际化

当使用 SpringMVC 标签显示错误消息时,SpringMVC 会查看WEB上下文是否装配了对应的国际化消息,如果没有,则显示默认的错误消息,否则使用国际化消息

若数据类型转换或数据格式转换时发生错误,或该有的参数不存在,或调用处理方法时发生错误,都会在隐含模型创建错误消息,其错误代码前缀(在国际化文件中配置)说明如下:

  • required:必要的参数不存在。
    @RequiredParam("param1")标注了一个入参,但是该参数不存在

  • typeMismatch :在数据绑定是,发生数据类型不匹配的问题

  • methodInvocation :SpringMVC 在调用处理方法时发生了错误

例如:
i18n_zh_CN.properties

NotEmpty.user.name= \u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A\u554A
Email.user.email= \u90AE\u7BB1\u683C\u5F0F\u4E0D\u5BF9\u54E6
Past.user.birth= \u4F60\u51FA\u751F\u65E5\u671F\u5728\u660E\u5929\uFF1F
typeMismatch.user.birth=Birth\u4E0D\u662F\u4E00\u4E2A\u65E5\u671F

在SpringMVC中配置

    <!--配置国际化资源文件-->
     <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n"></property>
        </bean>

6 项目结构

这里写图片描述

这里写图片描述

红色标注的为 HIbernate Validator jar包
官网下载地址 http://hibernate.org/validator/
解压后,使用dist\dist\lib\required两个目录下部分jar包

源代码下载(包含jar包):http://download.csdn.net/detail/peng_hong_fu/9707572

7 版本信息

Eclipse版本 Neon.1a Release (4.6.1)
Spring 4.3.4
hibernate-validator-5.3.3

源代码

web.xml和SpringMVC文件配置

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springmvc-dataFormat</display-name>
  <!-- 防止中文参数乱码 放在前面 -->  
      <filter>  
          <filter-name>SetCharacterEncoding</filter-name>  
          <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
          <init-param>  
               <param-name>encoding</param-name>  
               <param-value>UTF-8</param-value>  
          </init-param>  
          <init-param>  
               <param-name>forceEncoding</param-name>  
               <param-value>true</param-value>  
               <!-- 强制进行转码 -->  
          </init-param>  
     </filter>  
     <filter-mapping>  
          <filter-name>SetCharacterEncoding</filter-name>  
          <url-pattern>/*</url-pattern>  
     </filter-mapping>  

  <!--配置DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置DispatcherServlet 的一个初始化参数:配置SpringMVC 配置文件的位置和名称 -->
        <!-- 实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件 默认的配置文件路径为 /WEB-INF/{servlet-name}-servlet.xml 
            可以去除下面的<init-param> -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springmvc.xml

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    <context:component-scan base-package="com.jxust.dataformat"></context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven></mvc:annotation-driven>
     <!--配置国际化资源文件-->
     <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n"></property>
        </bean>
</beans>

<mvc:annotation-driven/>的作用

<mvc:annotation-driven></mvc:annotation-driven>
会自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter
和ExceptionHandlerExceptionResolver三个bean

还提供了以下的支持
-支持使用ConversionService 示例对表单参数进行类型转换
-支持使用@NumberFormatannotation@DateTimeFormat 注解完成数据类型的格式化
-支持使用 @Valid 注解对 JavaBean 实例进行JSR 303验证
-支持使用@RequestBody@ResponseBody 注解

实体类

User.java

package com.jxust.dataformat.entity;

import java.util.Date;

import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

public class User {
    @Range(min=100,max=11,message="内容必须在11到100之间")
    private Integer id;
    @NotEmpty
    private String name;
    @Email
    private String email;

    @NumberFormat(pattern="#,###,###,#")
    private Float idCard;
    @Past
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
    //birth 和idCard 的格式声明,输入的格式就必须匹配

    //省略 getter and setter

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + ", idCard=" + idCard + ", birth=" + birth
                + "]";
    }   
}

Controller

DataFormatHandler.java

package com.jxust.dataformat.handler;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jxust.dataformat.entity.User;

@Controller
public class DataFormatHandler {
    /**
     * 跳转到输入页面input.jsp
     * 
     * @param map
     * @return
     */
    @RequestMapping("/input")
    public String dataformat(Map<String, Object> map) {
        /**
         * 对应 form表单的 modelAttribute="user"
         *  因为表单默认是要回显的,这里传入一个空对象
         */
        map.put("user", new User());
        return "input";
    }

    /**
     * input界面提交表单数据的处理方法,在这个方法中进行数据校验
     *  注意: 
     *  需要校验 bean 对象和其绑定结果对象或错误结果(Error)
     * @Valid User user,BindingResult result 两个入参必须成对出现,中间不允许其他入参分隔
     * @param user
     * @param result
     * @return
     */
    @RequestMapping("/testinput")
    public String testinput(@Valid User user, BindingResult result) {
        System.out.println(user.toString());
        /**
         * 类型转换失败时的错误信息输出
         */
        if (result.getErrorCount() > 0) {
            System.out.println("出错了...");
            for (FieldError error : result.getFieldErrors()) {
                System.out.println(error.getField() + ":" + error.getDefaultMessage());
            }
            // 验证出错,则转向特定的页面(这里是之前的输入的页面)
            return "input";
        }
        return "success";
    }
}

SpringMVC 是通过对处理方法签名的规则来保存校验结果的,前一个表单、命令对象的校验结果保存到随后的入参中,这个保存校验结果的入参必须是 BindingResult 或 Errors类型(这里使用的是BindingResult),这两个类都位于 org.springframework.validation

JSP页面

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试表单数据格式化</title>
</head>
<body>
    <a href="input">To Input</a>
</body>
</html>

input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
            <!-- 
            1.数据校验,生日不能是今日之后
                1)如何校验,注解
                ①使用 JSR 303 验证标准
                ② 加入 hibernate validator 验证框架的jar包
                ③ 在SpringMVC 配置文件中添加 <mvc:annotation-drivern/>
                ④ 需要在bean的属性上添加对应的注解
                ⑤ 在目标方法 bean类型的前面添加 @Valid 注解
                2)验证出错转向哪个页面?
                注意:需要校验的 bean 对象和其绑定结果对象或错误对象时成对出现的,他们之间不允许其他的入参
                3)错误消息?如何显示,如何实现国际化
            -->
    <form:form action="testinput" method="post" modelAttribute="user">  
        <form:errors path="*"></form:errors><br><!-- 显示所有错误消息 -->

        id:<form:input path="id"/>
        <form:errors path="id"></form:errors><br>

        name:<form:input path="name"/>
        <form:errors path="name"></form:errors><br>

        email:<form:input path="email"/>
        <form:errors path="email"></form:errors><br>

        idCard:<form:input path="idCard"/>
        <form:errors path="idCard"></form:errors><br>

        birth:<form:input path="birth"/>
        <form:errors path="birth"></form:errors><br>
        <input type="submit" value="提交"/>
    </form:form>  
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>success</h2>
</body>
</html>

国际化文件

i18n_zh_CN.properties

NotEmpty.user.name= \u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A\u554A
Email.user.email= \u90AE\u7BB1\u683C\u5F0F\u4E0D\u5BF9\u54E6
Past.user.birth= \u4F60\u51FA\u751F\u65E5\u671F\u5728\u660E\u5929\uFF1F
typeMismatch.user.birth=Birth\u4E0D\u662F\u4E00\u4E2A\u65E5\u671F

这里写图片描述

笔记.txt

声明了格式,才能正常的使用
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
输出的内容为:
User [id=1, name=ee, email=ee, idCard=12134.0, birth=Sun Sep 09 00:00:00 CDT 1990]
---------------------
声明了birth和idCard的格式,故意输入错误格式,输出的内容为:
User [id=null, name=, email=ee, idCard=null, birth=null]
出错了...
birth:Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birth'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.Past @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '2033-09-'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2033-09-]
idCard:Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Float' for property 'idCard'; nested exception is java.lang.NumberFormatException: For input string: "ee"

---------------------
使用了@Valid,格式校验启动,故意输入错误格式,输出的内容为:

User [id=null, name=, email=ee, idCard=null, birth=Fri Sep 09 00:00:00 CST 2033]
出错了...
email:不是一个合法的电子邮件地址
name:不能为空
birth:需要是一个过去的时间

源代码下载

下载地址:http://download.csdn.net/detail/peng_hong_fu/9707572

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC国际化是建立在Java国际化的基础之上的。它通过提供不同国家/语言环境的消息资源,然后通过Resource Bundle加载指定Locale对应的资源文件,再取得该资源文件中指定key对应的消息。整个过程与Java程序的国际化完全相同,只是Spring MVC框架对Java程序国际化进行了进一步的封装,从而简化了应用程序的国际化。 在Spring MVC中,实现国际化有以下几个步骤: 1. 给系统加载国际化资源文件。 2. 输出国际化消息。可以在视图页面上输出国际化消息,需要使用Spring MVC的标签库;也可以在Controller的处理方法中输出国际化消息,需要使用org.springframework.web.servlet.support.RequestContext的getMessage()方法来完成。 除了默认的实现方式之外,Spring MVC还提供了其他两种国际化方式:SessionLocaleResolver和CookieLocaleResolver。这两种方式的配置稍有不同,包括配置国际化资源文件、配置国际化操作拦截器和配置LocaleResolver。 总结起来,Spring MVC国际化是通过加载不同国家/语言环境的消息资源文件来实现的,可以在视图页面或Controller的处理方法中输出国际化消息。同时,Spring MVC还提供了不同的国际化实现方式供选择。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Spring MVC国际化](https://blog.csdn.net/A_Runner/article/details/83684593)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值