1. 程式人生 > >從例項看struts2執行原理

從例項看struts2執行原理

1.1         簡單例子
先做一個最簡單的struts2的例子:在瀏覽器中請求一個action,然後返回一個字串到jsp頁面上顯示出來。

第一步:把struts2最低配置的jar包加入的專案中。
         commons-logging-1.0.4.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar
    struts2-core-2.0.11.jar
    xwork-2.0.4.jar

第二步:在web.xml中加入攔截器配置。
         <filter>
        <filter-name>struts2</filter-name>


 <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

第三步:把空的struts.xml配置檔案放到專案src下面。
         <struts>

</struts>


第四部:編寫自定義的action類。
package test;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
    private String str;
    public String hello() {
       this.str = "hello!!!";
       return "success";
    }
    public String getStr() {
       return str;
    }
    public void setStr(String str) {

       this.str = str;
    }
}

第五步:編寫struts.xml配置檔案。
<struts>
    <package name="test" namespace="/np" extends="struts-default">
       <action name="hello" class="test.HelloAction" method="hello">
           <result name="success">/hello.jsp</result>
       </action>
    </package>
</struts>

第六步:編寫hello.jsp檔案。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
</head>
<body>
    <h1><s:property value="str"/></h1>
</body>
</html>

第七步:啟動tomcat,在瀏覽器中訪問:
http://localhost:8080/hello/np/hello.action
         hello 是專案名字
         np 名稱空間,對應namespace裡面的字串。
         hello.action 其中hello對應action裡面的字串,“.action”表示請求的是一個action。

1.2         執行機制
1)客戶端在瀏覽器中輸入一個url地址。
2)這個url請求通過http協議傳送給tomcat。
3)tomcat根據url找到對應專案裡面的web.xml檔案。
4)在web.xml裡面會發現有struts2的配置。
5)然後會找到struts2對應的struts.xml配置檔案。
6)根據url解析struts.xml配置檔案就會找到對應的class。
7)呼叫完class返回一個字String,根據struts.xml返回到對應的jsp。

1.3         struts2流程

上圖來源於Struts2官方站點,是Struts 2 的整體結構。
一個請求在Struts2框架中的處理大概分為以下幾個步驟:
1)  客戶端初始化一個指向Servlet容器(例如Tomcat)的請求。
2)  這個請求經過一系列的過濾器(Filter)。
3)  接著FilterDispatcher被呼叫,FilterDispatcher詢問ActionMapper來決定這個請是否需要呼叫某個Action。
4)  如果ActionMapper決定需要呼叫某個Action,FilterDispatcher把請求的處理交給ActionProxy。
5)  ActionProxy通過Configuration Manager詢問框架的配置檔案,找到需要呼叫的Action類。
6)  ActionProxy建立一個ActionInvocation的例項。
7)  ActionInvocation例項使用命名模式來呼叫,在呼叫Action的過程前後,涉及到相關攔截器(Intercepter)的呼叫。
8)  一旦Action執行完畢,ActionInvocation負責根據struts.xml中的配置找到對應的返回結果。
Struts2的核心就是攔截器。Struts.xml中所有的package都要extends="struts-default"。同理與所有的Java類都要extends自Object一樣。struts-default.xml裡面就是要做以上事情。