SpringMVC绑定日期类型参数

  • Controller层代码
@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;
    }
}
  • 页面访问HTTP报400错误


    HTTP 400
  • 控制台输出警告
[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没有找到对应的类型转换器。

  • 自定义时间类型转换器
    实现Spring core包下的Converter接口,实现自定义转化器
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>
  • 验证时间类型拦截器生效
    页面正常能够访问,没有错误信息


    HTTP 请求

    控制台日志正常输出,无异常信息

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容