配置struts2默认的拦截器

    首先struts2拦截器的类,要继承AbstractInterceptor类。

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的配置如下:

<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。

下面是使用这个拦截器的struts2的xml文件:

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

一旦在某个包下定义了默认拦截器栈,在该包下的所有 action 都会使用此拦截器栈。对于那些不想使用些拦截器栈的 action ,则应该将它放置在其它的包下。 

这样拦截器就可以使用了!

你可能感兴趣的:(struts2拦截器,struts2)