Controller层接收Date类型参数进行统一转换

需求

当后台接收参数类型为Date时,前端传过来的参数类型为String:“2020-05-08 17:08:10”,这样就会出现参数类型不匹配的问题,这种情况下我们就要对接收Date类型参数进行统一处理。Java中提供了PropertyEditorSupport来进行类型转换,我们只需要继承这个类,并且重写它主要的方法就行了。

PropertyEditorSupport

PropertyEditorSupport中通过setAsText(String text)方法来实现转换逻辑,然后调用setValue(Object value)方法将转换后的数据进行保存。

    public void setAsText(String text) throws java.lang.IllegalArgumentException {
        if (value instanceof String) {
            setValue(text);
            return;
        }
        throw new java.lang.IllegalArgumentException(text);
    }

自定义DateEditor
继承PropertyEditorSupport并且重写setAsText(String text) 和getAsText()方法。

/**
 * Editor - 日期
 */
public class DateEditor extends PropertyEditorSupport {

	/**
	 * 默认的日期格式
	 */
	private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 能够进行转换的日期格式
	 */
	public static final String[] DATE_PATTERNS = new String[] { "yyyy", "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyy-MM-dd", "yyyyMMdd", "yyyy/MM/dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy/MM/dd HH:mm:ss" };


	/**
	 * 是否将空转换为null
	 */
	private boolean emptyAsNull;

	/**
	 * 日期格式
	 */
	private String dateFormat = DEFAULT_DATE_FORMAT;

	public DateEditor(boolean emptyAsNull) {
		this.emptyAsNull = emptyAsNull;
	}

	public DateEditor(boolean emptyAsNull, String dateFormat) {
		this.emptyAsNull = emptyAsNull;
		this.dateFormat = dateFormat;
	}

	/**
	 * 获取日期
	 */
	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		return value != null ? DateFormatUtils.format(value, dateFormat) : StringUtils.EMPTY;
	}

	/**
	 * 设置日期
	 */
	@Override
	public void setAsText(String text) {
		if (text != null) {
			String value = text.trim();
			if (emptyAsNull && StringUtils.isEmpty(text)) {
				setValue(null);
			} else {
				try {
					setValue(DateUtils.parseDate(value, DATE_PATTERNS));
				} catch (ParseException e) {
					setValue(null);
				}
			}
		} else {
			setValue(null);
		}
	}

}

通过@InitBinder进行数据绑定

/**
 * Controller增强
 */
@ControllerAdvice("xx.xx.controller")
public class BaseControllerAdvice {

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateEditor(true));
	}
	
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值