手把手教你--SpringMVC配置全局日期转换器,处理日期转换异常

方法一:实体类中加日期格式化注解

@DateTimeFormat(pattern = "yyyy-MM-dd") //如果为具体的时分秒(pattern="yyyy-MM-dd HH:mm:ss)
private Date currentDay;

这种方法配置过于麻烦,推荐使用第三种

方法二:控制器Action中加入一段数据绑定代码

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
@Controller
@RequestMapping("user")
public class MyController extends MultiActionController{
    @InitBinder
    public void init(WebDataBinder dataBinder){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(dateFormat,true);
        dataBinder.registerCustomEditor(Date.class, dateEditor);
    }
    @RequestMapping("date")
    public ModelAndView date(Date date){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String ss = dateFormat.format(date);
        ModelAndView mv = new ModelAndView();
        mv.addObject("date", ss);
        mv.setViewName("MyJsp");
        return mv;
    }
}

方法三:实现一个全局日期类型转换器并进行配置

public class CustomDateConverter implements Converter<String, Date> {
	@Override
	public Date convert(String source) {
		try {
			//进行日期转换
			System.out.println(source);
			if(source.length()>10){
				return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
			}else{
				return new SimpleDateFormat("yyyy-MM-dd").parse(source);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

通过对日期的长度判断,这样两种类型的日期都能处理了

此时注意在springmvc.xml文件中进行一下配置

<!-- 配置自定义转换器 注意: 一定要将自定义的转换器配置到注解驱动上 -->
	<bean id="conversionService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
                <!-- 指定自定义转换器的全路径名称 -->
				<bean class="cm.cn.convert.DateConverter" />
			</set>
		</property>
	</bean>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值