struts2攔截器

  • 攔截器

攔截器在AOP中用於在某個方法和字段被訪問之前進行攔截,然後在之前或者之後加入某些操作,攔截是AOP的一種實現策略。

  • AOP簡介

AOP(Aspect Oriented programming,面向切面編程)可以說是對OOP(Object, Oriented Programming,面向對象程序設計)的補充和完善。

在面向對象編程中,對象封裝的是對象的行爲和屬性。AOP技術利用一種稱爲“橫切”的技術,刨開封裝的對象內部,並將那些影響對個類的公共行爲封裝到一個可重用模塊,並將其命名爲切面(Aspect)。

  • 攔截的實現原理

AOP通過攔截來實現關注點織入(Weaving),並且能夠自動將橫切關注點織入到面向對象的軟件系統中,從而實現橫切關注點的模塊化

  • 攔截的意義

通過攔截器形成攔截器模塊,極大地提高了系統開發的靈活性和複用性,AOP使用代理的方式,將多個攔截器和核心業務邏輯組合在一起,滿足用戶不同的需求。

攔截器的特點是可插拔的。

1.模塊化橫切關注點,使系統代碼冗餘量小

2.系統容易擴展

3.代碼重用行。AOP將每個切面實現爲獨立模塊,模塊之間的是鬆耦合的。

  • Struts2攔截器

Struts2的攔截器是動態攔截Action調用的對象。它提供了一種機制,使開發者可以定義一個特定的功能模塊,這個模塊可以在Action執行之前或者之後運行,也可以在一個Action執行之前阻止Action執行,同時也提供了一種可以提取Action中可重用部分的方式。

通常情況下,攔截器都是通過代理(ActionProxy)的方式調用。當請求到達Struts2的ServletDispatcher時,Struts2會查找配置文件,並且根據配置實例化相應的攔截器對象,然後將這些對象組成一個列表(List),最後卓哥調用列表中的攔截器。

          攔截器配置

<!-- 定義攔截器 -->
        <interceptors>
            <!-- 定義攔截器    name攔截器的名字,class攔截器對應的類  -->
            <interceptor name="annotationInterceptor"
                class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor" />
            <!-- 應以攔截器棧 -->
            <interceptor-stack name="annotationStack">
                <interceptor-ref name="defaultStack">
                <!-- 配置參數(可以配置也可以不配置)   excludeMethod爲參數名, default爲參數值 -->
                    <param name="excludeMethod">default</param>
                </interceptor-ref>
                <interceptor-ref name="annotationInterceptor" />
            </interceptor-stack>
        </interceptors>
        <action name="annotationAction" class="action.AnnotationAction">
            <result name="success">/index.jsp</result>
            <!-- 引用攔截器       name可以使攔截器的名字,也可以是攔截器棧的名字 -->
            <interceptor-ref name="annotationStack"></interceptor-ref>
        </action>


  • 使用攔截器註解

Struts2有三個攔截器註解類型

1.before

該方法將在Action的處理之前被調用。如果該標註方法有返回值並且不爲null,那麼這個返回值將作爲Action的結果代碼

2.After

該方法在Action的處理方法執行之後被調用

3.BeforeResult

該方法在Action的處理方法執行之後,result執行之前調用

並且其在struts.xml還要進行如下配置

<interceptors>

			<interceptor name="annotationInterceptor" 
				class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
			<interceptor-stack name="annotationStack">
				<interceptor-ref name="defaultStack"/>
				<interceptor-ref name="annotationInterceptor"/>
			</interceptor-stack>
			
		</interceptors>

  • 自定義一個攔截器器類

在定義一個攔截器時,該類將實現Interceptor接口或者繼承抽象攔截器類AbstractInterceptor。


1.Interceptor接口

init(),在攔截器執行之前調用,初始化系統資源

destroy(),在攔截器執行之後銷燬資源,在攔截器被垃圾回收之前調用

intercept()攔截器的核心方法,實現具體的攔截器操作,返回一個字符串作爲邏輯視圖。

注:如果需要調用其他的Action或者攔截器,只需要在Interceptor()方法中調用invocation.invoke()方法,表示繼續執行其他操作。如果不需要則返回一個字符串如SUCCESS.

2.AbstractInterceptor類

提供Interceptor接口的空實現。因爲並不是每次實現攔截器時都需要申請和銷燬資源,所以在抽象看節氣類AbstratInterceptor中,對init()和destory()方法已經進行了空實現,這樣就只需要實現Interceptor()方法


  • 攔截器實例

1.創建register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<!-- saved from url=(0021)http://www.itzcn.com/ -->
<HTML>
<HEAD><TITLE>免費看視頻教程,輕鬆學習計算機技術!-窗內網 - 視頻教程</TITLE>
<LINK href="pay.css" type=text/css rel=stylesheet>
</HEAD>
<body style="text-align: center;">
<center>
<jsp:include page="index.html"></jsp:include>
	<div style="margin-left:50px;text-align: left;">
	<strong>註冊</strong>
	

	<s:form action="reg" method="post">
		<s:textfield name="userName" label="註冊姓名" maxLength="30" cssStyle="width:194px;"></s:textfield>
		<s:password name="userPassword" label="註冊密碼" maxLength="30" cssStyle="width:194px;"> </s:password>
		<s:textarea name="userInfo" label="個人說明" cols="30" rows="3"></s:textarea>
		<s:submit value="提交"></s:submit>
	</s:form>
		</div>
			</center>
			</BODY>
		</HTML>



2.RegisterAction.java


package action;

import com.opensymphony.xwork2.ActionSupport;


public class RegisterAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 9124103366421816974L;

	private String userName;
	private String userPassword;
	private String userInfo;
	
	
	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getUserPassword() {
		return userPassword;
	}


	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}


	public String getUserInfo() {
		return userInfo;
	}


	public void setUserInfo(String userInfo) {
		this.userInfo = userInfo;
	}


	public String execute(){
		return SUCCESS;
	}	

}


3.myRegister.jsp

<%@ page language="java"  pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<jsp:include page="index.html"></jsp:include>
 <%! String trans(String chi){
		String result = null;
		byte[] temp;
		try{
			temp = chi.getBytes("utf-8");
			result = new String(temp);
		}catch(Exception e){}
		return result;
}
 %>

<strong>我的註冊信息</strong><br>
	註冊姓名:<s:property value="userName"/><br>
	註冊密碼:<s:property value="userPassword"/><br>
	個人說明:<s:property value="userInfo"/>
<br/><br/>

4.RegisterInterceptor.java

package Interceptor;

import action.RegisterAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class RegisterInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4968747288453947207L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		//獲取Action實例
		Object object = invocation.getAction();
		
		if (object != null) {
			if ( object instanceof RegisterAction) {
				RegisterAction action = (RegisterAction) object;
				// 取得用戶提交的評論內容
				String userInfo = action.getUserInfo();
				if (userInfo.contains("壞")) { // 如果判斷評論內容有需要過濾的文字
					userInfo = userInfo.replaceAll("壞", "*");
					// 以*替換爲要過濾的內容
					action.setUserInfo(userInfo); // 把替換後的內容設置爲評論內容
				}
				return invocation.invoke();
			}
			return Action.LOGIN;
		}
		return Action.LOGIN;
	}

}

5.struts.xml配置

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.i18n.encoding" value="utf-8" />
	<package name="default" extends="struts-default">
		<!-- 定義攔截器 -->
		<interceptors>	
			<interceptor name="replace" class="Interceptor.RegisterInterceptor" />
		</interceptors>

		<action name="reg" class="action.RegisterAction">
			<result name="success">/myRegister.jsp</result>
			<result name="login">/register.jsp</result>
			<interceptor-ref name="replace"></interceptor-ref>
		</action>

	</package>
</struts>

















































































發佈了85 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章