一簡單例子
先做一個最簡單的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)客戶端在瀏覽器中輸入一個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。
三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裏面就是要做以上事情。
文章來源:http://www.cnblogs.com/doco/articles/2226369.html