springmvc接收Date类型的参数

1、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 [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value '1571846399000'; nested exception is java.lang.IllegalArgumentException

接口接收参数类型为Date,但是传进来的参数却不是Date类型,springmvc不支持Date传参,需要自己写转换器,或者使用@InitBinder

第一步、编写InitBinderControllerAdvice

@ControllerAdvice
public class InitBinderControllerAdvice {

   @InitBinder
   public void initBinder(WebDataBinder binder) {
      binder.registerCustomEditor(Date.class, new MyCustomDateEditor());
   }

}

第二步、编写MyCustomDateEditor

package com.casstime.ec.cloud.aftersale.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @Author: jie.yin
 * @Date: 2019/10/26 9:48
 */
@Slf4j
@Configuration
public class MyCustomDateEditor extends PropertyEditorSupport {

    private static final Pattern HH_MM_SS_SSS = Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{0,3}");

    private static final Pattern YYYY_MM_DD = Pattern.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}.*");

    private static final Pattern YYYY_M_D = Pattern.compile("^[0-9]{4}-[0-9]{1}-[0-9]+.*||^[0-9]{4}-[0-9]+-[0-9]{1}.*");

    private static final Pattern YY_MM_DD = Pattern.compile("^[0-9]{2}-[0-9]{2}-[0-9]{2}.*");

    private static final Pattern YY_M_D = Pattern.compile("^[0-9]{2}-[0-9]{1}-[0-9]+.*||^[0-9]{2}-[0-9]+-[0-9]{1}.*");

    private static final Pattern HH_MM_SS = Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}");

    private static final Pattern HH = Pattern.compile(".*[ ][0-9]{2}");

    private static final Pattern HH_MM = Pattern.compile(".*[ ][0-9]{2}:[0-9]{2}");

    /**
     * Parse the Date from the given text, using the specified DateFormat.
     */
    @Override

    public void setAsText(String text) throws IllegalArgumentException {

        if (!StringUtils.hasText(text)) {
            setValue(null);
        } else {
            try {
                setValue(dateAdapter(text));
            } catch (Exception ex) {
                ex.printStackTrace();
                log.error("出错日志:" + ex.getMessage());
            }
        }
    }


    /**
     * Format the Date as String, using the specified DateFormat.
     */

    @Override

    public String getAsText() {

        Date value = (Date) getValue();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return (value != null ? dateFormat.format(value) : "");

    }


    /**
     * 字符串转日期适配方法
     *
     * @param dateStr 日期字符串
     * @throws
     */

    public static Date dateAdapter(String dateStr) throws Exception {

        Date date = null;
        if (!(null == dateStr || "".equals(dateStr))) {
            //判断是不是日期字符串,如Wed May 28 08:00:00 CST 2014
            if (dateStr.contains("CST")) {
                date = new Date(dateStr);
            } else {
                dateStr = dateStr.replace("年", "-").replace("月", "-").replace("日", "").replaceAll("/", "-").replaceAll("\\.", "-").trim();
                String fm = "";
                //确定日期格式
                if (YYYY_MM_DD.matcher(dateStr).matches()) {
                    fm = "yyyy-MM-dd";
                } else if (YYYY_M_D.matcher(dateStr).matches()) {
                    fm = "yyyy-M-d";
                } else if (YY_MM_DD.matcher(dateStr).matches()) {
                    fm = "yy-MM-dd";
                } else if (YY_M_D.matcher(dateStr).matches()) {
                    fm = "yy-M-d";
                }

                //确定时间格式
                if (HH.matcher(dateStr).matches()) {
                    fm += "HH";
                } else if (HH_MM.matcher(dateStr).matches()) {
                    fm += "HH:mm";
                } else if (HH_MM_SS.matcher(dateStr).matches()) {
                    fm += "HH:mm:ss";
                } else if (HH_MM_SS_SSS.matcher(dateStr).matches()) {
                    fm += "HH:mm:ss:sss";
                }
                if (!"".equals(fm)) {
                    try {
                        date = new SimpleDateFormat(fm).parse(dateStr);
                    } catch (ParseException e) {
                        throw new Exception("参数字符串" + dateStr + "无法被转换为日期格式!");
                    }
                }
            }
            if (date == null) {
                long l = Long.parseLong(dateStr);
                date = new Date(l);
            }
        }
        return date;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC接收日期格式的方法有几种。其中一种是使用Converter接口来自定义日期类型转换。通过实现Converter接口,可以将一个String类型的日期参数转换为Date类型。 另外一种方式是使用@DateTimeFormat注解来指定日期的格式。在Controller的方法参数上使用@DateTimeFormat注解,并指定日期的格式,Spring MVC会自动将String类型的日期参数转换为指定格式的Date类型。 如果需要同时接收多种格式的日期参数,可以在方法参数上使用多个@DateTimeFormat注解,每个注解都指定一个日期格式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springMvc接受日期类型参数处理](https://blog.csdn.net/z69183787/article/details/52780611)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringMVC之日期类型参数传递](https://blog.csdn.net/qq_61313896/article/details/128862433)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值