欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springmvc conver实现原理及用法解析

程序员文章站 2024-01-13 21:44:10
这种情况:如果request参数是string类型,但是controller的入参需要date类型, 这种情况就需要converter:代码:hiconverter:请求路径:http://local...

这种情况:

如果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;
  }
}

结果:

Springmvc conver实现原理及用法解析

注:

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

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

相关标签: Spring mvc conver