Struts2课程 - 3.1 使用web.xml配置Struts2实现Web项目Struts2应用
在现在开发的 Web 项目中,大家都是使用 web.xml 来实现 MVC 框架的应用。既然 Struts2 也属于 MVC 框架,因此在 web.xml 中必定要配置 Struts2 用以实现应用。
技术要点
本节代码说明 Struts2 基本配置。
= 如何加载 FilterDispatcher 过滤器。
= 如何使用 FilterDispatcher 过滤器拦截 URL 。
演示代码
<!------------------------------------------- 文件名: web.xml-------------------------------->
<?xml version="1.0" encoding="GB2312"?>
<web-app xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
version="2.4"
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>
<!-- 过滤器支持的 struts2 类 -->
<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>
代码解释
( 1 )在 Struts1 中 web.xml 中对它的加载都是加载一个 Servlet ,但是在 Struts2 中,因为设计者为了实现 AOP (面向方面编程)概念,因此是用 filter 来实现的。所以 web.xml 里加载的都是 Struts2 的 FilterDispatcher 类。 <filter-name> 是定义的过滤器名字,而 <class> 就是 Struts2 里那个 FilterDispatcher 类。
( 2 )定义好过滤器,还需要在 web.xml 里指明该过滤器是如何拦截 URL 的。 <url-pattern></url-pattern> 中的“ /* ”是个通配符,它表明该过滤器是拦截所有的 HTTP 请求。基本上是不会改成其他形式,因为在开发中所有的 HTTP 请求都可能是一个页面上进行业务逻辑处理的请求。就目前而言,开发人员只需要写成“ /* ”就可以了。
( 3 )本节中的示例代码是最基本的 web.xml 配置 Struts2 的内容。其实还有 <init-param> 等设置过滤器初始化参数的配置内容。之所以这里没有具体解释,是因为这些也可以在 struts.properties 文件内定义 。
更多信息请查看 java进阶网 http://www.javady.com