zoukankan      html  css  js  c++  java
  • 第四节:SpringMVC 数据格式化

    一、数据格式化概述

      (1)对属性对象的输入/输出进行格式化,从其本质上讲依然属于 “类型转换” 的范畴。

      (2)Spring 在格式化模块中定义了一个实现 ConversionService 接口的 FormattingConversionService 实现类,该实现类扩展了 GenericConversionService,因此它既具有类型转换的功能,又具有格式化的功能;

      (3)FormattingConversionService 拥有一个 FormattingConversionServiceFactroyBean 工厂类,后者用于在 Spring 上下文中构造前者;

      FormattingConversionServiceFactroyBean 内部已经注册了 : 

        ① NumberFormatAnnotationFormatterFactroy:支持对数字类型的属性使用,使用 @NumberFormat 注解

        ② JodaDateTimeFormatAnnotationFormatterFactroy:支持对日期类型的属性使用,使用 @DateTimeFormat 注解

      装配了 FormattingConversionServiceFactroyBean 后,就可以在 Spring MVC 入参绑定及模型数据输出时使用注解驱动了。

    < mvc:annotation-driven /> 默认创建的 ConversionService 实例即为 DefaultFormattingConversionService
    

      

    二、SpringMVC 提供的两种格式化

      1、日期格式化

        @DateTimeFormat 注解可对 java.util.Date、java.util.Calendar、java.long.Long时间类型进行标注:

        pattern 属性:类型为字符串。指定解析/格式化字段数据的模式,如:”yyyy-MM-dd hh:mm:ss”;

        iso 属性:类型为 DateTimeFormat.ISO。指定解析/格式化字段数据的ISO模式,包括四种:ISO.NONE(不使用) – 默认、ISO.DATE(yyyy-MM-dd) 、ISO.TIME(hh:mm:ss.SSSZ)、 ISO.DATE_TIME(yyyy-MM-dd hh:mm:ss.SSSZ);

        style 属性:字符串类型。通过样式指定日期时间的格式,由两位字符组成,第一位表示日期的格式,第二位表示时间的格式:S:短日期/时间格式、M:中日期/时间格式、L:长日期/时间格式、F:完整日期/时间格式、-:忽略日期或时间格式;

     

      2、数值格式化

        @NumberFormat 可对类似数字类型的属性进行标注,它拥有两个互斥的属性:

        style:类型为 NumberFormat.Style。用于指定样式类型,包括三种:Style.NUMBER(正常数字类型)、 Style.CURRENCY(货币类型)、 Style.PERCENT(百分数类型)

        pattern:类型为 String,自定义样式,如pattern="#,###";

    三、实验代码

      1、Employee类增加日期对象属性,数字属性

    public class Employee {
    
        private Integer id;
        private String lastName;
        private String email;
        private Integer gender;
    
        private Date birth;
    
        private Double salary;
        private Department department;
    }

      2、页面表单

    <form:form action="${ctx}/emp" modelAttribute="employee" method="POST">
        lastName:<form:input path="lastName" /><br/>
        email:<form:input path="email" /><br/>
        gender:<br><form:radiobutton path="gender" value="1"/><br/><form:radiobutton path="gender" value="0" /><br/>
        birth:<form:input path="birth" /><br/>
        salary:<form:input path="salary" /><br/>
        dept:
    
        <form:select path="department.id" items="${depts}" itemLabel="departmentName" itemValue="id"></form:select>
        <br>
        <input type="submit" value="保存">
    </form:form>

      3、关于格式错误(框架默认支持的格式为斜线方式。1990/09/09)

        在页面上设置格式为:1990-09-09

        报错:

        

      4、解决 400 错误

        在Employee类的日期属性上使用注解增加格式:

    public class Employee {
    
        private Integer id;
        private String lastName;
        private String email;
        private Integer gender;
    
        //可以规定页面提交的日期格式
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date birth;
    
        //假设页面,为了显示方便提交的工资 10000.98,---》 ¥10,000.98
        @NumberFormat(pattern="#,###,###.##")
        private Double salary;
        private Department department;
    }

      5、配置,配置时不能指定conversion-service属性,否则,依然报错400。

           用FormattingConversionServiceFactoryBean替换ConversionServiceFactoryBean后再进行引用。

    <mvc:annotation-driven  conversion-service="conversionService"/>    

      

      ConversionService 是一个接口,下面的 DefaultFormattingConversionService 提供了类型转换器和格式化器。

     

      在SpringMVC 的配置文件中使用 FormattingConversionServiceFactoryBean 配置带有格式化器的 ConversionService:

        <!--以后写自定义类型转换器的时候,就使用 FormattingConversionServiceFactoryBean 来注册,
            既具有类型转换,还有格式化功能
        -->
        <!--带有格式化功能的conversionService-->
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <!--converters 转换器中添加我们自定义的类型转换器-->
            <property name="converters">
                <set>
                    <bean class="com.njf.dataBinder.component.MyStringToEmployeeConverter"></bean>
                </set>
            </property>
        </bean>

      6、如果类型转换错误,如何获取错误信息

    //添加员工
    @RequestMapping(value="/empAdd",method=RequestMethod.POST)
    public String empAdd(Employee employee,BindingResult bindingResult){
        System.out.println("empAdd - employee="+employee);
     
        if(bindingResult.getErrorCount() > 0 ){
            System.out.println("类型转换处错误了");
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(FieldError fieldError : fieldErrors){
                System.out.println(fieldError.getField() + " - " + fieldError.getDefaultMessage());
            }
        }
    
        employeeDao.save(employee);
        return "redirect:/empList";
    }
    
    类型转换出错误了
    birthDay - Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthDay'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Date for value 's'; nested exception is java.lang.IllegalArgumentException: Unable to parse 's'
    salary - Failed to convert property value of type 'java.lang.String' to required type 'double' for property 'salary'; nested exception is java.lang.NumberFormatException: For input string: "ss"
  • 相关阅读:
    如何用微软StreamInsight 处理和分析实时数据
    网站压力测试软件WebBench以及压测Jexus
    Xamarin 开源应用汇集
    微软开源 C++ REST SDK
    Visual Studio 2010/2012 Pro Power Tools
    深入浅出事件流处理NEsper(一)
    将Windows日志转换为Syslog
    事件流处理框架NEsper for .NET
    WCF技术剖析之二十一: WCF基本的异常处理模式[上篇]
    WCF技术剖析之二十一:WCF基本异常处理模式[下篇]
  • 原文地址:https://www.cnblogs.com/niujifei/p/15630929.html
Copyright © 2011-2022 走看看