1. 程式人生 > >Struts2 入門例項程式碼

Struts2 入門例項程式碼

[b]Struts.xml 檔案[/b]

[code]<?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>[/code]

[b]HelloWorld.xml[/b]

[code]<?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>[/code]

[b]LogonInterceptor.java[/b]

[code]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;
}
}
}[/code]

[b]Logon.java[/b]

[code]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;
}
}[/code]

[b]UserAction.java[/b]

[code]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;
}
}[/code]

[b]ExampleSupport.java[/b]

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

[b]User.java[/b]

[code]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;
}
}[/code]

[b]DataBaseMock.java[/b]

[code]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);
}
}[/code]

[b]Logon-validation.xml[/b]

[code]<!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>[/code]

[b]UserAction-validation.xml[/b]

[code]<!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>[/code]

[b]package.properties[/b]

[code]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[/code]

[b]Logon.jsp[/b]

[code]<%@ 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>[/code]

[b]userList.jsp[/b]

[code]<%@ 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>[/code]


[b]userForm.jsp[/b]

[code]<%@ 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>[/code]

[b]應用程式目錄結構[/b]

[code]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
[/code]