日期类型(Date)"/>
SpringMVC从前端接收一个日期类型(Date)
<a href="account/deleteAccount?date=2018-01-01">根据日期删除账户</a>
(1)
@RequestMapping("/deleteAccount")
public String deleteAccount(String date) {
System.out.println("删除了账户。。。。"+date);
return "success";
}(2)
@RequestMapping("/deleteAccount")
public String deleteAccount(Date date) {
System.out.println("删除了账户。。。。"+date);
return "success";
}
代码一接收的是一个字符类型,所以可以正常执行的,但是代码二接收的是一个日期类型,就会报错,这是因为Java不能自动转换为日期类型
所以为了解决这个问题,我们需要用到自定义类型转换器
自定义类型转换器:
第一步:定义一个类,实现 Converter 接口,该接口有两个泛型。
public interface Converter<S, T> {//S:表示接受的类型,T:表示目标类型
/**
* 实现类型转换的方法
*/
@Nullable
T convert(S source);
}
/**
* 自定义类型转换器
* @author 黑马程序员
* @Company
* @Version 1.0
*/
public class StringToDateConverter implements Converter<String, Date> {
/**
* 用于把 String 类型转成日期类型
*/
@Override
public Date convert(String source) {
DateFormat format = null;
try {
if(StringUtils.isEmpty(source)) {
throw new NullPointerException("请输入要转换的日期");
}
format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(source);
return date;
} catch (Exception e) {
throw new RuntimeException("输入日期有误");
}
}
}
第二步:在 spring 配置文件中配置类型转换器。
spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去。
<!-- 配置类型转换器工厂 -->
<bean id="converterService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 给工厂注入一个新的类型转换器 --><property name="converters"><array><!-- 配置自定义类型转换器 --><bean class="com.itheima.web.converter.StringToDateConverter"></bean></array></property>
</bean>
**第三步:在 annotation-driven 标签中引用配置的类型转换服务 **
<!-- 引用自定义类型转换器 -->
<mvc:annotation-driven
conversion-service="converterService"></mvc:annotation-driven>
来自黑马程序员
更多推荐
SpringMVC从前端接收一个日期类型(Date)
发布评论