亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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工程師
手記
粉絲
5143
獲贊與收藏
2663

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消