为了账号安全,请及时绑定邮箱和手机立即绑定

Spring mvc参数类型转换

标签:
Spring

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")@ResponseBodypublic String get_count(HttpServletRequest request, @PathVariable String useruid, @PathVariable ESport type) {	return BaseResultHP.jsonResultSuccess(so.getSum(useruid, type));
}

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


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Python工程师
手记
粉丝
5147
获赞与收藏
2660

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消