spring mvc4的日期/數(shù)字格式化、枚舉轉(zhuǎn)換示例
日期、數(shù)字格式化顯示,是web開發(fā)中的常見需求,spring mvc采用XXXFormatter來處理,先看一個最基本的單元測試:
package com.cnblogs.yjmyzz.test; import java.math.BigDecimal; import java.util.Date; import java.util.Locale; import org.junit.Test; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.format.datetime.DateFormatter; import org.springframework.format.number.CurrencyFormatter; import org.springframework.format.support.DefaultFormattingConversionService; public class FormatterTest { @Test public void testFormatter() { //設(shè)置上下語言的語言環(huán)境 LocaleContextHolder.setLocale(Locale.US); //--------測試日期格式化---------- Date d = new Date(); DateFormatter dateFormatter = new DateFormatter(); //按中文格式輸出日期 System.out.println(dateFormatter.print(d, Locale.CHINESE));//2014-10-30 DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); //添加前面的DateFormatter conversionService.addFormatter(dateFormatter); System.out.println(conversionService.convert(d, String.class));//Oct 30, 2014 dateFormatter.setPattern("yyyy年MM月dd日"); System.out.println(conversionService.convert(d, String.class));//2014年10月30日 // --------測試貨幣格式化------------- CurrencyFormatter currencyFormatter = new CurrencyFormatter(); BigDecimal money = new BigDecimal(1234567.890); System.out.println(currencyFormatter.print(money, Locale.CHINA));//¥1,234,567.89 conversionService.addFormatter(currencyFormatter); System.out.println(conversionService.convert(money, String.class));//$1,234,567.89 } }
除了DateFormatter、CurrencyFormatter,常用還有的以下Formatter:
這些Formatter全都實現(xiàn)了接口org.springframework.format.Formatter<T>,web開發(fā)中使用起來很方便:
一、先在servlet-context.xml中參考下面的內(nèi)容,修改配置:
<mvc:annotation-driven conversion-service="conversionService" /> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> </bean>
二、dto類中,在需要設(shè)置格式化的字段上,打上相關(guān)的注解
@NumberFormat(style=Style.CURRENCY) //@NumberFormat(pattern="#,###.00") double amount; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date createTime;
三、jsp頁面上,使用<spring:eval />標(biāo)簽綁定
<spring:eval expression="c.amount" /> <spring:eval expression="c.createTime" />
四、枚舉問題
表單提交的html頁面中,經(jīng)常會遇到一些諸如:性別(男、女) 的RadioButton組,背后通常對應(yīng)Enum,表單提交的是String,默認(rèn)情況下并不能自動映射成Model中的Enum成員,需要額外的Converter處理
4.1 先定義一個基本的枚舉
package com.cnblogs.yjmyzz.enums; public enum SEX { /** * 男 */ Male("1", "男"), /** * 女 */ Female("-1", "女"), /** * 保密 */ Unknown("0", "保密"); private final String value; private final String description; private SEX(String v, String desc) { this.value = v; this.description = desc; } public String getValue() { return value; } public String getDescription() { return description; } public static SEX get(String strValue) { for (SEX e : values()) { if (e.getValue().equals(strValue)) { return e; } } return null; } @Override public String toString() { return this.value; } }
保存到db中時,性別字段我們希望"男"存成"1","女"存成"-1","保密"存成"0"(當(dāng)然,這只是個人喜好,僅供參考)
4.2 定義SEX枚舉的Converter
package com.cnblogs.yjmyzz.convertor; import org.springframework.core.convert.converter.Converter; import com.cnblogs.yjmyzz.enums.SEX; public class String2SexConvertor implements Converter<String, SEX> { @Override public SEX convert(String enumValueStr) { String value = enumValueStr.trim(); if (value.isEmpty()) { return null; } return SEX.get(enumValueStr); } }
代碼很短,不多解釋,Convert方法,完成類似 "1" -> SEX.Male的轉(zhuǎn)換
4.3 配置修改
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.cnblogs.yjmyzz.convertor.String2SexConvertor" /> </set> </property> </bean>
只需要在剛才的conversionService加上自己的Converter就行
4.4 form頁面上的綁定示例:
<form:radiobuttons path="sex" items="${sexMap}" delimiter=" " />
sexMap是ModelAndView中的一個屬性,參考代碼如下:
package com.cnblogs.yjmyzz.repository; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import com.cnblogs.yjmyzz.enums.SEX; public class EnumRepository { static Map<String, String> sexMap = null; public static Map<String, String> getSexMap() { if (sexMap == null) { sexMap = new HashMap<String, String>(); EnumSet<SEX> sexs = EnumSet.allOf(SEX.class); for (SEX sex : sexs) { sexMap.put(sex.getValue(), sex.getDescription()); } } return sexMap; } }
Action中,這樣寫:
@RequestMapping(value = "edit/{id}") public ModelAndView edit(@PathVariable int id, HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); Order order = orderService.get(id + ""); model.addObject("sexMap", EnumRepository.getSexMap());//枚舉列表,便于頁面綁定 model.addObject("data", order); model.setViewName("orders/edit"); return model; }
4.5 頁面顯示時,如何轉(zhuǎn)義
就剛才的示例而言,性別“男”,對應(yīng)SEX.Male,自定義值是"1",自定義描述是“男”,默認(rèn)情況下${model.sex}顯示成Male,如果想顯示“自定義值”或“自定義描述”,不考慮國際化的話,直接調(diào)用value或description屬性即可,參考下面的內(nèi)容:
${c.sex}/${c.sex.description}/${c.sex.value}
最終顯示成: Male/男/1
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- springboot DTO字符字段與日期字段的轉(zhuǎn)換問題
- springboot日期轉(zhuǎn)換器實現(xiàn)實例解析
- 解決springmvc關(guān)于前臺日期作為實體類對象參數(shù)類型轉(zhuǎn)換錯誤的問題
- Spring MVC自定義日期類型轉(zhuǎn)換器實例詳解
- SpringMVC中日期格式的轉(zhuǎn)換
- SpringMVC對日期類型的轉(zhuǎn)換示例
- 詳解spring mvc4使用及json 日期轉(zhuǎn)換解決方案
- SpringMVC用JsonSerialize日期轉(zhuǎn)換方法
- Springboot日期轉(zhuǎn)換器實現(xiàn)代碼及示例
相關(guān)文章
SpringBoot項目nohup啟動運(yùn)行日志過大的解決方案
這篇文章主要介紹了SpringBoot項目nohup啟動運(yùn)行日志過大的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05JDBC實現(xiàn)Mysql自動重連機(jī)制的方法詳解
最近在工作中發(fā)現(xiàn)了一個問題,通過查找相關(guān)的資料終于解決了,下面這篇文章主要給大家介紹了關(guān)于JDBC實現(xiàn)Mysql自動重連機(jī)制的相關(guān)資料,文中給出多種解決的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07Java設(shè)計模式中的代理設(shè)計模式詳細(xì)解析
這篇文章主要介紹了Java設(shè)計模式中的代理設(shè)計模式詳細(xì)解析,代理模式,重要的在于代理二字,何為代理,我們可以聯(lián)想到生活中的例子,比如秘書、中介這類職業(yè),我們可以委托中介去幫我們完成某些事情,而我們自己只需要關(guān)注我們必須完成的事情,需要的朋友可以參考下2023-12-12Java aop面向切面編程(aspectJweaver)案例詳解
這篇文章主要介紹了Java aop面向切面編程(aspectJweaver)案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08SpringBoot請求參數(shù)加密、響應(yīng)參數(shù)解密的實現(xiàn)
在項目開發(fā)工程中,有的項目可能對參數(shù)安全要求比較高,在整個http數(shù)據(jù)傳輸?shù)倪^程中都需要對請求參數(shù)、響應(yīng)參數(shù)進(jìn)行加密,本文主要介紹了SpringBoot請求參數(shù)加密、響應(yīng)參數(shù)解密的實現(xiàn),感興趣的可以了解一下2024-01-01Java中隊列Queue和Deque的區(qū)別與代碼實例
學(xué)過數(shù)據(jù)結(jié)構(gòu)的,一定對隊列不陌生,java也實現(xiàn)了隊列,下面這篇文章主要給大家介紹了關(guān)于Java中隊列Queue和Deque區(qū)別的相關(guān)資料,需要的朋友可以參考下2021-08-08