---
title: "struts2示例学习1-HelloWorld"
author: "andyjames"
date: "2008-05-21T10:39:16Z"
tags: []
slug: "struts2-1-helloworld"
draft: false
lastmod: "2008-05-21T10:39:16Z"
id: 195125
url: "https://andyjames.iteye.com/blog/195125"
---

**这是Struts2的第二篇入门学习，从helloworld入手学习，使用了MVC的设置模式，下面是详细介绍和示例：**

    当提交一个Html的Form给Struts2框架时，数据不再是提交给服务器端的某一个JSP页面，而是提交给一个Action类。而框架根据配置文件把与该Action类对应的页面（这个页面可以是JSP页面，也可以是PDF、Excel或Applet）返回给客户端。

写一个Struts2的HelloWorld ， 我们需要做三件事：

1\. 创建一个显示信息的JSP文件

2\. 创建一个生成信息的Action类

3\. 建立JSP页面和Action的mapping（映射）

**创建HelloWorld.jsp文件**   
 

```

<%...@ taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h2><s:property value="message" /></h2>
    </body>
</html>

```

HelloWorld.jsp存放在war目录下面

**创建Action类HelloWorld.java**  
 

```

package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport ...{
public static final String MESSAGE = "Struts is up and running ...";
public String execute() throws Exception ...{
setMessage(MESSAGE);
return SUCCESS;
}
private String message;
public void setMessage(String message)...{
this.message = message;
}
public String getMessage() ...{
return message;
}
}
```

HelloWorld.java存放在src/tutorial下面  
**在struts.xml建立映射**

```

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="tutorial" extends="struts-default">
        <action name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
</action>
        <!-- Add your actions here -->
    </package>
</struts>
```

   
    此文件存放在classes下面，同时还要建一个struts.properties的属性文件放在这个目录下，这个文件可以是空的，什么都不写  
**创建web.xml**

```

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Struts2 Hello World!</display-name>
<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>
```

   
web.xml毫无疑问放在WEB-INF下

   
**创建build.xml**

```

<?xml version="1.0"?>
<project name="struts2app" basedir="." default="usage">
    <property file="build.properties"/>
    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="struts2app"/>
    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <!-- We need the servlet API classes:        -->
        <!--   for Tomcat 4.1 use servlet.jar        -->
        <!--   for Tomcat 5.0 use servlet-api.jar    -->
        <!--   for Other app server - check the docs -->
        <fileset dir="${appserver.home}/common/lib">
            <include name="servlet*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>
    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="build     --> Build the application"/>
        <echo message="deploy    --> Deploy application as directory"/>
        <echo message=""/>
    </target>
    <target name="build" description="Compile main source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" target="1.3" debug="true"
               deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>
    <target name="deploy" depends="build" description="Deploy application">
        <copy todir="${deploy.path}/${name}" preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>
</project>
```

   
build.xml放在struts2app目录下，再在这个目录下建一个build.properties文件，内容如下:

按照build.properties配置你的tomcat位置。在struts2app目录下运行ant build ，ant deploy ，程序就发布到tomcat的webapps下

\# Ant properties for building the springapp  
appserver.home=d:/tomcat5.5  
deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager  
tomcat.manager.username=admin  
tomcat.manager.password=admin  
 

运行  
现在，启动tomcat，访问[http://localhost:8080/tutorial/HelloWorld.action](http://localhost:8080/tutorial/HelloWorld.action)，能看到页面的title为"Hello World!" ，页面上显示"Struts is up and running!".

它们怎么运行的  
1、struts2容器收到HelloWorld.action请求，从web.xml获取设置，org.apache.struts2.dispatcher.FilterDispatcher是所有应用（包括\*.action）的入口点。  
2、 struts2在struts.xml中找到HelloWorld类（Action），并调用它的execute方法。  
3、 execute方法给message变量赋值，并返回SUCCESS，struts2收到SUCCESS标志，按照映射关系，把HelloWorld.jsp返回客户端。  
4、  当HelloWorld.jsp开始运行，&lt;s:property value="message" /&gt;会调用HelloWorld类getMessage方法，把结果显示在页面上。