當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring mvc参数类型转换
生活随笔
收集整理的這篇文章主要介紹了
Spring mvc参数类型转换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1,需求
有時候我們接收到的參數(shù)為String類型的,但是我們需要將它們轉(zhuǎn)化為其他類型的如: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> 別忘記上面那句,是注冊轉(zhuǎn)換器的。
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> {@Overridepublic 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;/*** 運(yùn)動枚舉* * @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);} }
轉(zhuǎn)換主要用到了get(String value)這個方法
5,controller中代碼
@ApiOperation(value="獲取某用戶單種運(yùn)動的總信息", notes="返回某用戶的運(yùn)動總次數(shù)和總耗時總消耗") @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類型的數(shù)字,而我接收參數(shù)@PathVariable ESport type
總結(jié)
以上是生活随笔為你收集整理的Spring mvc参数类型转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Swagger2 添加HTTP head
- 下一篇: Java IO流读取文件