【SSH】Struts2配置文件学习

来源:互联网 发布:淘宝店铺年费 编辑:程序博客网 时间:2024/06/06 01:05
       在Web开发项目中,都是使用web.xml来实现MVC框架的应用,如果要使用Struts的MVC模式,我们就必须在Web.xml中对Struts2进行配置,然后使用Struts.xml来对页面进行导航
 

   一、 在web.xml中需要配置的有两个地方:


    (1)加载FilterDispatcher过滤器
    (2)使用FilterDispatcher过滤器进行拦截URL。

web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"         version="3.1">    <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>


        为了实现AOP概念,都用filter来实现。定义好过滤器,还应该指明如何拦截URL。其中/*为通配符,它表明该过滤器是拦截所有的HTTP请求。


二、使用Struts.xml实现页面导航定义


        在Struts2中最核心的是Action,而Action的核心是struts.xml,它集中实现了所有页面的导航定义。
     
     (1)XML文件字符编码定义和DTD文件声明(DTD表明Struts.xml是支持struts2文档类型定义)。

     (2)global-results映射定义,如何进行全局导航页面。(可以被多个Action共用),如果在action中找不到定义的result唯一标识,就去寻找global中result的。

     (3)package映射定义,包含的Action各属性介绍。

Struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts><!--Action所在包定义-->    <package name="C01" namespace="/" extends="struts-default">         <default-action-ref name="index" /> <!--全局页面导航定义-->        <global-results>            <result name="error">/WEB-INF/jsp/error.jsp</result>        </global-results>         <global-exception-mappings>            <exception-mapping exception="java.lang.Exception" result="error"/>        </global-exception-mappings> <!--Action名字,类以及导航页面定义-->        <!--直接导航的Action定义-->        <action name="index">            <result>/jsp/login.jsp</result>        </action>        <!--通过Action类处理才导航的Action定义-->        <action name="Login"                class="com.example.struts.action.LoginAction">            <result name="input">/jsp/login.jsp</result>            <reuslt name="success">/jsp/success.jsp</reuslt>        </action>    </package>     <include file="example.xml"/>     <!-- Add packages here --> </struts>

       其中,Action中的name属性是JSP页面上定义的Action名字,在Struts2系统中主动找名字Action,一旦找到就根据class属性中定义的Action类路径去执行该Action。Action中的result相当于forward属性,name 是唯一标识,通过检索标识,Action对象分装了需要指向的URL,系统就会将最后响应的信息转到URL所指的JSP页面。

     注意:forward和redirect的区别是:forward不会显示转向后的页面地址,它仅是控制器的转向。而redirect是完全跳转,浏览器显示转向后的地址,并重新发送请求。因此,前者效率要高一些,还可以隐藏实际的链接地址。

1 0