自定义拦截器

使用自定义拦截器,用来验证Session中存放的当前用户信息是否存在:

  1. 如果Session存在,可以访问对应Action类中的方法 
  2. 如果Session不存在,跳转到指定目录

 在struts.xml配置自定义拦截器

登录验证拦截器LoginInteceptor

import cn.itcast.ssh.domain.Employee;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;


/**
 * 登录验证拦截器
 *
 */
@SuppressWarnings("serial")
public class LoginInteceptor implements Interceptor {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	/**每次访问Action类之前,先执行intercept方法*/
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		//获取当前访问Action的URL
		String actionName = invocation.getProxy().getActionName();
		//如果当前访问Action的URL是"loginAction_login"表示此时还没有Sesion,需要放行
		if(!"loginAction_login".equals(actionName)){
			//从Session中获取当前用户对象
			Employee employee = SessionContext.get();
			//如果Session不存在,跳转到登录页面
			if(employee==null){
				return "login";
			}
		}
		//放行,访问Action类中方法
		return invocation.invoke();
		
	}

}

 

import org.apache.struts2.ServletActionContext;

import cn.itcast.ssh.domain.Employee;

public class SessionContext {

	public static final String GLOBLE_USER_SESSION = "globle_user";
	
	public static void setUser(Employee user){
		if(user!=null){//设置session
			ServletActionContext.getRequest().getSession().setAttribute(GLOBLE_USER_SESSION, user);
		}else{ //重新登录时清空session
			ServletActionContext.getRequest().getSession().removeAttribute(GLOBLE_USER_SESSION);
		}
	}
	
	/**获取session*/
	public static Employee get(){
		return (Employee) ServletActionContext.getRequest().getSession().getAttribute(GLOBLE_USER_SESSION);
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值