struts配置流程

来源:互联网 发布:php应用网站源码 编辑:程序博客网 时间:2024/05/16 07:48

引导语:在学习框架的过程中,总是有各种配置要配,稍不注意就会导致程序错误。本人java web新手,为了增强记忆巩固学习,决定写篇日志理清一下struts配置的思路。

在学习完servlet和jsp后,我们面对的第一个框架就是ssh中的struts了,struts是一种基于mvc思想设计的web框架,所以其配置思路也遵循mvc配置思路。

要想掌握struts,就得先理解其原理(自画渣图,原图借鉴自how2j.cn,一个不错的java学习网站):

                                                                                            struts原理uml图

                                

从其原理不难看出,其核心配置是struts.xml文件,其次是web.xml中的拦截器配置。当然有通过注解进行配置的,但是初学还是从xml入手比较好,简单易懂。

在图中我多次用到“对应”二字,这些对应都是在struts.xml中进行配置的,其一般格式为:

<?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="basicstruts" extends="struts-default">    <action name="url" class="Action文件路径" method="Action中的方法名">    <result name="对应的有意义的名称">结果页.jsp</result>  </action>      </package>  </struts>

举个栗子:

 

<?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="basicstruts" extends="struts-default">    <action name="showMoney" class="com.project.action.MoneyAction" method="show">    <result name="show">show.jsp</result>  </action>      </package>  </struts>
其中showMoney表示访问路径为 路径/showMoney.调用的Action文件为MoneyAction.java,它的包路径为com.project.action.然后调用它的show()方法,show()方法会返回一个

String "show",对应跳转结果为show.jsp页面。配置一个Action的多个方法可以用通配符*,简单了解就可掌握。

web.xml的一般配置为:

<web-app>    <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>        <dispatcher>FORWARD</dispatcher>        <dispatcher>REQUEST</dispatcher>                <url-pattern>/*</url-pattern>    </filter-mapping> </web-app>
从filter-mapping中可以看出,文件将dispatcher FORWARD和REQUEST都配给了struts2,并且ulr-pattern配置为所有,说明一切路径访问都会被这个拦截器拦截。

关于struts的配置就说这么多,最后再说一遍,先理解原理,后面深入就会更快