配置struts2默認的攔截器

    首先struts2攔截器的類,要繼承AbstractInterceptor類。java

package com.huaat.weibo.interceptor;

import org.apache.log4j.Logger;

import com.huaat.common.utils.web.Struts2Utils;
import com.huaat.weibo.vo.UserInfo;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 攔截器
 * @author  jing.yue
 * @version 2012/07/17 1.0.0
 */
public class UserInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -5653729083843893528L;

	// log4j日誌
	private static final Logger logger = Logger.getLogger(UserInterceptor.class);

	@Override
	public void init() {
		// TODO Auto-generated method stub
		logger.debug("init UserInterceptor...");
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		// TODO Auto-generated method stub

        UserInfo userInfo = (UserInfo) Struts2Utils.getSession().getAttribute("user");
        //沒有登陸, 則跳轉到登陸頁面
        if(userInfo == null) {
        	return "login";
        }

		return actionInvocation.invoke();
	}

}

   struts2的xml的配置以下:web

<package name="weibo" extends="struts-default">

		<interceptors>
			<!-- 先定義攔截器 -->
	        <interceptor name="userInterceptor" class="com.huaat.weibo.interceptor.UserInterceptor">
	        	<!-- 指定系統初始化給攔截器的參數
	            <param name="hello">你好</param> -->
	        </interceptor>

	        <!-- 加到本身設置的攔截器棧裏邊去 -->
	        <interceptor-stack name="userStack">
	        	<interceptor-ref name="userInterceptor"></interceptor-ref>
	            <interceptor-ref name="defaultStack"></interceptor-ref>
	       </interceptor-stack>
		</interceptors>

	    <!-- 改變系統默認的攔截器,改爲本身的默認攔截器,而且一個系統只能有一個默認的攔截器,這樣這個攔截器棧會默認應用到全部的Action上去 -->
	    <default-interceptor-ref name="userStack"></default-interceptor-ref>

		<global-results>
	     	 <result name="error">/error.jsp</result>
			   <result name="login">/jsp/weibo/login.jsp</result>
     	</global-results>
		<!-- 具體包配置 -->
      	<global-exception-mappings>
         	 <exception-mapping exception="java.lang.Exception" result="error"/>
     	</global-exception-mappings>


</package>

若是須要使用攔截器,則package的extends屬性要繼承攔截器的package。apache

下面是使用這個攔截器的struts2的xml文件:app

<struts>
	<package name="awardcondition" extends="weibo" namespace="/">
			<action name="awardConditionInfo" class="awardConditionInfoAction">
			   <result name="success">/list.jsp</result>
			</action>
	</package>
</struts>

一旦在某個包下定義了默認攔截器棧,在該包下的全部 action 都會使用此攔截器棧。對於那些不想使用些攔截器棧的 action ,則應該將它放置在其它的包下。 

這樣攔截器就能夠使用了!jsp

相關文章
相關標籤/搜索