WEB项目用户登陆拦截器

这个拦截器的主要目的是在用户执行以写操作之前需要用户已经登陆
但是拦截器需要对注册 登陆两个方法放行
也就是在配置文件中有这么一个配置

<interceptor-ref name="privilegeInterceptor">
	<param name="excludeMethods">login,regist</param>
</interceptor-ref>

拦截器类

package cn.crm.web.interceptor;


import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import cn.crm.domain.User;

/**
 * @author Administrator
 * 方法过滤拦截器
 */
public class PrivilegeInterceptor extends MethodFilterInterceptor {

	@Override
	//不校验登陆和注册方法
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		//1 获得Session
			Map<String, Object> session = ActionContext.getContext().getSession();
		//2 获得登陆标识
			User user = (User) session.get("user");
		//3 判断标识是否存在
			if(user != null){
				//存在=> 放行
				return invocation.invoke();
			}else{
				//不存在=> 重定向到登陆页面
				return "toLogin";
			}
			
	}

}

struts2.xml中拦截器配置部分

        <interceptors>
			<!-- 注册拦截器 -->
			<interceptor name="privilegeInterceptor" class="cn.itcast.web.interceptor.PrivilegeInterceptor">
			</interceptor>
				
			<!-- 配置拦截器栈 -->
			<interceptor-stack name="myStack">
				<interceptor-ref name="privilegeInterceptor">
					<param name="excludeMethods">login,regist</param>
				</interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
			<!-- 指定默认拦截器栈 -->
			<default-interceptor-ref name="myStack"></default-interceptor-ref>
		
			<!-- 全局结果集配置 -->
			<global-results>
				<result name="toLogin" type="redirect" >/login.jsp</result>
			</global-results>
			<global-exception-mappings>
				<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
			</global-exception-mappings>

要注意给注册 登陆的Action配置结果
也可以如上使用全局的配置 toLogin这样包下所有action都可以使用

猜你喜欢

转载自blog.csdn.net/qq_41009846/article/details/82915186