论坛首页 Java企业应用论坛

Struts2 入门实例代码

浏览 47629 次
精华帖 (6) :: 良好帖 (3) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-03-24  
Struts.xml 文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <include file="helloworld.xml"/>
</struts>


HelloWorld.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<include file="struts-default.xml"/>
    <package name="helloworld" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name ="authentication" class ="com.jamesby.struts2.LogonInterceptor"/> 
	        <interceptor-stack name="helloWorldStack">
	            <interceptor-ref name="authentication"/>
	            <interceptor-ref name="paramsPrepareParamsStack"/>
	        </interceptor-stack>
        </interceptors>  
		<default-interceptor-ref name="helloWorldStack"/>
		<global-results>
			<result name="login">/WEB-INF/jsp/Logon.jsp</result>				
                  </global-results>		
		<action name="Logon_*" method="{1}" class="com.jamesby.struts2.Logon">
			<interceptor-ref name="paramsPrepareParamsStack"/>		
			<result type="redirect-action">Main</result>
			<result name="input">/WEB-INF/jsp/Logon.jsp</result>		
		</action>
		<action name="crud" method="{1}" class="com.jamesby.struts2.UserAction">
			<result name="list">/WEB-INF/jsp/userList.jsp</result>				<result name="success" type="redirect-action">crud!list</result>
			<result name="input">/WEB-INF/jsp/userForm.jsp</result>
		</action>
		<action name="*" class="com.jamesby.struts2.ExampleSupport">
			<result>/WEB-INF/jsp/{1}.jsp</result>
		</action>         
    </package>
</struts>


LogonInterceptor.java

package com.jamesby.struts2;
import java.util.Map;
import com.jamesby.struts2.persist.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LogonInterceptor extends AbstractInterceptor{
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Map session = ai.getInvocationContext().getSession();
		User user = (User) session.get("user");
		if (null != user) {
			return ai.invoke();
		} else {
			return Action.LOGIN;
		}
	}
}


Logon.java

package com.jamesby.struts2;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.jamesby.struts2.persist.DataBaseMock;
import com.jamesby.struts2.persist.User;
import com.opensymphony.xwork2.ActionSupport;
public class Logon extends ActionSupport implements SessionAware {
	private Map session;
	public void setSession(Map session) {
		this.session = session;
	}
	@SkipValidation
	public String doInput() throws Exception {
		return INPUT;
	}
	public String doLogon() throws Exception {
		User user = DataBaseMock.selectUserByUsernameAndPassword(getUsername(),
				getPassword());
		if (null == user)
			return INPUT;
		session.put("user", user);
		return SUCCESS;
	}
	private String username;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	private String password;
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


UserAction.java

package com.jamesby.struts2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.jamesby.struts2.persist.DataBaseMock;
import com.jamesby.struts2.persist.User;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction  extends ActionSupport {
	private User user=new User();
	private List<User> userList;
	public List<HashMap> getSexArray() {
		List<HashMap> sexArray = new ArrayList<HashMap>();
		HashMap male = new HashMap();
		male.put("key",new Integer(1));
		male.put("value","男");
		HashMap female = new HashMap();
		female.put("key",new Integer(2));
		female.put("value","女");		
		sexArray.add(male);
		sexArray.add(female);
		return sexArray;
	}	
	public List<HashMap> getFromArray() {
		List<HashMap> fromArray = new ArrayList<HashMap>();
		HashMap bj = new HashMap();
		bj.put("id",new Integer(1));
		bj.put("name","北京");
		HashMap sh = new HashMap();
		sh.put("id",new Integer(2));
		sh.put("name","上海");		
		HashMap tj = new HashMap();
		tj.put("id",new Integer(3));
		tj.put("name","天津");
		fromArray.add(bj);
		fromArray.add(sh);
		fromArray.add(tj);
		return fromArray;
	}
	@SkipValidation
	public String doList() throws Exception {
		userList = DataBaseMock.selectAllUser();
		return "list";
	}
	@SkipValidation
	public String doInput() {
		return INPUT;
	}	
	public String doSave() {
		if (null == user.getUserid()) {
			user.setUserid(new Integer(DataBaseMock.getNewUserId()));
			DataBaseMock.saveUser(user);
		}else
		{
			DataBaseMock.updateUser(user);
		}
		return SUCCESS;
	}
	@SkipValidation
	public String doRead()
	{
		user = DataBaseMock.getUser(user.getUserid());
		return INPUT;
	}
	@SkipValidation
	public String doDelete() {
		DataBaseMock.deleteUser(user);
		return SUCCESS;
	}		
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
}


ExampleSupport.java

package com.jamesby.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class ExampleSupport extends ActionSupport {
}


User.java

package com.jamesby.struts2.persist;
public class User {
	private Integer userid;
	private String username;
	private String password;
	private int sex;
	private int age;
	private int from;
	public int getFrom() {
		return from;
	}
	public void setFrom(int from) {
		this.from = from;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public Integer getUserid() {
		return userid;
	}
	public void setUserid(Integer userid) {
		this.userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}


DataBaseMock.java

package com.jamesby.struts2.persist;
import java.util.ArrayList;
import java.util.List;
public class DataBaseMock {
	private static List<User> _cache = new ArrayList<User>();
	private static int userid = 0;
	static {
		User user = new User();
		user.setUserid(new Integer(0));
		user.setUsername("admin");
		user.setPassword("12345688");
		user.setFrom(1);// 北京
		user.setSex(1);// 男
		user.setAge(18);
		_cache.add(user);
	}
	public static User selectUserByUsernameAndPassword(String username,String password)
	{
		for (User u : _cache) {
			if (u.getUsername().equals(username)&&u.getPassword().equals(password)) {
				return u;
			}
		}
		return null;
	}
	public static List<User> selectAllUser()
	{
		return _cache;
	}
	public static int getNewUserId() {
		return ++userid;
	}
	public static void saveUser(User user) {
		_cache.add(user);
	}
	public static void updateUser(User user) {
		deleteUser(user);
		saveUser(user);
	}
	public static void deleteUser(User user) {
		for (User u : _cache) {
			if (u.getUserid().intValue() == user.getUserid().intValue()) {
				_cache.remove(u);
				break;
			}
		}
	}
	public static User getUser(Integer userid) {
		return _cache.get(userid);
	}
}


Logon-validation.xml

<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
    <field name="username">
        <field-validator type="requiredstring">
			<message key="requiredstring"/>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring">
			<message key="requiredstring"/>
        </field-validator>
    </field>
</validators>


UserAction-validation.xml

<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
  <field name="user.username">
     <field-validator type="requiredstring">
        <message key="errors.required.username"/>
      </field-validator>
  </field>
  <field name="user.password">
     <field-validator type="requiredstring">
        <message key="errors.required.password"/>
      </field-validator>
  </field>
  <field name="user.sex">
     <field-validator type="required">
        <message key="errors.required.sex"/>
      </field-validator>
  </field>  
  <field name="user.age">
     <field-validator type="required" short-circuit="true">
        <message key="errors.required.age"/>
      </field-validator>
      <field-validator type="int">
      	<param name="min">18</param>
      	<param name="max">65</param>
        <message key="errors.required.age.limit"/>
      </field-validator>
  </field>
  <field name="user.from">
     <field-validator type="required">
        <message key="errors.required.from"/>
      </field-validator>
  </field>    
</validators>


package.properties

requiredstring = $\{getText(fieldName)} is required.
password = Password
username = User Name
main.message = This is main page...................
label.userList= All User List

user.username=Username
user.password=Password
user.sex=Sex
user.age=Age
user.from=From

errors.required.username=Username is required
errors.required.password=Password is required
errors.required.sex=Sex is Required
errors.required.from=From is Required
errors.required.age.limit=Age between 18 and 65
errors.required.age.limit=Age between 18 and 65


Logon.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Logon</title>
</head>
<body>
<s:form action="Logon!logon"> 
  <s:textfield label="%{getText('username')}" name="username"/>
  <s:password label="%{getText('password')}" name="password" />
  <s:submit/>
</s:form>
</body>
</html>


userList.jsp

<%@ page contentType="text/html;charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags" %>

<head>
    <title><s:text name="label.userList"/></title>
</head>

<s:url id="url" action="crud!input" />
<a href="<s:property value="#url"/>">Add New User</a>
<br>
<table border="1">
	<tr class="<s:if test="#status.even">even</s:if><s:else>odd</s:else>">
		<td>用户ID</td>
		<td>用户名</td>
		<td>性别</td>
		<td>年龄</td>
		<td>来自</td>
		<td>修改</td>
		<td>删除</td>
	</tr>	
<s:iterator value="userList" status="status">
	<tr class="<s:if test="#status.even">even</s:if><s:else>odd</s:else>">
		<td><s:property value="userid" /></td>
		<td><s:property value="username" /></td>
		<td>
			<s:if test="sex==1">男</s:if>
			<s:else>女</s:else>
		</td>
		<td><s:property value="age" /></td>
		<td>
			<s:if test="from==1">北京</s:if>
			<s:if test="from==2">上海</s:if>
			<s:if test="from==3">天津</s:if>
		</td>
		<td>
			<a href="crud!read.action?user.userid=<s:property value="userid" />">修改</a>
		</td>
		<td>
			<a href="crud!delete.action?user.userid=<s:property value="userid" />">删除</a>
		</td>
	</tr>	
</s:iterator>
</table>



userForm.jsp

<%@ page contentType="text/html;charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags" %>
User Form
<s:form action="crud!save.action" method="post">
    <s:textfield required="true" name="user.username" value="%{user.username}" label="%{getText('user.username')}" size="40"/>
    <s:textfield required="true" name="user.password" value="%{user.password}" label="%{getText('user.password')}" size="40"/>
    <s:radio required="true" name="user.sex" listKey="key" listValue="value" value="%{user.sex}" label="%{getText('user.sex')}" list="sexArray"/>
    <s:textfield required="true" name="user.age" value="%{user.age}" label="%{getText('user.age')}" size="40"/>
    <s:select label="%{getText('user.from')}" name="user.from" headerKey="" headerValue="Select From" list="fromArray" listKey="id" listValue="name" value="user.from" required="true"/>
    <s:hidden name="user.userid" value="%{user.userid}"/>
    <s:submit value="Submit"/>
    <s:submit value="Cancel" name="redirect-action:crud!list"/>
</s:form>


应用程序目录结构

WEB-INF
│  web.xml
│
├─classes
│  │  commons-logging.properties
│  │  helloworld.xml
│  │  log4j.properties
│  │  struts.properties
│  │  struts.xml
│  │
│  └─com
│      └─jamesby
│          └─struts2
│              │  ExampleSupport.class
│              │  Logon-validation.xml
│              │  Logon.class
│              │  LogonInterceptor.class
│              │  package.properties
│              │  UserAction-validation.xml
│              │  UserAction.class
│              │
│              └─persist
│                      DataBaseMock.class
│                      User.class
│
├─jsp
│      Logon.jsp
│      Main.jsp
│      userForm.jsp
│      userList.jsp
│
├─lib
       commons-collections-3.1.jar
       commons-logging-1.0.4.jar
       freemarker-2.3.8.jar
       log4j-1.2.9.jar
       ognl-2.6.11.jar
       struts2-core-2.0.6.jar
       xwork-2.0.1.jar



   发表时间:2007-03-24  
本事例首先自己编写了一个拦截器,确保未登陆的用户不能进行任何操作。

然后就是一个简单的CRUD的功能!
0 请登录后投票
   发表时间:2007-03-24  
正在学习中支持你啊~~
0 请登录后投票
   发表时间:2007-03-25  
现在就是有一个问题没有搞明白,在我的userForm.jsp文件中没有编写任何table之类的HTML代码,为什么struts2会帮我生成一个table.

默认好象使用template\xhtml\*.ftl文件作为模板,就是说struts2 默认使用freemarker作为模板,可是如何才能不使用任何模板呢?

### Standard UI theme
### Change this to reflect which path should be used for JSP control tag templates by default
struts.ui.theme=xhtml
struts.ui.templateDir=template
#sets the default template type. Either ftl, vm, or jsp
struts.ui.templateSuffix=ftl
0 请登录后投票
   发表时间:2007-03-25  
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.ui.templateDir" value="template" />     
    <constant name="struts.ui.theme" value="simple" />    
    <constant name="struts.ui.templateSuffix" value="ftl" />    
    <include file="helloworld.xml"/>
</struts>


struts.xml 文件配置成上面这样,是可以去掉table标签的,但是很多功能可能就不能正常了,特别是标签内容的显示和校验回显可能需要自己使用ongl手动调用,具体不清楚。

从struts2的结构看似乎它推荐使用模板语言,而且默认为freemarker,当然可以自己更改为velocity,看来还要搞定freemarker或者velocity后,struts2才算学习的完整。
0 请登录后投票
   发表时间:2007-03-26  
正在学习struts2,lz写得很详细,收了
0 请登录后投票
   发表时间:2007-03-26  
看看了
0 请登录后投票
   发表时间:2007-03-26  
啊   一 看到 配置 文件 就 晕了 ,也没人给写写 XML的 注释!

是我太懒了吧 ,嘿嘿!
0 请登录后投票
   发表时间:2007-03-26  
piaochunzhi 写道
啊   一 看到 配置 文件 就 晕了 ,也没人给写写 XML的 注释!

是我太懒了吧 ,嘿嘿!
就是一个Interceptor和几个action.

如果想要完整的配制参考http://struts.apache.org/dtds/struts-2.0.dtd就可以了啊。

有些东西是自己发挥的,也不知道写的对不对,希望没有把大家引入歧途,另外有什么不正确的地方请批评指正。

0 请登录后投票
   发表时间:2007-03-26  
先表示感谢一下,再慢慢看!
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics