亲宝软件园·资讯

展开

Springmvc conver实现原理及用法解析

圣金巫灵 人气:0

这种情况:

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

加载全部内容

相关教程
猜你喜欢
用户评论