关于Struts2中使用枚举和静态调用
struts2中经常用到枚举,代码如下:
/** * 用户级别 * @author LiYongqaing */public enum UserLevel {/**超级管理员*/SUPER_ADMIN{@Overridepublic String getValue() {return "超级管理员";}},/**局长*/JUZHANG{@Overridepublic String getValue() {return "局长";}},/**主任*/ZHUREN{@Overridepublic String getValue() {return "主任";}},/**系统管理员*/ADMIN{@Overridepublic String getValue() {return "系统管理员";}},/**科长*/KEZHANG{@Overridepublic String getValue() {return "科长";}},/**科员*/KEYUAN{@Overridepublic String getValue() {return "科员";}};public abstract String getValue();public static List<String> getValues(){List<String> list = new ArrayList<String>();for (UserLevel level : UserLevel.values()) {list.add(level.getValue());}return list;}public static List<String> getValues2(){List<String> list = new ArrayList<String>();for (UserLevel level : UserLevel.values()) {if(!"超级管理员".equals(level.getValue())){list.add(level.getValue());}}return list;}}
?还需要定义类型转换器:
@SuppressWarnings("unchecked")public class UserLevelConverter extends StrutsTypeConverter {@Overridepublic Object convertFromString(Map arg0, String[] arg1, Class arg2) {UserLevel[] levels = UserLevel.values();for (UserLevel level : levels) {if(level.getValue().equals(arg1[0])){return level;}}return null;}@Overridepublic String convertToString(Map arg0, Object arg1) {UserLevel level = (UserLevel) arg1;return level.getValue();}}
?
?
struts2标签调用如下:
<s:select name="userLevel" list="@com.itqiang.bean.user.UserLevel@getValues2()" value="@com.itqiang.bean.user.UserLevel@KEYUAN.getValue()" />
?
注意静态方法调用需要:
<!-- OGNL可以使用静态方法 -->
?<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>?