struts2

package元素

屬性:

name:必須的,配置文件中要唯一.

extends:指定父包.會(huì)把父包中的配置內(nèi)容繼承下來(lái).一般需要直接或間接的繼承一個(gè)叫做"struts-default"的包(在struts-default.xml配置文件中),如果不繼承,那么struts2的核心功能將無(wú)法使用

abstract:是否是抽象包.沒(méi)有任何action子元素的package可以生命為抽象包

namespace:指定名稱空間.一般以"/"開(kāi)頭,該包中的動(dòng)作訪問(wèn)路徑:namespace+動(dòng)作名稱.如果namespace="",這是默認(rèn)名稱空間,和不寫(xiě)該屬性是一樣的

屏幕快照 2017-01-17 12.51.17.png

action元素

作用:定義一個(gè)動(dòng)作

屬性:

name:必須的,動(dòng)作名稱,用戶用戶發(fā)起請(qǐng)求,在包中要唯一

class:指定動(dòng)作類的全名,框架會(huì)通過(guò)反射機(jī)制實(shí)例化,默認(rèn)是:com.opensymphony.xwork2.ActionSupport.

method:指定動(dòng)作類中的動(dòng)作方法.框架會(huì)執(zhí)行該方法,默認(rèn)是execute();

關(guān)于默認(rèn)類:是在struts-default.xml中進(jìn)行了聲明

動(dòng)作類

1嗅辣、編寫(xiě)動(dòng)作類的三種方式:

  • POJO(Plain Old Java Object)普通的JavaBean
public Hello{
  public String sayHello(){
    return "success";
  }
}
  • 實(shí)現(xiàn)com.opensymphony.xwork2.Action接口
public Hello implements Action{
  public String sayHello(){
    return SUCCESS;
  }
}

Action接口中的常量:

String SUCCESS:success赏表。一切正常侵浸。

String NONE:none佩研。動(dòng)作方法執(zhí)行后复罐,不轉(zhuǎn)向任何的結(jié)果視圖政供。或者在動(dòng)作方法中返回null椒振。

String ERROR:error昭伸。動(dòng)作方法執(zhí)行時(shí)遇到異常,轉(zhuǎn)向錯(cuò)誤提示頁(yè)面澎迎。

String INPUT:input庐杨。驗(yàn)證、轉(zhuǎn)換失敗嗡善,轉(zhuǎn)向輸入頁(yè)面辑莫。

String LOGIN:login。檢測(cè)用戶是否登錄罩引,沒(méi)有登錄轉(zhuǎn)向此視圖。

  • 繼承com.opensymphony.xwork2.ActionSupport(推薦)

意義:提供了一些基本的功能枝笨。比如驗(yàn)證和國(guó)際化消息提示等袁铐。

public Hello extends ActionSupport{
}

Struts2的配置

配置文件和加載順序

default.properties struts-core-**.jar org.apache.struts包中

struts-default.xml struts-core-**.jar 包中

struts-plugin.xml 插件中

struts.xml 構(gòu)建路徑的頂端

struts.properties 構(gòu)建路徑的頂端

web.xml;

在動(dòng)作中訪問(wèn)ServeletAPI

通過(guò)ServletActionContext靜態(tài)方法

ServletContext servletContext = ServletActionContext.getServletContext();
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

Struts2提供的結(jié)果類型

  • dispatcher:轉(zhuǎn)發(fā)到一個(gè)jsp
  • redirect:用于重定向到另外一個(gè)jsp頁(yè)面
  • redirectAction:用于重定向到另外一個(gè)動(dòng)作
  • chain:用戶轉(zhuǎn)發(fā)到另外一個(gè)動(dòng)作
  • stream:用于文件下載

自定義結(jié)果類型

  • 定義一個(gè)類繼承StrutsResultSupport
public class CaptachaResult extends StrutsResultSupport{
    
    //輸出你的結(jié)果即可
    protected void doExecute(String finalLocation, ActionInvocation invocation)
            throws Exception {
        
    }

}
  • 在package中定義結(jié)果類型
    • result-type 中 name:指定結(jié)果類型的名字,class:指定的結(jié)果類型包名
<package name="p3" extends="struts-default">
        <result-types>
            <!-- 結(jié)果類型定義 -->
            <result-type name="captcha" class="com.itheima.results.CaptachaResult"></result-type>
        </result-types>
        <action name="captcha">
            <result name="success" type="captcha">
                <param name="width">200</param>
            </result>
        </action>
    </package>

封裝參數(shù)

方式一:動(dòng)作類當(dāng)做模型對(duì)象

login.jsp

<body>
    <form action="${pageContext.request.contextPath}/regist.action" method="post">
        用戶名:<input type="text" name="username"/><br/>
        密碼:<input type="password" name="password"/><br/>
        <input type="submit" value="登錄"/>
    </form>
  </body>

struts.xml

<package name="p1" extends="struts-default">
        <action name="regist" class="com.itheima.action.UserAction" method="regist">
            <result>/success.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </package>

動(dòng)作類UserAction

//封裝參數(shù):方式一:動(dòng)作類當(dāng)做模型對(duì)象
public class UserAction extends ActionSupport {
    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }
    //框架會(huì)按照表單的name值,調(diào)用對(duì)應(yīng)的setter屬性
    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String regist(){
        System.out.println(username+":"+password);
        if("wzhting".equals(username)&&"sorry".equals(password))
            return SUCCESS;
        else
            return LOGIN;
    }
}

方式二:動(dòng)作和模型分開(kāi)

動(dòng)作:

public class PersonAction extends ActionSupport {
    private Person person = new Person();

    public Person getPerson() {
        System.out.println("getter");
        return person;
    }

    public void setPerson(Person person) {
        System.out.println("setter");
        this.person = person;
    }
    public String regist(){
        System.out.println(person);
        if("wzhting".equals(person.getUsername())&&"sorry".equals(person.getPassword()))
            return SUCCESS;
        else
            return LOGIN;
    }
}

模型:

//屬性和form中的字段名一致
public class Person implements Serializable {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "Person [username=" + username + ", password=" + password + "]";
    }
    
}

配置文件:

<package name="p2" extends="struts-default" namespace="/person">
        <action name="regist" class="com.itheima.action.PersonAction" method="regist">
            <result>/success.jsp</result>
            <result name="login">/login1.jsp</result>
        </action>
    </package>

jsp

<body>
    <form action="${pageContext.request.contextPath}/person/regist.action" method="post">
        用戶名:<input type="text" name="person.username"/><br/>
        密碼:<input type="password" name="person.password"/><br/>
        <input type="submit" value="登錄"/>
    </form>
  </body>

方式三:實(shí)現(xiàn)ModelDriver

public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
    //必須實(shí)例化
    private Customer customer = new Customer();

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public String regist(){
        System.out.println(customer);
        if("wzhting".equals(customer.getUsername())&&"sorry".equals(customer.getPassword()))
            return SUCCESS;
        else
            return LOGIN;
    }
    //此方法會(huì)在動(dòng)作方法執(zhí)行前先執(zhí)行横浑;得到當(dāng)前對(duì)應(yīng)的模型對(duì)象并把模型對(duì)象壓入值棧的棧頂剔桨。setUsername先調(diào)用棧頂對(duì)象的該方法。
    //后面會(huì)有值棧(存放數(shù)據(jù)的大倉(cāng)庫(kù))的詳細(xì)介紹
    public Customer getModel() {
        return customer;
    }
}

Customer類略

配置文件:

<package name="p3" extends="struts-default" namespace="/customer">
        <action name="regist" class="com.itheima.action.CustomerAction" method="regist">
            <result>/success.jsp</result>
            <result name="login">/login2.jsp</result>
        </action>
    </package>

jsp視圖:

<body>
    <form action="${pageContext.request.contextPath}/customer/regist.action" method="post">
        用戶名:<input type="text" name="username"/><br/>
        密碼:<input type="password" name="password"/><br/>
        <input type="submit" value="登錄"/>
    </form>
  </body>

OGNL表達(dá)式

注意事項(xiàng):必須要寫(xiě)在struts2的標(biāo)簽中

  • 支持對(duì)象方法調(diào)用:

    <!--s:property相當(dāng)于c:out-->
    <s:property value="'abcdefg'.length()">
    
  • 支持靜態(tài)的方法調(diào)用和值訪問(wèn)

    <!--訪問(wèn)靜態(tài)變量-->
    <s:property value="@java.lang.Integer@MAX_VALUE" />
    <!--訪問(wèn)靜態(tài)方法 配置參數(shù) <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>-->
    <s:property value="@java.lang.Math@abs(-100)" />
    
  • 訪問(wèn)OGNL上下文(OGNL context)和ActionContext;
  • 操作集合對(duì)象
context上下文

application:ServletContext中的所有屬性attributes

  • 相當(dāng)于EL的內(nèi)置對(duì)象applicationScope

session:HttpSession中的所有屬性attributes

  • 相當(dāng)于EL內(nèi)置對(duì)象sessionScope

value statck(根):是一個(gè)List

action:動(dòng)作類

request:ServletRequest中的所有屬性

  • 相當(dāng)于EL的內(nèi)置對(duì)象requestScope

parameters:Map map = request.getParameterMap()

  • 相當(dāng)于EL內(nèi)置對(duì)象param Values

attr :從四大域范圍中搜索

  • ${}

動(dòng)作類的生命周期:每次訪問(wèn)都會(huì)重新創(chuàng)建心的動(dòng)作類的實(shí)例.還會(huì)創(chuàng)建ActionContext和ValueStack實(shí)例.ActionContext和ValueStack一直保持在你的線程中(ThreadLocal)

獲取ActionContext的實(shí)例:

ActionContext ac = ActionContext.getContext();

往ContextMap存數(shù)據(jù)
//向contextMap中存入數(shù)據(jù)
context.put("contextMap","hello contextMap");

//向HttpSession域范圍內(nèi)存入數(shù)據(jù)
//第一種方式:使用contextMap的session
Map<String,Object> sessionAttributes = context.getSession();
sessionAttributes.put("sessionMap","hello sessionMap");
//方式二:使用原始方式
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("sessionMap1","hello sessionMap1");

//向ServletContext域中存放數(shù)據(jù)
//第一種方式,使用contextMap中的application(它也是一個(gè)Map)
Map<String,Object> applicationAttributes = context.getApplication();
applicationAttributes.put("applicationMap","hello applicationMap");
//第二種方式,使用原始方式
ServletContext application = ServletActionContext.getServletContext();
application.setAttribute("applicationMap1","hello applicationMap1");

往ContextMap存數(shù)據(jù)取數(shù)據(jù)
<s:property value="#contextMap" />

<s:property value="#session.sessionMap" />
<s:property value="#session.sessionMap1" />

<s:property value="#application.applicationMap" />
<s:property value="#application.applicationMap1" />

獲取ValueStack的實(shí)例:

方式一:

ActionContext ac = ActionContext.getContext();
ValueStack vs = ac.getValueStack();

方式二:

MaP<String,Object> requestAttributes = (MaP<String,Object>)ac,get("request");
ValueStack vs = requestAttributes.get("struts.valueStack");

方式三:

ActionContext ac = ActionContext.getContext();
ac.get(ValueStack.VALUE_STACK);

ValueStack

ValueStack實(shí)際上就是一個(gè)容器,每次前段頁(yè)面發(fā)送一個(gè)請(qǐng)求時(shí),就會(huì)將請(qǐng)求的數(shù)據(jù)進(jìn)行封裝,并入ValueStack的棧頂,發(fā)送一次請(qǐng)求開(kāi)始,struts會(huì)為每一個(gè)action創(chuàng)建一個(gè)ValueStack

ValueStack是一個(gè)接口,我們使用OgnlValueStack,貫穿action的整個(gè)生命周期

ValueStack組成部分

root區(qū)域:本質(zhì)上就是一個(gè)ArrayList

context區(qū)域:本質(zhì)上就是一個(gè)map

往root中存放數(shù)據(jù)
valueStacke.set("","");此方法是操作根的

檢測(cè)棧頂是不是一個(gè)Map,如果不是,創(chuàng)建一個(gè)Map,Map中的數(shù)據(jù)就是p1=pp1,再把這個(gè)Map壓入棧頂

ValueStack vs = ActionContext.getContext().getValueStack();
vs.set("p1","pp1");

vs.put(Object obj);//放入一個(gè)對(duì)象

ValueStack vs = ActionContext.getContext().getValueStack();
vs.put(new User("name","age"));

第一個(gè)參數(shù)是ONGL表達(dá)式,從棧頂開(kāi)始搜索,調(diào)用setName("luoluo");

ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("name","luoluo");

向contextMap中存放數(shù)據(jù),相當(dāng)于ActionContext.getContext().put("abc","shit1");

ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#abc","shit1");

參數(shù)是OGNL表達(dá)式,取數(shù)據(jù)

ValueStack vs = ActionContext.getContext().getValueStack();
Object obj1 = vs.findValue("name");
ValueStack的其他方法
setValue方法
vs.setValue("name","張三");//就是把根中第一個(gè)name屬性,設(shè)置為張三;

vs.setValue("#name","李四");//就是向contextMap中放數(shù)據(jù)

操作集合對(duì)象

List:

<s:radio name="gender" list="{'男','女'}" />

Map:

<s:radio name="gender1" list="#{'1':'男':'0':'女'}">

iterator:

<s:iterator value="students" var="s" status="vs">
    <s:property value="#s.name" />${s.name}---${s.age}
    <s:property value="#vs.index" />
</s:iterator>

OGNL中的特殊符號(hào)使用

"#"作用:

  • 獲取contextMap中的數(shù)據(jù)
  • 構(gòu)建map集合

"%"作用:

  • 如果想把一個(gè)普通的字符串強(qiáng)制看成時(shí)OGNL

    //因?yàn)?#'顯示OGNL表達(dá)式的內(nèi)容只能通過(guò)<s:property >來(lái)顯示,其他的struts標(biāo)簽不管用,所以需要'%'
    
    <s:textfield value="%{name}" />
    

"$":

作用:在配置文件中使用,表示一個(gè)占位符

struts2常用標(biāo)簽

set標(biāo)簽:

value存入map中屬性的值,是一個(gè)OGNL表達(dá)式

var存入map中屬性的key

scope:存入的范圍有application,session,request,page和action

如果不寫(xiě),默認(rèn)是action,它是在contextMap中和request范圍內(nèi)各存一份

<!--在contextMap中不會(huì)有個(gè)名稱叫str,值是abc的,因?yàn)閍bc是一個(gè)ognl表達(dá)式,在棧頂元素查找沒(méi)有abc對(duì)應(yīng)的值,再去contextMap中查找也米有,所以就不會(huì)存入任何內(nèi)容-->
<s:set value="abc" var="str" scope="session" />
<!--把a(bǔ)bc看成方式一個(gè)字符串,這個(gè)時(shí)候在session的Map中可以找到-->
<s:set value="'abc'" var="str" scope="session" />
<s:set value="'def'" var="str2" />

<s:property value="#session.str" />
<s:property value="#str2" />

攔截器

攔截器和filter的區(qū)別:

攔截器只攔截action(方法),filter過(guò)濾任何請(qǐng)求

struts執(zhí)行流程

請(qǐng)求—>StrutsPrepareAndExecuteFilter—>執(zhí)行doFilter方法(判斷請(qǐng)求的是action還是其他資源,是action繼續(xù)往內(nèi)部核心走,不是的話就直接放行)

請(qǐng)求到達(dá)內(nèi)部核心—>生成action的代理對(duì)象—>action執(zhí)行類(執(zhí)行一組攔截器)—>執(zhí)行action中的指定的方法(查看是否有返回值,若有返回值到某個(gè)指定資源上,若沒(méi)有方法執(zhí)行完成)—>逆序執(zhí)行一組攔截器—>StrutsPrepareAndExecuteFilter(放行之后的代碼)—>生成響應(yīng)信息,返回用戶頁(yè)面上

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末徙融,一起剝皮案震驚了整個(gè)濱河市洒缀,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖树绩,帶你破解...
    沈念sama閱讀 217,907評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件萨脑,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡饺饭,警方通過(guò)查閱死者的電腦和手機(jī)渤早,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)瘫俊,“玉大人鹊杖,你說(shuō)我怎么就攤上這事】秆浚” “怎么了骂蓖?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,298評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)川尖。 經(jīng)常有香客問(wèn)我涯竟,道長(zhǎng),這世上最難降的妖魔是什么空厌? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,586評(píng)論 1 293
  • 正文 為了忘掉前任庐船,我火速辦了婚禮,結(jié)果婚禮上嘲更,老公的妹妹穿的比我還像新娘筐钟。我一直安慰自己,他們只是感情好赋朦,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布篓冲。 她就那樣靜靜地躺著,像睡著了一般宠哄。 火紅的嫁衣襯著肌膚如雪壹将。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,488評(píng)論 1 302
  • 那天毛嫉,我揣著相機(jī)與錄音诽俯,去河邊找鬼。 笑死承粤,一個(gè)胖子當(dāng)著我的面吹牛暴区,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播辛臊,決...
    沈念sama閱讀 40,275評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼仙粱,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了彻舰?” 一聲冷哼從身側(cè)響起伐割,我...
    開(kāi)封第一講書(shū)人閱讀 39,176評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤候味,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后隔心,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體白群,經(jīng)...
    沈念sama閱讀 45,619評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評(píng)論 3 336
  • 正文 我和宋清朗相戀三年济炎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了川抡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡须尚,死狀恐怖崖堤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情耐床,我是刑警寧澤密幔,帶...
    沈念sama閱讀 35,655評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站撩轰,受9級(jí)特大地震影響胯甩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜堪嫂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評(píng)論 3 329
  • 文/蒙蒙 一偎箫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧皆串,春花似錦淹办、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,871評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至谤牡,卻和暖如春副硅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背翅萤。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,994評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工恐疲, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人断序。 一個(gè)月前我還...
    沈念sama閱讀 48,095評(píng)論 3 370
  • 正文 我出身青樓流纹,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親违诗。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容