1、在Eclipse下新建Dynamic Web project項目
2、在WEB-INF/lib下拷入Struts2必要jar包
3、在WEB-INF下新建web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- web-app是Web應用配置的根元素,指定Web應用的Schema信息 -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 定義struts 2 的FilterDispatcher的Filter -->
<filter>
<!-- 定義核心Filter的名字 -->
<filter-name>struts2</filter-name>
<!-- 定義核心Filter實現類 -->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- FilterDispatcher用來初始化struts2並且處理所有的Web請求 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4、在根目錄下新建login.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登錄頁面</title>
</head>
<body>
<!-- 提交請求參數的表單 -->
<form action="LoginAction" method="post">
<table align="center">
<caption><h3>用戶登錄</h3></caption>
<tr>
<!-- 用戶名的表單域 -->
<td>用戶名:<input type="text" name="username"/></td>
</tr>
<tr>
<!-- 密碼的表單域 -->
<td>密 碼:<input type="password" name="password"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="登陸"/><input type="reset" value="重填" /></td>
</tr>
</table>
</form>
</body>
</html>
5、在src目錄下建包com.sun.action並新建LoginAction.java頁面
package com.sun.action;
public class LoginAction {
//下面是Action內用於封裝用戶請求參數的兩個屬性
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//處理用戶請求的execute方法
public String execute() throws Exception{
//當用戶請求參數的username等於scott,密碼請求參數爲tiger時,返回success字符串
//否則返回error字符串
if(getUsername().equals("scott")&&getPassword().equals("tiger")){
return "success";
}else{
return "error";
}
}
}
6、在src根目錄下新建struts.xml文件,配置struts信息
<?xml version="1.0" encoding="UTF-8"?>
<!-- 指定 Struts 2 配置文件 DTD 信息 -->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0">
<!-- struts 是 Struts 2 配置文件的根元素 -->
<struts>
<!-- Struts 2 的 Action 必須放在指定的包空間下定義 -->
<package name="default" namespace="/" extends="struts-default">
<!-- 定義login的Action,該 Action 的實現類爲 lee.Action類 -->
<action name="LoginAction" class="com.sun.action.LoginAction" method="execute">
<!-- 定義處理結果和資源之間映射關係 -->
<result name="error">/error.jsp</result>
<result name="success">/welcome.jsp</result>
</action>
</package>
</struts>
7、全項目目錄樹如下圖所示: