SpringMVC绑定日期类型参数

2021-08-16  本文已影响0人  Scallion
@Controller
@RequestMapping("/demo")
public class DemoController {
    @RequestMapping("/handle02")
    public ModelAndView handle02(Date birthday) {
        //服务器时间
        Date date = new Date();
        //返回服务器时间到前端页面
        //封装了数据和页面信息的modelAndView
        ModelAndView modelAndView = new ModelAndView();
        //addObject 其实是向请求域中request.setAttribute("date",date)
        modelAndView.addObject("date", date);
        //视图信息(封装跳转的页面信息)
        modelAndView.setViewName("success");
        System.out.println("date: " + date);
        System.out.println("birthday" + birthday);
        return modelAndView;
    }
}
[INFO] Initializing Servlet 'springmvc'
[INFO] Completed initialization in 677 ms
[WARNING] Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-08-16'; nested exception is java.lang.IllegalArgumentException]

从控制台的日志上可以看出,SpringMVC没有找到对应的类型转换器。

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Version 1.0
 */
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        // 完成字符串向日期的转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date parse = simpleDateFormat.parse(source);
            return parse;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

修改Spring MVC配置文件,加载自定义时间类型转换器

        <!--
        自动注册最合适的处理器映射器,处理器适配器(调用handler方法)
        -->
        <mvc:annotation-driven conversion-service="conversionServiceBean"/>
        <!--注册自定义类型转换器-->
        <bean id="conversionServiceBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
                <property name="converters">
                        <set>
                                <bean class="com.erxiao.edu.converter.DateConverter"></bean>
                        </set>
                </property>
        </bean>
INFO] Initializing Servlet 'springmvc'
[INFO] Completed initialization in 648 ms
date: Mon Aug 16 17:49:01 CST 2021
birthdayMon Aug 16 00:00:00 CST 2021
上一篇 下一篇

猜你喜欢

热点阅读