当前位置: 移动技术网 > IT编程>开发语言>Java > spring mvc4的日期/数字格式化、枚举转换示例

spring mvc4的日期/数字格式化、枚举转换示例

2019年07月22日  | 移动技术网IT编程  | 我要评论
日期、数字格式化显示,是web开发中的常见需求,spring mvc采用xxxformatter来处理,先看一个最基本的单元测试: package com.c

日期、数字格式化显示,是web开发中的常见需求,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() {
    
    //设置上下语言的语言环境
    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全都实现了接口org.springframework.format.formatter<t>,web开发中使用起来很方便:

一、先在servlet-context.xml中参考下面的内容,修改配置:

 <mvc:annotation-driven  conversion-service="conversionservice" />
 
  <bean id="conversionservice"
     class="org.springframework.format.support.formattingconversionservicefactorybean">    
  </bean>

二、dto类中,在需要设置格式化的字段上,打上相关的注解

@numberformat(style=style.currency)
  //@numberformat(pattern="#,###.00")
  double amount;  

  @datetimeformat(pattern = "yyyy-mm-dd hh:mm:ss")
  date createtime;

三、jsp页面上,使用<spring:eval />标签绑定

<spring:eval expression="c.amount" />         
<spring:eval expression="c.createtime" />

四、枚举问题

表单提交的html页面中,经常会遇到一些诸如:性别(男、女) 的radiobutton组,背后通常对应enum,表单提交的是string,默认情况下并不能自动映射成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"(当然,这只是个人喜好,仅供参考)

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的转换

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 页面显示时,如何转义

就刚才的示例而言,性别“男”,对应sex.male,自定义值是"1",自定义描述是“男”,默认情况下${model.sex}显示成male,如果想显示“自定义值”或“自定义描述”,不考虑国际化的话,直接调用value或description属性即可,参考下面的内容:

${c.sex}/${c.sex.description}/${c.sex.value}

最终显示成: male/男/1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网