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:
<!-- 配置器转换 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.springmvc.converter.MyDateConverter" /> </list> </property> </bean> <!-- 加载注解驱动 --> <mvc:annotation-driven conversion-service="conversionService"/>
结果:
注:
// S - source, T - to @FunctionalInterface public interface Converter<S, T> { @Nullable T convert(S var1); }