struts2工作原理

来源:互联网 发布:真实的推油经历知乎 编辑:程序博客网 时间:2024/05/19 05:01

写了几篇struts2相关的博文了,似乎还没有介绍它的原理。

用两张图片就可以很清楚的看出来了:

struts2执行顺序:
用户请求web资源时,会被拦截器拦截,经过一系列拦截器后再由Action处理,Action调用service,service调用dao处理业务(dao里面的实体,也就是entity是由实体类提供的),dao处理完业务之后将结果返回给service,service将结果再给Action,然后又会经过拦截器处理(此时经过的拦截器与前面经过的拦截器顺序相反),然后将结果显示在页面上给用户看。


代码示例:

testAction.java:

package com.web.action;import com.opensymphony.xwork2.ActionSupport;public class TestAction extends ActionSupport {    public String test(){        return SUCCESS;    }}

TestSequenceInterceptor.java

package com.web.interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;//测试拦截器的工作顺序/* * 关于struts2拦截器的工作顺序: * 当用户请求web资源时,会注册拦截器。以本拦截器作为示例讲解: * 当本拦截器在struts.xml中被多次调用时,如: *      <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">1</param>        </interceptor-ref>        <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">2</param>        </interceptor-ref>        <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">3</param>        </interceptor-ref> * 此时,拦截器执行“1”时,执行到String result=arg0.invoke();语句,拦截器会发现后面还有需要执行的拦截器,所以 * 至此不会执行System.out.println("拦截器"+sign+"执行完毕");而会截止执行拦截器“2”,然后执行到拦截器“2”的 * String result=arg0.invoke();语句时,拦截器会判断后面还有没有拦截器需要执行,如果有,继续;如果没有了,就可以 * 逐一执行每个拦截器中String result=arg0.invoke();后面的语句,但是执行String result=arg0.invoke(); * 后面的语句顺序刚好和执行String result=arg0.invoke();前面的语句相反,也就是说,会先执行拦截器“2”的 * System.out.println("拦截器"+sign+"执行完毕");,再执行拦截器“1”的System.out.println("拦截器"+sign+"执行完毕"); * */@SuppressWarnings("serial")public class TestSequenceInterceptor extends AbstractInterceptor {// 定义一份变量作为拦截器的编号private int sign;public int getSign() {return sign;}public void setSign(int sign) {this.sign = sign;}public String intercept(ActionInvocation arg0) throws Exception {System.out.println("拦截器" + sign + "正在工作");String result = arg0.invoke();System.out.println("拦截器" + sign + "执行完毕");return result;}}

struts.xml:

<struts>    <constant name="struts.devMode" value="true"></constant>    <!-- 配置包元素 -->    <package name="default" extends="struts-default" namespace="/">      <interceptors>        <interceptor name="TestSequenceInterceptor" class="com.web.interceptor.TestSequenceInterceptor"></interceptor>      </interceptors>      <action name="TestAction" class="com.web.action.TestAction">        <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">1</param>        </interceptor-ref>        <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">2</param>        </interceptor-ref>        <interceptor-ref name="TestSequenceInterceptor">          <param name="sign">3</param>        </interceptor-ref>        <result name="success">/success.jsp</result>      </action>    </package></struts>