一、 搭建Struts2的运行环境:
1、建立Web Project;
2、建立Struts2的配置文件(struts.xml);
将Struts2的空项目中的配置文件(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" />
<package name="front" namespace="/" extends="struts-default">
<action name="index" class="com.fzj.action.IndexAction" >
<result name="success">/action.jsp</result>
</action>
</package>
</struts>
再在WebRoot目录下建一个action.jsp文件。(内容自己写)
3、复制Struts2相应的jar包及第三方包。
将空项目中lib目录中的除junit和spring-test之外的所有文件复制到项目的WebRoot/WEB-INF/lib目录下
4、修改对应的web.xml,建立struts2的filter(参考struts自带的项目),添加如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</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>
注:在struts.xml配置文件中,<action>标签中的class属性是表示action的对应的类(这个类是一个普通Java类),当访问这个action时会创建这个类成为一个对象,然后执行这个对象中的execute方法()(execute方法返回类型为String)。
当<action>标签中class属性省略时,则默认执行com.opensymphony.xwork2.ActionSupport类中的execute方法,而这个方法返回一个字符串常量SUCCESS(常量值为:”success”).
5、具体视图的返回可以由用户自己定义的Action来决定
package com.fzj.front.action;
import com.opensymphony.xwork2.ActionSupport;
public class IndexAction extends ActionSupport {
public String add() {
return this.SUCCESS;
}
}
注:这种Action是我们需要使用的方式,因为这个类不担实现了com.opensymphony.xwork2.Action接口,更重要的是它已经帮我封装了许多其它有用的方法。
运行环境的搭建基本上ok了,可以在IE上输入http://localhost/struts_first/index
二、对于上面的部分标签及其属性做简单的解释:
1、struts.xml中
(1) struts.devMode : 是否设置为开发模式 true:是开发模式,否则不是
注:在开发模式下,修改Struts的配置文件后不需要重新启动Tomcat服务器即生效。
否则修改Struts配置文件后需要重新启动Tomcat服务器才生效。
(2)namespace :对应与项目名称后面的"/"(例如struts_first后面的"/")
(http://localhost:8080/struts_first/)
namespace决定了action的访问路径,默认为“”,可以接收所有路径的action,如果没有找到相应的namespace时,则使用namespace为空的action
namespace可以写为/,或者/xxx,或者/xxx/yyy,对应的action访问路径为/index.action、/xxx/index.action、或者/xxx/yyy/index.action.
namespace最好也用模块来进行命名。
(3) <package>标签
<package>是用来解决重名的问题,例如当系统的前台和后台都有一个action名叫hello,这时就需要用package来区分。前台<package name="front">后台<package name="back">
struts2中的package与java的package是相同的作用的。