zoukankan      html  css  js  c++  java
  • SpringMvc几种数据转化方法

    SpringMvc几种数据转化

    1 使用DateTimeFormat

      @DateTimeFormat(pattern = "yyyy-MM-dd")
      private Date birthday;
    

    2 使用InitBinder

    @InitBinder("user")
      public void dateBinder(WebDataBinder dataBinder){
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
     }
    

    但是这个只能在当前Controller生效

    3 使用InitBinder和ControllerAdvice

    @ControllerAdvice
    public class InitBinderAdvice {
      @InitBinder("user")
      public void dateBinder(WebDataBinder dataBinder){
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
     }
    }
    

    但是这个只能对全局Controller生效

    4 实现Converter接口

        public class  StringToDateConverter  implements Converter<String, Date> {
                /*** 用于把 String 类型转成日期类型*/
                @Override
                public Date convert(String source) {
                DateFormat format = null;try {
                    if(StringUtils.isEmpty(source)) {
                        throw new NullPointerException("请输入要转换的日期");
                    }
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = format.parse(source);
                    return date;} catch (Exception e) {
                    throw new RuntimeException("输入日期有误");
    
                }
            }
        }
    
  • 相关阅读:
    记坑
    常用模板
    ACM-东北赛划水记
    jzoj 4178游戏
    JZOI 4163
    jzoj 4146踩气球
    jzoj 5589. 缩点
    jzoj 5588 %%%
    jzoj 5571 ffs
    BJOI 2017 Kakuro
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13730142.html
Copyright © 2011-2022 走看看