`

spring项目中velocity使用枚举类

阅读更多
在springmvc中配置velocity
<!--相关的文档http://docs.spring.io/spring/docs/4.2.9.RELEASE/spring-framework-reference/htmlsingle/#view-velocity-->
    <!-- 配置velocity引擎 -->
    <bean id="velocityConfigurer"
          class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/vm/"/><!-- 模板存放的路径 -->
        <property name="configLocation" value="/WEB-INF/velocity/velocity.properties"/>
    </bean>
    <!-- 配置视图的显示 -->
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="prefix" value="/"/><!-- 视图文件的前缀,即存放的路径 -->
        <property name="suffix" value=".vm"/><!-- 视图文件的后缀名 -->
        <property name="dateToolAttribute" value="date"/><!--日期函数名称-->
        <property name="numberToolAttribute" value="number"/><!--数字函数名称-->
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="exposeSpringMacroHelpers" value="true"/><!--是否使用spring对宏定义的支持-->
        <property name="exposeRequestAttributes" value="true"/><!--是否开放request属性-->
        <property name="requestContextAttribute" value="rc"/><!--request属性引用名称-->
        <property name="layoutUrl" value="layout/default.vm"/><!--指定layout文件-->
        <property name="toolboxConfigLocation" value="/WEB-INF/velocity/velocityToolbox.xml"/>
    </bean>

配置对应的velocityTool和layout这里忽略
配置相关的文件,主要是加载枚举类加载的路径
import com.google.common.collect.Maps;
import com.my.common.conf.PropertiesLoader;

import java.util.Map;

/**
 * 加载枚举类对应的配置文件
 * Created by Janle on 2017/3/8.
 */
public class EnumSetting {
    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = Maps.newHashMap();
    /**
     * 属性文件加载对象
     */
    private static PropertiesLoader propertiesLoader = new PropertiesLoader(
            "common_key.properties");

    /**
     * 获取配置中对应的值.
     *
     * @param key
     * @return
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if ("".equals(value) || value == null) {
            value = propertiesLoader.getProperty(key);
            map.put(key, value);
        }
        return value;
    }

    /**
     * 获得对应key的value.
     *
     * @return
     */
    public static String getValue(String value) {
        return getConfig(value);
    }
}

属性加载器
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Properties;

/**
 * Created by lijianzhen1 on 2017/3/8.
 */
public class PropertiesLoader {
    private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
    private final Properties properties;

    public PropertiesLoader(String resourcesPath) {
        properties = loadProperties(resourcesPath);
    }

    /**
     * 加载对应的properties文件
     *
     * @param resourcesPath
     * @return
     */
    private Properties loadProperties(String resourcesPath) {
        Properties props = null;
        try {
            props = PropertiesLoaderUtils.loadAllProperties(resourcesPath);
        } catch (IOException e) {
            logger.error("加载[{}].properties文件时候出现异常[{}]", resourcesPath, e);
        }
        return props;
    }

    /**
     * 返回当前加载的properties文件内容.
     *
     * @return
     */
    public Properties getProperties() {
        return properties;
    }

    /**
     * 获得当前文件的property
     *
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return value;
    }

    /**
     * 通过key获得value值
     *
     * @param key
     * @return
     */
    private String getValue(String key) {
        String systemProperty = System.getProperty(key);
        if (systemProperty != null) {
            return systemProperty;
        }
        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return "";
    }

}
//[b]记得配置[/b]
common_key.properties

枚举类
public class StatusEnum{
  待付款(0), 付款成功(1), 退款中(2), 退款成功(3);

    private int code;//私有变量

    //创建私有构造
    private StatusEnum(int code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return String.valueOf(this.code);
    }

    @Override
    public int getIntValue() {
        return this.code;
    }
}

对应的velocity工具类
/**
 * 使用具体说明:
 * 针对velocity前端页面引入枚举类
 * 使用自定义解析工具类标签
 * <p>
 * 迭代使用说明
 * #foreach($enumItem in $enums.getEnumList("InsurPeriodEnum"))
 * $!enumItem
 * #end
 * 获得枚举对象值
 * [$enums.getLabel("InsurPeriodEnum","0")]; 通过重构后的值获得枚举对象的中文名字
 * [$enums.getOrdinal("InsurPeriodEnum","年")] 获得枚举Ordinal值
 * [${myEnum}] 获得重构后的值
 * <p>
 * Created by lijianzhen1 on 2017/3/7.
 */
@DefaultKey("enums")
public class EnumsTool extends SafeConfig {
    private static Logger logger = LoggerFactory.getLogger(EnumsTool.class);
    //默认枚举读取的包
    private static final String ENUM_PACKAGE = "enum_default_package";

    /**
     * 已经扫描到的类缓存起来
     */
    private static final Map<String, Class<?>> ENUM_LOCAL_CACHE = Maps.newConcurrentMap();


    /**
     * 通过枚举类获得所有的枚举值
     *
     * @param enumName 枚举类的名称
     * @return
     */
    public static Enum[] getEnumList(String enumName) {
        Class<?> clazz = getEnumClass(enumName);
        try {
            Method method = null;
            try {
                method = clazz.getMethod("values");
                Object obj = method.invoke(clazz);
                if (obj instanceof Enum[])
                    return (Enum[]) method.invoke(clazz);
                logger.error("不能找到对应的枚举类[{}]", enumName);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过枚举类和枚举值获得对应的ordinal值
     *
     * @param enumName
     * @param value
     * @return
     */
    public static Integer getOrdinal(String enumName, String value) {
        Enum[] enums = getEnumList(enumName);
        for (Enum en : enums) {
            if (StringUtils.equals(en.toString(), value)) {
                return en.ordinal();
            }
        }
        logger.error("对应的枚举类对象[{}]枚举值[{}]不能获得", enumName, value);
        return null;
    }

    /**
     * 通过枚举类和枚举值获得对应的Label值
     *
     * @param enumName
     * @param value
     * @return
     */
    public static String getLabel(String enumName, String value) {
        Enum[] enums = getEnumList(enumName);
        for (Enum en : enums) {
            if (StringUtils.equals(en.toString(), value)) {
                return en.name();
            }
        }
        logger.error("对应的枚举类对象[{}]枚举值[{}]不能获得", enumName, value);
        return null;
    }

    /**
     * 获得要代理的对象的方法
     *
     * @param clazz
     * @param methodName
     * @return
     */
    private static Method getInvokeMethod(Class<?> clazz, String methodName) {
        if (clazz == null) {
            logger.error("没有找到对应的枚举类[{}]", clazz);
            return null;
        }
        Method method = null;
        try {
            method = clazz.getMethod(methodName, String.class);
            if (method != null) {
                return method;
            }
            logger.error("没有获得对应要代理的方法[{}]" + methodName);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return method;
    }

    /**
     * 根据枚举类名称获取具体的枚举类Class
     *
     * @param enumName 枚举类名.
     * @return
     */
    private static Class<?> getEnumClass(String enumName) {
        return getEnumClass(enumName, EnumSetting.getValue(ENUM_PACKAGE));
    }

    /**
     * 根据枚举类名称获取具体的枚举类Class,和自定义package
     *
     * @param enumName
     * @param enumPackageKey
     * @return
     */
    private static Class<?> getEnumClass(String enumName, String enumPackageKey) {
        if (StringUtils.isEmpty(enumName)) {
            return null;
        }
        //如果缓存中有值从缓存中获得
        if (ENUM_LOCAL_CACHE.containsKey(enumName)) {
            return ENUM_LOCAL_CACHE.get(enumName);
        }
        if (null == enumPackageKey) {
            logger.error("没有找到对应的枚举类的包");
            return null;
        }
        String classPath = enumPackageKey + "." + enumName;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(classPath);
            if (clazz != null) {
                ENUM_LOCAL_CACHE.put(enumName, clazz);
                return clazz;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            logger.error("没有找到对应的枚举类[{}],对应的错误信息[{}]", classPath, e);
        }
        return null;
    }


}


需要修改页面的处理
**
 * 前端处理时候使用
 * Created by lijianzhen1 on 2017/3/17.
 */
public class EnumTypeEditor<E extends Enum<E>> extends PropertyEditorSupport {
    private final E[] anEnum;

    public EnumTypeEditor(E[] anEnum) {
        this.anEnum = anEnum;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        for (E en : anEnum) {
            if (StringUtils.equals(en.toString(), text)){
                this.setValue(en);
                break;
            }
        }
    }
    public String getAsText() {
        String value = (String)this.getValue();
        return value != null?value:"";
    }
}

测试页面
 #foreach($enumItem in $enums.getEnumList("InsurPeriodEnum"))
        <br/>
        $!enumItem
        ==
    #end
    #foreach($enumItem in $enums.getEnumList("InsurPeriodEnum"))
        <br/>
        $!enumItem.name()
        ==
    #end
    <br/>
    测试我velocity tool中返回的枚举类:[$enums.getLabel("InsurPeriodEnum","0")];[$enums.getOrdinal("InsurPeriodEnum","年")][${myEnum}]<br>


页面好了我们要存入数据库,我使用的是mybats操作的数据库,

/**
 * 主要是为了在数据库操作时候使用
 * Created by lijianzhen1 on 2017/3/16.
 */
public interface IntEnum<E extends Enum<E>> {
    int getIntValue();
}

public class EnumTypeHandler<E extends Enum<E> & IntEnum<E>> extends BaseTypeHandler<IntEnum> {
    private Class<IntEnum> clazz;

    public EnumTypeHandler(Class<IntEnum> enumType) {
        if (enumType == null)
            throw new IllegalArgumentException("enumType argument cannot be null");
        this.clazz = enumType;
    }

    /**
     * 将数据库映射的值转化为对应的枚举值
     *
     * @param code
     * @return
     */
    private IntEnum convert(int code) {
        IntEnum[] enumConstants = clazz.getEnumConstants();
        for (IntEnum im : enumConstants) {
            if (im.getIntValue() == code)
                return im;
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, IntEnum intEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, intEnum.getIntValue());
    }

    @Override
    public IntEnum getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return convert(resultSet.getInt(columnName));
    }

    @Override
    public IntEnum getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return convert(resultSet.getInt(columnIndex));
    }

    @Override
    public IntEnum getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return convert(callableStatement.getInt(columnIndex));
    }
}

在数据库的xml中获得添加
 <result column="service_status" jdbcType="TINYINT" property="serviceStatus"
                typeHandler="com.XX.mybatis.handlers.EnumTypeHandler"/>

service_status=#{serviceStatus,jdbcType=TINYINT,typeHandler=com.XX.mybatis.handlers.EnumTypeHandler}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics