SpringMVC从前端接收一个日期类型(Date)

编程入门 行业动态 更新时间:2024-10-07 21:45:34

SpringMVC从前端接收一个<a href=https://www.elefans.com/category/jswz/34/1771397.html style=日期类型(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)

本文发布于:2024-03-23 20:44:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1742623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   类型   SpringMVC   Date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!