这是我学Struts2以来的编写的第一个Action,虽然简单,但也把我折腾得够怆的,不过,倒也从中让我收益良多,至少,让我对Struts2框架有了比较感性的认识。
首先,在MyEclipse中创建一个web project,我命名为Hello,在Hello工程下的WebRoot\WEB-INF\lib中添加以下几个Struts2中的包(不用将Struts2中的所有包都添加进来,以下几个就行),它们分别是
commons-logging-1.0.4.jar
ognl-2.6.11.jar
tiles-jsp-2.0.4.jar
struts2-core-2.0.9.jar
xwork-2.0.4.jar
freemarker-2.3.8.jar
接下来,创建相应的文件并编写代码(注意其创建的位置)
helloworld.java(在src文件夹中的example包中)
package example;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class helloworld extends ActionSupport{
public String message;
//实现execute的方法,为message赋值
public String execute(){
message="hello world!\n";
return SUCCESS;
}
public String getMessage(){
return message;
}
}
struts.xml(在src文件夹中)
<?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.devMode" value="true" />
<!-- 在包中导入Struts自带的配置文件struts-default.xml -->
<package name="default" extends="struts-default">
<!-- 配置自已定义的Action -->
<action name="hello" class="example.helloworld">
<!-- 根据不同的返回字符串类型,跳转到不同的页面 -->
<result name="success">hello.jsp</result>
</action>
</package>
</struts>
hello.jsp
<%@ page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%-- 在这里用到Struts 2的标签,需要先导入标签库,并为之定义一个前缀 --%>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
The message generated by my first action is:
<%-- 取出Action中对应的message的值 --%>
<s:property value="message" />
</body>
</html>
web.xml(默认位置,只是对其配置做修改而已)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Struts 2 First</display-name>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
最后,在地址栏中输入http://localhost:8080/Hello/hello.action
如果成功的话,会显示The message generated by my first action is: hello world!