Springmvc conver实现原理及用法解析

2022-07-28,,,

这种情况:

如果request参数是string类型,但是controller的入参需要date类型, 这种情况就需要converter:

代码:

hiconverter:

请求路径:

http://localhost:8080/mvc/date?mydate=2020-11-22

@controller
public class hicontroller {
  @requestmapping("/date")
  @responsebody
  public string getdate(date mydate) {
    return mydate.tostring();
  }
}

mydateconverter:

public class mydateconverter implements converter<string, date> {
  
  @override
  public date convert(string s) {
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
    date date = null;
    try {
      date = sdf.parse(s);
    } catch (parseexception e) {
      e.printstacktrace();
    }
    return date;
  }
}

springmvc.xml:

public class mydateconverter implements converter<string, date> {
  
  @override
  public date convert(string s) {
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
    date date = null;
    try {
      date = sdf.parse(s);
    } catch (parseexception e) {
      e.printstacktrace();
    }
    return date;
  }
}

结果:

注:

// s - source, t - to
@functionalinterface
public interface converter<s, t> {
  @nullable
  t convert(s var1);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《Springmvc conver实现原理及用法解析.doc》

下载本文的Word格式文档,以方便收藏与打印。