1、Struts2历史,与Struts1的关系
两者的内部基于的原理完全不同,Struts2是基于WebWork发展而来的框架。两者都是基于MVC实现的框架。Struts1是Apach推出的。WebWork是opensyfry推出的。Strut2是以WebWork为核心,引入Struts1的特性(Struts2由Apach推出)。
2、Struts2的特点
(1)由Action组件承担Struts1中ActionForm和Action的功能。(2)Action非常灵活,可以使用一个普通的Class来充当。(3)Action可测性强。(4)提供了大量的Result组件(可以自定义),简化了处理响应的实现。(5)提供了大量的拦截器组件。(6)易于扩展、整合、维护。
3、Struts2的MVC实现
控制器实现:StrutsPrepareAndExecuteFilter 以前是(1.8之前)FilterDispatcher
Servlet可以成为控制器,Filter也可以成为控制器(相似的特点:可以直接获得请求, 可以写大量java代码)
视图实现:各种类型的Result,支持各种视图组件的响应
struts2标签(框架自带的标签),提供了分支,循环,显示等功能。
模型实现:普通的POJO(Action)更加灵活,
ValueStack组件,用于封装请求相关信息,例如request、session等
4、Strut2开发入门
(1)创建web工程,引入Struts2 jar包jar包下载地址:http://struts.apache.org/download.cgi#struts216下载后解压的完整jar包如下图:
至少需要如下6 个jar包:(注意:不可将jar包全部拷贝到lib下,里面部分plug-in插件jar包会冲突)
struts2-core-2.1.6.jar
freemarker-2.3.13.jar
commons-logging-1.0.4.jar
ognl-2.6.11.jar
xwork-2.1.2.jar
commons-fileupload-1.2.1.jar
(2)在web.xml中配置控制器,添加控制器的配置文件struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>myproject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
struts.xml可参考struts2-core jar包根目录下的struts-default.xml文件,格式完全相同,下面是部分配置:<struts><package name="package名字" extends="struts-default"><action name="请求名"class="对应action路径"><result name="响应字符串" type="响应方式">xxx.jsp</result></action></package></struts>注意:上面的请求名不要带扩展名struts2只响应扩展名为.action的请求,或者不带扩展名struts.xml放在src目录下Action中默认执行方法public String execute();