---
title: "java枚举在struts2中的应用"
author: "wysaijun1314"
date: "2011-12-08T09:54:54Z"
tags: []
categories: ["编程语言"]
slug: "java-struts2"
draft: false
lastmod: "2011-12-08T09:54:54Z"
id: 1297375
url: "https://vsp.iteye.com/blog/1297375"
---

平常很少用java的枚举，也时常在想怎么来用它，最近结合struts2在jsp中来使用一下枚举
首先定义一个Rose类，很多时候为了方便，经常在页面写几个角色的选项（项目比较小）,这样带来的的问题是显而易见的,
这里如果用枚举的话就方便了，当然放到数据库中也是可以的，不过个人觉得如果种类不多话，建议用枚举。 
1.首先建立枚举类

```java

public enum Rose {
	
	SUPERADMIN(1,"超级管理员"),ADMIN(2,"管理员"),GUEST(3,"游客");
	private Integer code;
	private String roseName;
	
	public Integer getCode() {
		return code;
	}

	public String getRoseName() {
		return roseName;
	}

	private Rose(Integer code,String roseName){
		
		this.code = code;
		this.roseName = roseName;
		
	}
}

```

2.将Rose放到action的request中

```java

request.setAttribute("rose", Rose.values());

```

3.在页面上使用循环取出结果

```java

<s:iterator id="r" value="#request.rose">
		<s:property value="#r.code"/>:
		<s:property value="#r.roseName"/>							
									
</s:iterator>

```

如图：

![](http://dl.iteye.com/upload/attachment/602163/b3c119e8-db2f-3011-8c9d-3ac2c0817ba8.jpg)

4.在页面上使用checkbox取出枚举值

```java

<s:checkboxlist  name="con" list="#request.rose" listKey="code" listValue="roseName"> </s:checkboxlist>

```

如图：

![](http://dl.iteye.com/upload/attachment/602167/74afb2ce-937f-3a48-818e-8601bc79bec6.jpg)

当然还有其它的用法就不在列出来了.