web.xml文件的配置與1相同。
1)HelloWorld類的代碼:
public class HelloWorldAction {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() {
message = "The First Struts2 App";
return "success";
}
}
2)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>
<!-- package中的屬性:
name:用於其它包繼承該包
namespace:在訪問時唯一確定一個包的路徑
extends:繼承struts-default,以實現struts的核心功能
action中的屬性:
name:在訪問時與命名空間一起唯一確定包的action
class:action要跳轉到的action類
method:action的實現方法
result中的屬性:
name:action類中的實現方法會根據該名字進行跳轉
index.jsp:要跳轉到的顯示層
-->
<package name="packageName" namespace="/test"
extends="struts-default">
<action name="helloworld" class="itcase.HelloWorldAction"
method="execute">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
3)顯示層index.jsp的代碼:
<%@ page language="java" import="java.util.*"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP Page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
</head>
<body>
<!-- Ognl表達式,可以顯示action獲取的action類的屬性 -->
${message }
</body>
</html>
配置好上述配置,重新發布Tomcat,若沒有錯誤,打開瀏覽器,輸入:http://localhost:8080/Struts_1/test/helloworld
其中:localhost:8080爲本地電腦接口;
Struts_1:整個文件所在的web項目名稱;
Test:命名空間;
helloworld:action的名稱。