Struts2入門(二)——配置攔截器

一、前言

之前便了解過,Struts 2的核心控制器是一個Filter過濾器,負責攔截所有的用戶請求,當用戶請求發送過來時,會去檢測struts.xml是否存在這個action,如果存在,服務器便會自動幫我們跳轉到指定的處理類中去處理用戶的請求,基本流程如下:

該流程筆者理解是基本流程,。如果有不對的地方,請下方留言。我會改正。謝謝;

好,接著往下講:

注意:在struts.xml中,配置文件必須有該請求的處理類才能正常跳轉,同時,返回SUCCESS字符串的類,必須繼承ActionSupport,如果你沒有繼承,那么就返回"success",同樣能夠跳轉到jsp邏輯視圖,但是必須確保你struts.xml有<result name="success">xx.jsp</result>,該標簽,具體操作在上一篇文章有介紹過簡單例子。

1.1、了解攔截器

什么是攔截器,它的作用是什么?

攔截器,實際上就是對調用方法的改進。

作用:動態攔截對Action對象的調用,它提供了一種機制可以使開發者可以定義在一個action執行的前后執行的代碼,也可以在一個action執行前阻止其執行。同時也是提供了一種可以提取action中可重用的部分的方式。

攔截器的執行順序:

在執行Action的execute方法之前,Struts2會首先執行在struts.xml中引用的攔截器,在執行完所有引用的攔截器的intercept方法后,會執行Action的execute方法。?

二、實際操作

2.1、自定義攔截器

新建一個類繼承AbstractInterceptor。

package com.Interceptor;import java.util.Date;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class MyInterceptor extends AbstractInterceptor {private String name;//該屬性與struts.xml中的<param name="name">簡單攔截器</param>一致,也就是說該name的值是簡單攔截器public void setName(String name) {this.name = name;}//攔截action請求
    @Overridepublic String intercept(ActionInvocation arg0) throws Exception {//取得被攔截的actionLoginAction action = (LoginAction)arg0.getAction();System.out.println(name+":攔截器的動作------"+"開始執行登錄action的時間為:"+new Date());long start = System.currentTimeMillis();/** ActionInvocation.invoke()就是通知struts2接著干下面的事情* 比如 調用下一個攔截器 或 執行下一個Action* 就等于退出了你自己編寫的這個interceptor了* 在這里是去調用action的execute方法,也就是繼續執行Struts2 接下來的方法*/String result = arg0.invoke(); System.out.println(name+":攔截器的動作------"+"執行完登錄action的時間為:"+new Date());long end = System.currentTimeMillis();System.out.println(name+":攔截器的動作------"+"執行完該action的時間為:"+(end-start)+"毫秒");System.out.println(result);    //輸出的值是:successreturn result;}
}
/*** 該頁面的效果如下:* 簡單攔截器:攔截器的動作------開始執行登錄action的時間為:Mon Oct 24 19:06:17 CST 2016用戶名:admin,密碼:123簡單攔截器:攔截器的動作------執行完登錄action的時間為:Mon Oct 24 19:06:18 CST 2016簡單攔截器:攔截器的動作------執行完該action的時間為:1130毫秒success* */

?

在struts.xml中配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN""http://struts.apache.org/dtds/struts-2.5.dtd">
<struts><!--簡單的攔截器  --><package name="Interceptor" extends="struts-default" namespace="/ac"><!-- 跳轉前攔截 --><interceptors><!-- 聲明簡單的過濾器 --><interceptor name="Inter" class="com.Interceptor.MyInterceptor"><!--傳遞name的參數  --><param name="name">簡單攔截器</param></interceptor></interceptors><action name="loginaction" class="com.Interceptor.LoginAction"><result name="success">/Interceptor/welcome.jsp</result><result name="input">/Interceptor/error.jsp</result><!--注意:如果不加默認的攔截器的話,那么類型轉換不會執行,也就是說不會把文本上的值賦值給實體類  --><interceptor-ref name="defaultStack"/><!-- 簡單的過濾器,定義在這里告訴攔截器在此處action執行 --><interceptor-ref name="Inter"></interceptor-ref></action></package>
</struts>    

struts.xml解析:

<interceptors>:表示聲明攔截器

<interceptor>: 表示定義一個攔截器

<param>:給該攔截器一個參數,屬性為name

<interceptor-ref name="">:表示該攔截器在這個action中使用。

?

新建LoginAction類,繼承ActionSupport

package com.Interceptor;import com.opensymphony.xwork2.ActionSupport;//action類處理
public class LoginAction extends ActionSupport {private String username;private String pwd;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}//默認執行execute方法public String execute(){System.out.println("用戶名:"+username+",密碼:"+pwd);return SUCCESS;}

?

新建jsp視圖界面

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>    
<!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>簡單的登錄攔截</title>
</head>
<body><!--如果在struts.xml中,package包中有配置namespace的話,那么在此處就應該配置。不然會報404錯誤  --><s:form action="loginaction" namespace="/ac"> <s:textfield label="User Name" name="username"/><s:password label="Password" name="pwd" /><s:submit/></s:form>  
</body>
</html>

(代碼筆者測試沒問題)

?

2.2、過濾方法:

攔截器不僅可以定義多個攔截,還可以指定攔截特定的方法。

struts.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN""http://struts.apache.org/dtds/struts-2.5.dtd">
<struts><!--簡單的攔截器  --><package name="Interceptor" extends="struts-default" namespace="/ac"><!-- 跳轉前攔截 --><interceptors><!-- 聲明方法過濾器 -->    <interceptor name="myMethod" class="com.Interceptor.MyMethodInterceptor"><param name="name">方法過濾攔截器</param></interceptor></interceptors><action name="loginaction" class="com.Interceptor.LoginAction" method="method1"> <!-- 如果是攔截方法的話,改為method="method2" --><result name="success">/Interceptor/welcome.jsp</result>   <!-- /Interceptor是筆者文件夾。別弄錯了--><result name="input">/Interceptor/error.jsp</result><!--注意:如果不加默認的攔截器的話,那么類型轉換不會執行,也就是說不會把文本上的值賦值給實體類  --><interceptor-ref name="defaultStack"/><!-- 方法過濾器 --><interceptor-ref name="myMethod"><param name="name">改名后的方法過濾器</param><param name="includeMethods">method1,method3</param>  <!--表示該方法不被攔截--><param name="excludeMethods">method2</param>           <!--表示該方法被攔截  --></interceptor-ref></action></package>
</struts>    

?

修改LoginAction類

package com.Interceptor;import com.opensymphony.xwork2.ActionSupport;//action類處理
public class LoginAction extends ActionSupport {private String username;private String pwd;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}
//    過濾的方法public String method1() throws Exception {  System.out.println("Action執行方法:method1()");  return SUCCESS;  }  public String method2() throws Exception {  System.out.println("Action執行方法:method2()");  return SUCCESS;  }  public String method3() throws Exception {  System.out.println("Action執行方法:method3()");  return SUCCESS;  }  }

?

新建MyMethodInterceptor類繼承MethodFilterInterceptor

MethodFilterInterceptor類表示你定義的攔截器支持方法過濾。

package com.Interceptor;import java.util.Date;import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;//過濾方法
public class MyMethodInterceptor extends MethodFilterInterceptor {private String name;public void setName(String name) {this.name = name;}@Overrideprotected String doIntercept(ActionInvocation arg0) throws Exception {//取得被攔截的actionLoginAction action = (LoginAction)arg0.getAction();System.out.println(name+":攔截器的動作------"+"開始執行登錄action的時間為:"+new Date());long start = System.currentTimeMillis();String result = arg0.invoke(); System.out.println(name+":攔截器的動作------"+"執行完登錄action的時間為:"+new Date());long end = System.currentTimeMillis();System.out.println(name+":攔截器的動作------"+"執行完該action的時間為:"+(end-start)+"毫秒");System.out.println(result);    //輸出的值是:successreturn result;}}

至于jsp視圖,一樣,不需要改變。

得到的結果可以看出來:

當method="method1"或者是method="method3"的時候,會自動去執行MyMethodInterceptor 的方法doIntercept,然后跳轉到welcome.jsp界面。

當method="method2"的時候,控制臺會出現?Action執行方法:method2(),之后便被攔截了。

以上就是攔截方法的基本代碼,例子很簡單,但是重在理解。

可能筆者疑惑,為什么需要過濾方法呢?因為攔截器它會自動攔截所有的方法,回造成資源的損耗,所以有些方法我們可以指定不被攔截。

?

2.3、監聽過濾器:

在攔截器中,execute方法執行之前或者之后的方法都被攔截在intercept方法中,這些的結構不夠明白,我們可以定義監聽,雖然好像沒什么用,但是了解一下也挺不錯的。

實現攔截器的監聽結果必須實現PreResultListener接口。

?

package com.Interceptor;import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;//過攔截器配置一個監聽器
public class MyPreResultListener implements PreResultListener {//定義處理Result之前的行為
    @Overridepublic void beforeResult(ActionInvocation arg0, String arg1) {System.out.println("返回的邏輯視圖為:"+arg1);}
}

?

然后MyMethodInterceptor類修改為:

package com.Interceptor;import java.util.Date;import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;//過濾方法
public class MyMethodInterceptor extends MethodFilterInterceptor {private String name;public void setName(String name) {this.name = name;}@Overrideprotected String doIntercept(ActionInvocation arg0) throws Exception {//將一個攔截結果的監聽器注冊給攔截器arg0.addPreResultListener(new MyPreResultListener());System.out.println("execute方法被調用之前的攔截");//調用下一個攔截器或者action的執行方法String result = arg0.invoke();System.out.println("execute方法被調用之后的攔截");return result;}}

?

以上就是攔截器基本知識,如果有錯誤的地方,請指正。謝謝。

轉載于:https://www.cnblogs.com/IT-1994/p/5997079.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/457081.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/457081.shtml
英文地址,請注明出處:http://en.pswp.cn/news/457081.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

linux固態機械分區嗎,不再疑惑!實測數據后才知道固態硬盤究竟要不要分區

不再疑惑&#xff01;實測數據后才知道固態硬盤究竟要不要分區2019-12-10 20:52:00162點贊594收藏177評論前幾年的固態硬盤價格昂貴&#xff0c;一般用戶會選擇128G或256G的固態作為系統盤&#xff0c;由于單盤空間不大&#xff0c;一般都會配合機械硬盤使用&#xff0c;無需考…

關于無法加載已創建的布局文件的問題的解決方案以及已布局在對應的R文件中未生成相應ID的問題的解決

先來說下創建后的Layout布局文件在對應的R文件中不能生成相應的ID問題&#xff0c;一般情況下之所以出現這種問題是應為自己的res文件中有錯誤的文件&#xff1a;對應的是錯誤的文件格式名稱&#xff0c;以及錯誤的文件內容等。博主就遇到過為drawable文件起了一個非法的名稱&a…

安卓手機的后門控制工具SPADE

SPADE&#xff0c;一款安卓手機的后門控制工具&#xff0c;安全研究人員可以以此了解和研究安卓后門原理。 首先&#xff0c;我們從網站www.apk4fun.com下載apk文件&#xff0c;如ccleaner。然后&#xff0c;我們安裝spade git clone https://github.com/suraj-root/spade.git …

Day12-date time

import datetimedatetime比time高級了不少&#xff0c;可以理解為datetime基于time進行了封裝&#xff0c;提供了&#xff0c; 更為實用的函數&#xff0c;并且datetime模塊的接口更直觀更容易調用模塊中的類&#xff1a; datetime 同時又時間和日期 imedelta 主…

MySQL案例-open too many files,MyISAM與partition

-------------------------------------------------------------------------------------------------短文---------------------------------------------------------------------------------------------------------------長話短說~現象: error log中批量刷錯誤日志, 形…

關于異常:HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection的解決辦法

<span style"font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style"font-size:18px;">今天在寫一個app時&#xff0c;當實現從網絡上獲取圖片資源&#xff0c;發送HTTPURLConnection的時候拋出這樣…

linux網卡有很多error,教你設置win7系統虛擬機安裝linux提示network error的解決方法...

很多朋友在使用電腦的過程中&#xff0c;會發現win7系統虛擬機安裝linux提示network error的現象&#xff0c;當遇到win7系統虛擬機安裝linux提示network error的問題&#xff0c;我們要怎么解決呢&#xff1f;如今還有很多用戶不知道如何處理win7系統虛擬機安裝linux提示netwo…

codevs2171 棋盤覆蓋

題目描述 Description給出一張n*n(n<100)的國際象棋棋盤&#xff0c;其中被刪除了一些點&#xff0c;問可以使用多少1*2的多米諾骨牌進行掩蓋。 輸入描述 Input Description第一行為n&#xff0c;m&#xff08;表示有m個刪除的格子&#xff09;第二行到m1行為x,y&#xff0c…

Day13-日歷模塊

import calendar日歷模塊 #使用#返回制定歿年某月日歷 print(calendar.month(2019,3)) #返回指定年份的日歷 print(calendar.calendar(2019)) #判斷閏年返回True 或者Flase print(calendar.isleap(2000)) #返回某個月的weekd的第一天和這個月所有的天數 print(calendar.monthra…

關于eclipse項目紅色感嘆號的解決辦法

在網上找到了解決辦法&#xff0c;詳見&#xff1a;http://jingyan.baidu.com/article/ea24bc3986f7b0da62b33188.html

linux模擬網絡延遲,使用Nistnet搭建網絡延遲模擬設備 (network delay simulator)

mknod /dev/hitbox c 62 0mknod /dev/nistnet c 62 1chown root /dev/hitboxchown root /dev/nistnetmknod /dev/mungebox c 63 0chown root /dev/mungeboxmknod /dev/spybox c 64 0chown root /dev/spyboxmodprobe nistnet可以將這個放到/etc/rc.local中&#xff0c;以便重啟后…

MyBatis - MyBatis Generator 生成的example 如何使用 and or 簡單混合查詢

簡單介紹&#xff1a; Criteria&#xff0c;包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關系。oredCriteria&#xff0c;Example內有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預示的一樣&#xff0c;這個集合中的Cri…

將本地Blog部署到GitHub上,有自己的博客頁面!

前言 上一篇文章我們已經把本地的hexo環境搭建好了&#xff0c;并且在本地成功預覽&#xff0c;但是本地預覽也意味著自己的博文只能自己看的到&#xff0c;其他人根本看不到&#xff0c;這篇文章將接上文說一說如何把本地Blog部署到GitHub上&#xff0c;好讓小伙伴可以來訪問我…

Linux下安裝配置JDK

本人使用的VM虛擬機&#xff0c;在VM上安裝了Linux&#xff0c;版本是CentOS-6.7-i386-bin-DVD1.iso。 一、下載JDK 在進入JDK官網&#xff0c;找到要下載的JDK版本&#xff0c;將下載地址復制下來&#xff0c;放到迅雷中下載&#xff0c;我下載的是&#xff1a;http://downloa…

新手使用GitHub客戶端提交項目的步驟

1.下載https://windows.github.com/ github客戶端 2.安裝完github&#xff0c;會出現 點擊GitHub&#xff0c;Git Shell是命令行指令&#xff0c;暫時用不上 3.點擊進入之后 輸入你在https://github.com上面注冊的用戶名和密碼點擊log in 4.登錄之后新建項目 點擊左上角…

linux的命令uname n,Linux下uname命令及其選項

Linux下uname命令及其選項2017-03-15 23:22:26曉得了Linux系統的用戶信息后&#xff0c;你也可能想曉得所登錄的系統信息&#xff0c;今日就紹介獲取系統本身信息的命令uname,這搭u應當是UNIX的縮寫&#xff0c;操作如次&#xff1a;uname使役uname還可以得到其它相關系統的信息…

火狐瀏覽器Firefox如何使用插件,火狐有哪些好用的插件

1 CoorPreviews 不打開網頁鏈接預覽該網頁的內容。 預覽如圖所示&#xff1a; 點擊關閉旁邊的釘子可以讓該窗口保持開著并且瀏覽速度加快。這對于快速瀏覽圖片時非常有用。 2 FoxTab 3D方式預覽網頁&#xff0c;只要按一下輸入框左側按鈕即可。 此外還提供多種預覽模式和其…

GitHub+Hexo搭建自己的Blog之-主題配置

前言 前兩章我們已經把Blog的環境全部搭建完畢了&#xff0c;但是還沒有內容&#xff0c;而且hexo默認的主題是不是感覺挺丑的&#xff0c;其實hexo給我們提供了很多主題模板&#xff0c;總有一款是你喜歡的&#xff0c;本篇文章將繼續說一說如何配置主題&#xff0c;怎么創建博…

開源app之MyHearts

前言 這個月&#xff0c;說實話&#xff0c;有忙有閑&#xff0c;經歷了一次病痛的洗禮&#xff0c;才認識到了只有好好的生活&#xff0c;認真的對待自己的身體&#xff0c;才能更好的去工作&#xff0c;沒有了身體的支撐&#xff0c;什么工作都只能是紙老虎&#xff0c;不攻自…