1. 得到开发用到的struts2jar包
a. jar获得地址http://struts.apache.org/download.cgi#struts2312
在解压开的lib目录下找到开发需要的jar包,因为不同的应用开发需要的jar包也不同,下面只给出开发struts2程序最少的jar文件
struts2-core-2.3.1.2.jar : Struts2框架的核心类库
xwork-core-2.3.1.2.jar : XWork类库,Struts2在其上构建
ognl-3.0.4.jar :对象图导航语言,Struts2框架通过其读写对象的属性
freemarker-2.3.18.jar :struts2的UI标签的模板使用FreeMarker缩写
commons-logging-1.1.1.jar :asf出品的日志包,Struts2框架使用这个日志包来支持Log4和jdk1.4+的日志记录
commons-fileupload-1.2.2.jar:文件上传组件
commons-io-2.0.1.jar
commons-lang-2.5.jar
javassist-3.11.0.GA.jar
2. 编写struts2的配置文件
a. 在WEB-INF的class文件夹下放置struts.xml,该文件可以在下载包的apps文件夹中的例子中解压获得,文件内容大致如下:
<?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="sayHello" namespace="/test" extends="struts-default">
<action name="helloworld" class="com.jx.action.HelloWorldAction" method="execute">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
</struts>
解释:
a. struts2框架中使用包来管理Action,它主要用于管理一组业务功能相关的action.在实际开发中,我们应该把一组业务相关的action放在同一个包下。
b.包名必须填写,且唯一,如果其他包要继承该包,必须通过该属性进行引用。
c. namespace属性是该包的命名空间,作为访问该包下action的路径的一部分;namespace可以不配,如果不指定该属性,默认的命名空间为“”。
d. 当包继承了struts-default才能使用struts2提供的核心功能。通常每个包都应该继承struts-default包,因为struts2很多核心的功能都是拦截器来实现。如:从请求中把请求参数封装到action、文件上传和数据验证等等都是通过拦截器实现的。Struts-default定义了这些拦截器和Result类型。struts-default包是在struts2-core-2.x.x.jar文件中的struts-default.xml中定义。struts-default.xml也是struts2默认配置文件,每次都会自动加载struts-default.xml文件。
3. 在web.xml文件中加入Struts2mvc框架启动配置
a. 配置struts2的拦截器到web.xml文件中,内容大致如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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">
<display-name>Struts Blank</display-name>
<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.html</welcome-file>
</welcome-file-list>
</web-app>