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的名称。