Springmvc conver实现原理及用法解析
这种情况:
如果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实现原理及用法解析 的全部内容, 来源链接: utcz.com/z/338994.html