Spring mvc参数类型转换

时间:2023-03-09 15:59:40
Spring mvc参数类型转换

1,需求

有时候我们接收到的参数为String类型的,但是我们需要将它们转化为其他类型的如:date类型,枚举类型等等,spring mvc为我们提供了这样的功能。

2,配置文件

在springmvc.xml配置文件中添加如下代码:

<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
		<list>
			<bean class="com.cmc.core.converters.StringToESportConverter" />
		</list>
	</property>
</bean>

别忘记上面那句,是注册转换器的。

3,添加StringToESportConverter类

package com.cmc.core.converters;

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

import com.gionee.xo.healthy.enums.ESport;

/**
 * 配置spring mvc自动接收ESport
 *
 * @author chenmc
 */
public class StringToESportConverter implements Converter<String, ESport> {

	@Override
	public ESport convert(String source) {
		String value = source.trim();
		if ("".equals(value)) {
			return null;
		}
		return ESport.get(Integer.parseInt(source));
	}

}

4,添加ESport枚举类

package com.cmc.xo.healthy.enums;

import java.util.Locale;

import com.cmc.core.base.utils.I18N;

/**
 * 运动枚举
 *
 * @author chenmc
 * @date 2017年4月18日 下午8:32:33
 */
public enum ESport {

	run("0"),//跑步
	cycling("1");//骑行

	private final String value;

	private ESport(String v) {
		this.value = v;
	}

	public String toString() {
		return this.value;
	}

	public static ESport get(int v) {
		String str = String.valueOf(v);
		return get(str);
	}

	public static ESport get(String value) {
		for (ESport e : values()) {
			if (e.toString().equals(value)) {
				return e;
			}
		}
		return null;
	}

	public String getName() {
		return I18N.getEnumName(this, Locale.CHINA);
	}
}

转换主要用到了get(String value)这个方法

5,controller中代码

@ApiOperation(value="获取某用户单种运动的总信息", notes="返回某用户的运动总次数和总耗时总消耗")
@RequestMapping( value = {"/sports/{useruid:.{32}}/{type:\\d{1}}/sum"}, method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public String get_count(HttpServletRequest request, @PathVariable String useruid, @PathVariable ESport type) {
	return BaseResultHP.jsonResultSuccess(so.getSum(useruid, type));
}

url中传入的type为String类型的数字,而我接收参数@PathVariable ESport type