struts2 拦截器

truts2 拦截器.
某些操作需要用户登录后才能执行。

 

java 代码:

 

import java.util.Map;

import com.iss.beans.UserBean;
import com.iss.common.util.Constants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * struts2 拦截器.
 * 某些操作需要用户登录后才能执行。
 * @author lj
 *
 */

public class AuthenticationInterceptor implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1113623727670044215L;

	public void destroy() {
	}

	public void init() {
	}

	/**
	 * 拦截器的拦截方法
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		
		/** 从session中获取登录的用户信息 
		 * 登录用户的信息在用户登录时绑定在session中。
		 */
		UserBean user = (UserBean)session.get(Constants.USER_KEY);
		
		if (null == user){
			/**
			 * 如果用户信息为空,说明未登录。
			 * 跳转到登录页面。
			 */
			return Action.LOGIN;
		}else{
			/**
			 * 如果已经登录,则执行下一步操作.
			 */
			return invocation.invoke();
		}
	}

}

 


注:在登录时(login.action),不要引用此拦截器,不然无法登录。

 

 

struts.xml

 

<package name="default" namespace="/" extends="struts-default">
		<interceptors>
        	<interceptor name="session" 
        			class="com.iss.common.interceptor.AuthenticationInterceptor"/>
    	</interceptors>
		<action name="getUsersPage" class="getUsersPage" 
					method="getUsersPage">
		   
		   <!-- 此action需要调用session拦截器 -->
		   <interceptor-ref name="session"/>
		   
	       <result name="success">/WEB-INF/pages/users/userlist.jsp</result>
	       <result name="error">/WEB-INF/pages/error.jsp</result>
	       <result name="login">index.jsp</result>
	    </action>
	    
	    <!-- 退出 -->
	    <action name="logout" class="logout" method="logout">
	    	
	    	<!-- 此action需要调用session拦截器 -->
	    	<interceptor-ref name="session"/>
	    	
	    	<result name="login">/index.jsp</result>
	    </action>
	    
    </package>
 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值