zoukankan      html  css  js  c++  java
  • springmvc之数据的格式化

    当提交时,数据的格式化和转换是一起发生的,我们在前端输入的时间数据需要转换成springmvc里面的对象的类型的格式,不然会报:

     首先在sprinbmvc配置文件里面添加:

        <mvc:annotation-driven></mvc:annotation-driven>

    然后可以在相应属性上指定格式:

        @DateTimeFormat(pattern="yyyy-mm-dd")
        private Date birth;

    此时再提交,就不会报4o4了,在控制台可以看到:

    数据格式化:

    • 对属性对象的输入/输出进行格式化,从其本质上来说就是类型转换。
    • spring在格式化模块中定义了一个实现ConversionService接口的实现类,该实现类扩展了GenericConversionService,因此它既有类型转换的功能,又有格式化的功能。
    • FormattingConversionService拥有一个FormattingConversionServiceFactoryBean工厂类,后者用于在spring上下文中构造前者。
    • FormattingConversionServiceFactoryBean内部已经注册了:NumberFormatAnnotationFormatterFactory用于对数字类型属性使用NumberFormat注解,JodaDateTimeFormatAnnotationFormatterFactory用于对时间属性使用@DateTimeFormat注解。
    • 装配了FormattingConversionServiceFactoryBean后,就可以在springmvc入参绑定及模型数据输出时使用注解驱动了。<mvc:annotation-driver>默认创建的ConversionService实例即为FormattingConversionServiceFactoryBean。
    • @DateTimeFromat可对java.util.Date、java.util.Calendar和java.long.Long时间类型进行标注。

    如果格式化失败,我们可以这么写:

        @RequestMapping(value="/emp",method=RequestMethod.POST)
        public String save(Employee employee, BindingResult result) {
            System.out.println("save-->"+employee);
            if (result.getErrorCount()>0) {
                System.out.println("出错了");
                for(FieldError error:result.getFieldErrors()) {
                    System.out.println(error.getField()+":"+error.getDefaultMessage());
                }
            }
            employeeDao.save(employee);
            return "redirect:/emps";
        }

    可以利用BindingResult来接受格式化错误消息,进行下一步处理。 

  • 相关阅读:
    windows RabbitMQ Server 环境配置中的一些坑
    Redis自定义fastJson Serializer
    如何使用Feign构造多参数的请求
    跨域访问支持(Spring Boot、Nginx、浏览器)
    chrome浏览器的跨域设置
    Jenkins手把手图文教程[基于Jenkins 2.164.1]
    Spring Boot 2发送邮件手把手图文教程
    poi读取Excel模板并修改模板内容与动态的增加行
    Lock类-ReentrantLock的使用
    类ThreadLocal的使用与源码分析
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12186445.html
Copyright © 2011-2022 走看看