struts2的执行流程与配置详解

DonDeLittle 8年前

来自: http://blog.csdn.net/peace1213/article/details/50772777


本章主要讲解Struts的执行流程以及Struts的配置以及访问servletApi


全部代码下载:
github链接:链接

写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;

1.Struts的执行流程:

  • 1.服务器启动时
    1. 加载项目web.xml
    2. 创建Struts核心过滤器对象, 执行StrutsPrepareAndExecuteFilter的doFilter 的 init()方法:
      在StrutsPrepareAndExecuteFilter的init()方法中将会读取类路径下默认的配置文件struts.xml完成初始化操作。
      注意:
      struts2读取到struts.xml的内容后,是将内容封装进javabean对象然后存放在内存中,以后用户的每次请求处理将使用内存中的数据,而不是每次请求都读取struts.xml文件。
init(FilterConfig filterConfig) throws ServletException {          InitOperations init = new InitOperations();          Dispatcher dispatcher = null;          try {              //包装javax.servlet.FilterConfig对象              FilterHostConfig config = new FilterHostConfig(filterConfig);              //初始化日志              init.initLogging(config);              //创建Dispatcher 包含了2方面的信息:servletcontext,拦截器的配置参数              //同时指定了初始化配置文件的顺序              dispatcher = init.initDispatcher(config);              init.initStaticContentLoader(config, dispatcher);              //PrepareOperations为请求处理做一些准备工作              prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);              //执行器              execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);            //哪些请求是被过滤掉的, 不执行拦截器              this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);              //回调方法              postInit(dispatcher, filterConfig);          } finally {              if (dispatcher != null) {                  dispatcher.cleanUpAfterInit();              }              init.cleanup();          }
  • 2.访问时
    1. 请求经过一系列的过滤器(Filter)
    2. 接着StrutsPrepareAndExecuteFilter的doFilter方法被调用,doFilter中判断是否有对应的ActionMapper的action来决定这个请是否需要调用某个Action 。
    3. 如果有交给execute.executeAction(request, response, mapping);再交给dispatcher.serviceAction(request, response, servletContext, mapping);再交给ActionProxy 此处方法在org.apache.struts2.dispatcher.Dispatcher类中。
    4. ActionProxy通过ConfigurationManager询问框架的配置文件,找到需要调用的Action类 ,这里,我们一般是从struts.xml配置中读取。
    5. ActionProxy创建一个ActionInvocation的实例。
    6. ActionInvocation初始化时,根据配置,加载Action相关的所有Interceptor。
    7. 通过ActionInvocation.invoke方法反射调用Action的实现时,会先执行Interceptor(如:执行默认拦截器栈中定义的18个拦截器)
    8. 执行完action的execute方法后返回结果:ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。
    9. 通过不能的结果进行转发或者重定向等待。过程结束;

2.Struts2的配置详解:

Struts2的xml配置一般都是遵循http://struts.apache.org/dtds/struts-2.0.dtd规定的规则,很多配置文件上都有注明该dtd文件:

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

下面就主要讲解下主要的配置

2.1.配置Bean:

  1. 在struts.xml定义Bean时,通常有以下两个作用:
    1、 创建的Bean实例作为Struts2框架的核心组件使用。
    2、 Bean的静态方法需要一个值注入
  2. 语法规则
    <bean class="com.rlovep.entity.User" ....属性/>
  3. 有如下几个属性:未注明必选的都是可选
    class(必选):表示Bean的类名。
    type:这个属性是个可选属性,它指定了Bean实例实现的Struts2的规范,该规范通常是通过某个接口或者在此前定义过的Bean,因此该属性值通常是个接口或者此前定义过的Bean的name属性值。如果需要将Bean的实例作为Strut2组件使用,则应该指定该属性的值。
    name:表示Bean的实例名,对于有相同type的多个Bean。则它们的name属性不能相同。
    scope:该属性是个可选属性,它指定Bean实例的作用域,该属性的值只能是default、singleton、request、session或thread之一。
    static:该属性是个可选属性,它指定Bean是否使用静态方法注入。通常而言,当指定了type属性时,该属性就不应该指定为true。
    optional:该属性是个可选属性,它指定Bean是否是一个可选Bean。
  4. 使用例子:
<!—-配置自定义的ObjectFactory Bean,名称为myFactory,实现com.opensymphony.xwork2.ObjectFactory 类,实现类com.smp.ObjectFactory -->  <bean name="myFactory"  type="com.opensymphony.xwork2.ObjectFactory" class="com.smp.ObjectFactory" />

2.2.配置常量:

  1. 作用:
    常量说白了就是key-value属性对,作用主要用来作为struts的控制参数。
    有三种配置方式:
    1.在struts.properties文件中配置常量(不建议的方式):方式key-value
struts.i18n.encoding=UTF-8```  2.在struts.xml中配置:推荐用的方式   ```constant标签:配置常量  name:指定的是struts2框架底层提供的default.properties资源文件中配置的"常量"    value:指定的是配置常量的值   在struts.xml文件中,配置的常量的值会覆盖底层提供的default.properties资源文件中配置的常量的值   配置struts2框架的页面中请求连接的后缀名,如果指定多个的话,用","隔开   如:  <!-- 配置文件上传的总大小 -->   <constant name="struts.multipart.maxSize" value="2097152000"></constant>          <div class="se-preview-section-delimiter"></div>

    3.在web.xml中配置:
通过init-param进行配置:

<filter>  .....  <init-param>   <param-name>struts.multipart.maxSize</param-name>  <param-value>2097152000</param-value>  </init-param>  </filter>          <div class="se-preview-section-delimiter"></div>

2.如果在多个文件配置同一个常量,则加载顺序在后面的会覆盖前面配置的常量
Struts2配置文件加载顺序如下:
   default.properties(默认常量配置)
   struts-default.xml(默认配置文件,主要配置bean和拦截器)
   struts-plugin.xml(配置插件)
   struts.xml(配置action或者常量等)
   struts.properties(常量配置)
   web.xml(配置监听器和过滤器等)

2.3.配置include:

  1. 作用:
    include节点是struts2中组件化的方式,可以将每个功能模块独立到一个xml配置文件中,然后用include节点引用
  2. 规则:
    <include file="name.xml"/>

2.4.配置package:

  1. 包作用,管理action。
  2. 规则:<package name="struts2" extends="struts-default">....</package>
  3. 属性说明:
1. name  包的名字; 包名不能重复;  2. extends 当前包继承自哪个包                     在struts中,包一定要继承struts-default                    struts-default在struts-default.xml中定的包   3.abstract  默认为false                    表示当前包为抽象包; 抽象包中不能有action的定义,否则运行时期报错                   abstract=true  只有当当前的包被其他包继承时候才用!                   如:                      <package name="basePackage" extends="struts-default" abstract="true"></package>                      <package name="user" extends="basePackage">  4.namespace   名称空间,默认为"/"                          作为路径的一部分                         访问路径=  http://localhost:8080/项目/名称空间/ActionName

4.名称搜搜机制:

1、获得请求路径的URI,例如url是:        /struts2Demo/hello_a/a/b/helloWorld.action  2、首先查询namespace为/hello_a/a/b的package,        如果存在这个package,则在这个package中查询名字为helloWorld的        action,如果不存在这个package则转步骤3  3、查询namespace为/hello_a/a的package,        如果存在这个package,则在这个package中寻找名字为helloWorld的        action,如果不存在这个package,则转步骤4  4、查询namespace为/hello_a的package,        如果存在这个package,则在这个package中寻找名字为helloWorld的        action,如果仍然不存在这个package,则转步骤5  5、查询默认的namaspace的package        查询名字为helloWorld的action(默认的命名空间为空字符串“/” )        如果还是找不到,页面提示404找不到action的异常。

2.5.配置action:

  1. 作用:
    用于找到Action实际类,配置请求路径与Action类的映射关系
  2. 规则:<action name="login" class="com.rlovep.action.UserAction" method="login"> 。。。</action>
  3. 属性说明:
1. name  请求路径名称,  假如name=ActionName  则访问路径=  http://localhost:8080/项目/名称空间/ActionName。  2. class 请求处理的aciton类的全名  默认值为:com.opensymphony.xwork2.ActionSupport,该类中有默认的execute方法返回success;  3. method 请求处理方法 默认为execute方法; 当配置该属性后将执行对应的方法 该方法必须为public型且返回值为字符串不能有参数

4.路径不对的action配置:
如果配置的路径找不到Action,那么404异常。配置默认的Action处理找不到的Action匹配异常

<default-action-ref name="helloworld"></default-action-ref>  ##配置默认的action,使用默认的ActionSupport类。返回为success;

2.6.配置result:

  1. 作用:
    配置根据方法返回结果对应的动作类型
  2. 规则:<result name="success">/success.jsp</result>
  3. 属性说明:
1.name  action处理方法返回值,   2.type  跳转的结果类型,默认包中有10种类型。默认为转发:dispatcher               <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>               <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>              <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>              <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>              <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>              <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>              <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>              <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>              <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>              <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />    3.标签体中指定跳转的页面  4. 可以指定全局的result:只要是返回success的action都会跳转到success.jsp  <global-results>              <result name="success">/success.jsp</result>   </global-results>

2.7自定义后缀名:

Struts2中的核心控制器,该Filter主要的任务是拦截用户/*的所有请求。如果请求的路径中带后缀为.action或没有带后缀,此时将请求交给Struts2框架处理。否则不做任何处理。例如:请求路径为/index.jsp直接访问页面
那么怎么使用我们常见的do,go等后缀名了?
解决办法:修改常量struts.action.extension的值:

 <struts>           <!-- 修改default.prroperties中的后缀名 -->           <constant name="struts.action.extension" value="do,go"></constant>          ......     </struts>

2.8.整体演示如下:

##package,action,result演示:  <struts>            <!-- 继承自默认包,名字为user -->      <package name="user" extends="struts-default" namespace="/user">             <!-- 配置action,使用方法login -->           <action name="login" class="com.rlovep.action.UserAction" method="login">               <!-- 配置结果为默认的转发 -->              <result name="login">/index.jsp</result>           </action>             <!-- 配置action,使用方法login -->           <action name="login1" class="com.rlovep.action.Maction" method="login">               <!-- 配置结果为默认的转发 -->              <result name="login">/index.jsp</result>           </action>      </package>  </struts>  ##include演示:  <!-- 总配置文件中引入其他所有的配置文件 -->    <include file="com/rlovep/action/login.xml"></include>

3.访问Servlet API

通过使用ActionContext可以访问Servlet API,可以访问request,session,application ,Jsp对像的所有域对象Map:
通过getXX方法获得map对象,有了map对象就可以对域对象进行操作了;演示如下:(lServletActionContext.getRequest();获取请求)

//用ActionContext访问Servlet API          //此方法返回一个ActionContext,该类有put和get方法,相当于request的setAttribute和getAttribute方法          ActionContext context = ActionContext.getContext();          context.put("name1", "peace_request");          //当然也可以获得与request对象相对应的域对象的map          Map<String, Object> request = context.getContextMap();          request.put("name4", "peace_request1");          //该方法获得与application对象相对应的域对象的map          Map<String, Object> application = context.getApplication();          application.put("name2", "peace_application");          //该方法获得与session对象相对应的域对象的map          Map<String, Object> session = context.getSession();          session.put("name3", "peace_session");

在jsp中获得存入的域对象的值:

<!-- 获得对应域的属性值 -->       ${requestScope.name1 }<br>       ${requestScope.name4 }<br>       ${sessionScope.name3  }<br>       ${applicationScope.name2 }<br>

4.常量详解附录:

<struts>       <!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 -->       <constant name="struts.i18n.encoding" value="UTF-8" />         <!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。 如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->       <constant name="struts.action.extension" value="do" />         <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->       <constant name="struts.serve.static.browserCache" value="false" />         <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->       <constant name="struts.configuration.xml.reload" value="true" />         <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->       <constant name="struts.devMode" value="true" />         <!-- 默认的视图主题 -->       <constant name="struts.ui.theme" value="simple" />         <!-- spring 托管 -->       <constant name="struts.objectFactory" value="spring" />         <!-- 指定加载struts2配置文件管理器,默认为org.apache.struts2.config.DefaultConfiguration 开发者可以自定义配置文件管理器,该类要实现Configuration接口,可以自动加载struts2配置文件。 -->       <constant name="struts.configuration" value="org.apache.struts2.config.DefaultConfiguration" />         <!-- 设置默认的locale和字符编码 -->       <constant name="struts.locale" value="zh_CN" />       <constant name="struts.i18n.encoding" value="GBK" />         <!-- 指定Struts的工厂类 -->       <constant name="struts.objectFactory" value="spring"></constant>         <!-- 指定spring框架的装配模式,装配方式有: name, type, auto, and constructor (name 是默认装配模式) -->       <constant name="struts.objectFactory.spring.autoWire" value="name" />         <!-- 该属性指定整合spring时,是否对bean进行缓存,值为true or false,默认为true -->       <cosntant name="struts.objectFactory.spring.useClassCache" />         <!-- 指定类型检查,包含tiger和notiger -->       <cosntant name="struts.objectTypeDeterminer" value="tiger" />         <!-- 该属性指定处理 MIME-type multipart/form-data,文件上传 -->       <constant name="struts.multipart.parser" value="cos" />       <constant name="struts.multipart.parser" value="pell" />       <constant name="struts.multipart.parser" value="jakarta" />         <!-- 指定上传文件时的临时目录,默认使用 javax.servlet.context.tempdir -->       <constant name="struts.multipart.saveDir" value="/tmpuploadfiles" />         <!-- 该属性指定Struts 2文件上传中整个请求内容允许的最大字节数 -->       <constant name="struts.multipart.maxSize" value="2097152" />         <!-- 该属性指定Struts2应用加载用户自定义的属性文件,该自定义属性文件指定的属性不会覆盖 struts.properties文件中指定的属性。如果需要加载多个自定义属性文件,多个自定义属性文 件的文件名以英文逗号(,)隔开。(也就是说不要改写struts.properties!) -->       <constant name="struts.custom.properties" value="application,org/apache/struts2/extension/custom" />         <!-- 指定请求url与action映射器,默认为org.apache.struts2.dispatcher.mapper.DefaultActionMapper -->       <constant name="struts.mapper.class" value="org.apache.struts2.dispatcher.mapper.DefaultActionMapper" />         <!-- 指定action的后缀,默认为action -->       <constant name="struts.action.extension" value="do" />         <!-- 被 FilterDispatcher使用指定浏览器是否缓存静态内容,测试阶段设置为false,发布阶段设置为true. -->       <constant name="struts.serve.static.browserCache" value="true" />         <!-- 设置是否支持动态方法调用,true为支持,false不支持. -->       <constant name="struts.enable.DynamicMethodInvocation" value="true" />         <!-- 设置是否可以在action中使用斜线,默认为false不可以,想使用需设置为true. -->       <constant name="struts.enable.SlashesInActionNames" value="true" />         <!-- 是否允许使用表达式语法,默认为true. -->       <constant name="struts.tag.altSyntax" value="true" />         <!-- 设置当struts.xml文件改动时,是否重新加载 -->       <cosntant name="struts.configuration.xml.reload" value="true" />         <!-- 设置struts是否为开发模式,默认为false,测试阶段一般设为true. -->       <cosntant name="struts.devMode" value="true" />         <!-- 设置是否每次请求,都重新加载资源文件,默认值为false. -->       <cosntant name="struts.i18n.reload" value="false" />         <!-- 标准的UI主题,默认的UI主题为xhtml,可以为simple,xhtml或ajax -->       <cosntant name="struts.ui.theme" value="xhtml" />         <!-- 模板目录 -->       <cosntant name="struts.ui.templateDir" value="template" />         <!-- 设置模板类型. 可以为 ftl, vm, or jsp -->       <cosntant name="struts.ui.templateSuffix" value="ftl" />         <!-- 定位velocity.properties 文件. 默认velocity.properties -->       <cosntant name="struts.velocity.configfile" value="velocity.properties" />         <!-- 设置velocity的context. -->       <cosntant name="struts.velocity.contexts" value="...." />         <!-- 定位toolbox -->       <cosntant name="struts.velocity.toolboxlocation" value="...." />         <!-- 指定web应用的端口 -->       <cosntant name="struts.url.http.port" value="80" />         <!-- 指定加密端口 -->       <cosntant name="struts.url.https.port" value="443" />         <!-- 设置生成url时,是否包含参数.值可以为: none,get or all -->       <cosntant name="struts.url.includeParams" value="get" />         <!-- 设置要加载的国际化资源文件,以逗号分隔. -->       <cosntant name="struts.custom.i18n.resources" value="application" />         <!-- 对于一些web应用服务器不能处理HttpServletRequest.getParameterMap(), 像 WebLogic,Orion, and OC4J等,须设置成true,默认为false. -->       <cosntant name="struts.dispatcher.parametersWorkaround" value="false" />         <!-- 指定freemarker管理器 -->       <cosntant name="struts.freemarker.manager.classname" value="org.apache.struts2.views.freemarker.FreemarkerManager" />         <!-- 设置是否对freemarker的模板设置缓存,效果相当于把template拷贝到 WEB_APP/templates. -->       <cosntant name="struts.freemarker.templatesCache" value="false" />       <!-- 通常不需要修改此属性. -->       <cosntant name="struts.freemarker.wrapper.altMap" value="true" />       <!-- 指定xslt result是否使用样式表缓存.开发阶段设为true,发布阶段设为false. -->       <cosntant name="struts.xslt.nocache" value="false" />         <!-- 设置struts自动加载的文件列表. -->       <cosntant name="struts.configuration.files" value="struts-default.xml,struts-plugin.xml,struts.xml" />         <!-- 设定是否一直在最后一个slash之前的任何位置选定namespace. -->       <cosntant name="struts.mapper.alwaysSelectFullNamespace" value="false" />   </struts>

好的本章介绍到这里
来自伊豚wpeace(rlovep.com)