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("输入日期有误");
    
                }
            }
        }
    
  • 相关阅读:
    webrtc公开课
    webrtc第二篇 聊天室
    webrtc第一篇
    lua53
    setValuesForKeysWithDictionary forUndefinedKey
    xcode 插件
    2016年1月7日 隐藏NavigationBar时的一个坑
    jdbc
    brew gradle
    Openwrt TF Card Auto Mount&Check (4)
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13730142.html
Copyright © 2011-2022 走看看