我是靠谱客的博主 完美奇异果,最近开发中收集的这篇文章主要介绍SpringMVC 配置请求参数String 转Date 全局转换器,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

问题描述:SpringMVC 请求接收前端发送过来的请求参数提示如下错误信息:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date]

错误含义:RequestParam 无法将String 转换为Date

 RequestParam源码分析:Spring 注解面面通 之 @RequestParam参数绑定源码解析

针对上述问题的解决方法总结:

第一:使用@DateTimeFormat  注解,接收日期格式数据

  • 项目编译为JDK1.7、1.8以及更高版本,会自动支持@DateTimeFormat注解 .
  • 低版本的话需要引入 joda-time jar包

实战:

@ApiOperation(value = "列表:搜索客户信息", notes = "传入 用户姓名、标记")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "用户姓名", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "mark", value = "性别", paramType = "query", dataType = "Integer"), })
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public CommonResult<List<ConnectInfo>> list(@RequestParam(required = false) Long userId, @RequestParam(required = false) Long customerId,
			@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDt,@RequestParam(required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDt) {
		return CommonResult.success(connectInfoService.list(userId, customerId, startDt, endDt));
	}

第二:编写全局日期转换器

实战:

package com.zzg.crm.config;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
 * 定义系统全局转换器
 * 
 * @author zzg
 *
 */
@Configuration
public class ConversionConfig {
	/**
	 * String->Date 日期格式转换器
	 * 
	 * @author zzg
	 *
	 */
	class StringToDateConverter implements Converter<String, Date> {
		private final List<DateFormat> formarts = new ArrayList<>(5);

		public void init() {
			formarts.add(new SimpleDateFormat("yyyy-MM"));
			formarts.add(new SimpleDateFormat("yyyy-MM-dd"));
			formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm"));
			formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
			formarts.add(new SimpleDateFormat("yyyy.MM.dd"));
		}

		@Override
		public Date convert(String value) {
			// TODO Auto-generated method stub
			if (StringUtils.isEmpty(value)) {
				return null;
			}
			// 初始化formarts 数据
			this.init();

			value = value.trim();
			try {
				if (value.matches("^\d{4}-\d{1,2}$")) {
					return formarts.get(0).parse(value);
				} else if (value.matches("^\d{4}-\d{1,2}-\d{1,2}$")) {
					return formarts.get(1).parse(value);
				} else if (value.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}$")) {
					return formarts.get(2).parse(value);
				} else if (value.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}:\d{1,2}$")) {
					return formarts.get(3).parse(value);
				} else if (value.matches("^\d{4}.\d{1,2}.\d{1,2}$")) {
					return formarts.get(4).parse(value);
				}
			} catch (ParseException e) {
				System.out.print(e.getMessage());
			}
			return null;
		}

	}

	@Autowired
	private RequestMappingHandlerAdapter handlerAdapter;

	/**
	 * 增加字符串转日期的功能
	 */

	@PostConstruct
	public void initEditableAvlidation() {

		ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
				.getWebBindingInitializer();
		if (initializer.getConversionService() != null) {
			GenericConversionService genericConversionService = (GenericConversionService) initializer
					.getConversionService();

			genericConversionService.addConverter(new StringToDateConverter());

		}

	}

}
@ApiOperation(value = "分页:搜索客户信息", notes = "传入 名称、标记、第几页、页大小")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "mark", value = "标记", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer", required = true),
			@ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer", required = true), })
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	public CommonResult<CommonPage<ConnectInfoDTO>> page(@RequestParam(required = false) Long userId, @RequestParam(required = false) Long customerId,
			@RequestParam(required = false) Date startDt,@RequestParam(required = false)  Date endDt,
			@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
		long total = connectInfoService.pageTotal(userId, customerId, startDt, endDt);
		return CommonResult.success(
				CommonPage.restPage(connectInfoService.page(userId, customerId, startDt, endDt, pageNum, pageSize), total, pageNum, pageSize));
	}

第三:参数改为String类型,在后端处理String到Date的转换,而不是交给SpringMVC来处理。

最后

以上就是完美奇异果为你收集整理的SpringMVC 配置请求参数String 转Date 全局转换器的全部内容,希望文章能够帮你解决SpringMVC 配置请求参数String 转Date 全局转换器所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部