我們必須首先下載struts2的包。其下載地址為:http://struts./download.cgi#struts2211
struts2的開發(fā)步驟大致如下:
(1)準(zhǔn)備類庫
(2)在web.xml文件中配置FilterDispatcher
(3)開發(fā)action。針對每一個(gè)功能點(diǎn),編寫一個(gè)action類。
(4)編寫相關(guān)的結(jié)果頁面。針對action返回的結(jié)果代碼,編寫相應(yīng)的結(jié)果頁面。
(5)在Web應(yīng)用程序的WEB-INF/classes目錄下創(chuàng)建struts.xml,對action進(jìn)行配置,將頁面與結(jié)果頁面關(guān)聯(lián)在一起。
具體的操作如下:
step 1:新建web項(xiàng)目
新建web
project。

step 2:導(dǎo)入struts類庫

step
3:在web.xml文件中配置FilterDispatcher
得到的web.xml文件內(nèi)容如下:
<?xml version="1.0"
encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java./xml/ns/j2ee"
xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:schemaLocation="http://java./xml/ns/j2ee
http://java./xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
step 4:編寫Action類
輸入Name為:HelloWorldAction。
然后選擇Add,在choose interfaces中填入Action,選擇com.open....。如下圖:

于是在src的ch03.action中生成了文件HelloWorldAction.java。
編輯其內(nèi)容如下:
package ch03.action;
import com.opensymphony.xwork2.Action;
public class HelloWorldAction implements Action {
private String message;
public String getMessage()
{
return message;
}
public String execute() throws Exception {
message="Hello World.";
return SUCCESS;
}
}
step 5:編寫結(jié)果頁面
新建jsp文件,命名為HelloWorld.jsp。內(nèi)容如下:
<%@ page
contentType="text/html;charset=GBK"%>
<%@ taglib prefix="s"
uri="/struts-tags"%>
<html>
<head><title>歡迎頁面</title></head>
<body>
<h2><s:property
value="message"/></h2>
</body>
</html>
step 6:在struts.xml文件中配置action
struts.xml是Struts框架的核心設(shè)置文件,默認(rèn)的路徑是:WEB-INF/classes/struts.xml。
其內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"
?>
<!DOCTYPE struts PUBLIC
"-//Apache
Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts./dtds/struts-2.0.dtd">
<struts>
<package
name="default" extends="struts-default">
<action name="HelloWorld"
class="ch03.action.HelloWorldAction">
<result
name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
step 7:發(fā)布并測試


最后得到的目錄結(jié)構(gòu)為:

以上的目錄結(jié)構(gòu)非常重要,程序出錯(cuò)的很大一部分原因就是一些文件放錯(cuò)了位置。具體的錯(cuò)誤表現(xiàn)為:程序的各部分都沒有出錯(cuò),但是最后卻得不到想要的結(jié)果。
測試輸入網(wǎng)址:http://localhost:8080/ch03/HelloWorld.action
得到的結(jié)果為:HelloWorld
|