---
title: "用Struts拦截器实现登陆限制"
author: "小色帝"
date: "2016-07-08T09:45:57Z"
tags: []
categories: ["企业架构"]
slug: "struts"
draft: false
lastmod: "2016-07-08T09:45:57Z"
id: 2309984
url: "https://wangdingxin.iteye.com/blog/2309984"
---

拦截器从字面意思来看就是限制，限制用户访问某些网页。在Action提出请求之前用拦截器来做权限设置，让符合的用户跳入相应的界面中。最近做的一个商城项目中就用到了自定义的拦截器，实现了一个简单的session判断，成功就登陆，不成功就跳转到门户。

 

【拦截器工作原理】

Struts2拦截器是在访问某个Action或Action的某个方法，字段之前或之后实施拦截，并且Struts2拦截器是可插拔的，拦截器是AOP的一种实现。AOP为Aspect Oriented Programming的缩写，意为：面向切面编程，通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离，从而使得业务逻辑各部分之间的耦合度降低，提高程序的可重用性，同时提高了开发的效率。

我的理解是每一个action请求都会在拦截器的内部，当发生请求的时候，Struts会找对应的配置文件，实例化相应的拦截器对象，如设置拦截器属性excludeMethods。很类似于过滤器的，但是过滤器的范围要大于拦截器。

【创建拦截器】

　　第一种方法就是直接实现Interceptor接口，这样的话，有个弊端，这里面的init() destroy() intercept() 方法都需要实现了。
 
　　第二种方法是继承自AbstractInterceptor抽象类，实现了Interceptor接口，并且对里面的init()和destroy()方法进行空实现，而把intercept()方法设置为抽象方法，让继承它的子类去实现，这样的话，子类只要实现这个intercept()方法就可以了，比上面的简单。

　　第三种方法是继承自MethodFilterInterceptor（我下面就是用这个方法实现的），这个类叫做方法过滤拦截器，MethodFilterInterceptor继承自AbstractInterceptor，并且提供了一种机制，即可以指定对Action中某些方法进行拦截或者是不拦截，所谓拦截不拦截，指的就是拦截器中的intercept()方法是否被执行了，若没有执行，就是没有拦截，若执行了，就是拦截了。

　　总的来说，相比之前的接口和抽象类，最后一个只需要指定对Action中某些方法进行拦截是最简单的。是通过includeMethods和excludeMethods这两个参数来设置那个方法需要拦截的，在Struts.xml中进行配置。

 

【拦截器实现登陆】

1＞首先我们要自定义一个拦截器类：

package com.lyq.action.interceptor;

import java.util.Map;

import com.lyq.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
 * 消费者登录拦截器
 * @author Li Yongqiang
 *
 */
public class CustomerLoginInteceptor extends AbstractInterceptor{
	private static final long serialVersionUID = 1L;
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext context = invocation.getInvocationContext();// 获取ActionContext
		Map<String, Object> session = context.getSession();// 获取Map类型的session
		if(session.get("customer") != null){// 判断用户是否登录 
			return invocation.invoke();// 调用执行方法
		}
		return BaseAction.CUSTOMER_LOGIN;// 返回登录
	}
}




2＞然后在配置文件中去注册这个拦截器，并在后台登陆的action中利用excludeMethods这个成员变量来绑定login这个方法被拦截。(structs-front.xml 哪个方法需要拦截，就在哪儿引用拦截器)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC 
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" 
	"http://struts.apache.org/dtds/struts-2.1.dtd" >
<struts>
	<!-- 前台登录 -->
	<package name="shop.front" extends="shop-default">
		<!-- 配置拦截器 -->
		<interceptors>
			<interceptor name="loginInterceptor" class="com.lyq.action.interceptor.CustomerLoginInteceptor"/>
			<interceptor-stack name="customerDefaultStack">
				<interceptor-ref name="loginInterceptor"/>
    			<interceptor-ref name="defaultStack"/>
			</interceptor-stack>
		</interceptors>
		<action name="index" class="indexAction">
            <result>/WEB-INF/pages/index.jsp</result>
        </action>
	</package>
	<!-- 消费者Action -->
	<package name="shop.customer" extends="shop-default" namespace="/customer">
		<action name="customer_*" method="{1}" class="customerAction">
		<result name="input">/WEB-INF/pages/user/customer_reg.jsp</result>
		</action>
	</package>
	<!-- 商品Action -->
	<package name="shop.product" extends="shop-default" namespace="/product">
		<action name="product_*" class="productAction" method="{1}">
			<result name="list">/WEB-INF/pages/product/product_list.jsp</result>
			<result name="select">/WEB-INF/pages/product/product_select.jsp</result>
			<result name="clickList">/WEB-INF/pages/product/product_click_list.jsp</result>
			<result name="findList">/WEB-INF/pages/product/product_find_list.jsp</result>
		</action>
	</package>
	<!-- 购物车Action 这里配置了定义的拦截器 -->
	<package name="shop.cart" extends="shop.front" namespace="/product">
		<action name="cart_*" class="cartAction" method="{1}">
			<result name="list">/WEB-INF/pages/cart/cart_list.jsp</result>
			<interceptor-ref name="customerDefaultStack"/>
		</action>
	</package>
	<!-- 订单Action  这里配置了定义的拦截器-->
	<package name="shop.order" extends="shop.front" namespace="/product">
		<action name="order_*" class="orderAction" method="{1}">
			<result name="add">/WEB-INF/pages/order/order_add.jsp</result>
			<result name="confirm">/WEB-INF/pages/order/order_confirm.jsp</result>
			<result name="list">/WEB-INF/pages/order/order_list.jsp</result>
			<result name="error">/WEB-INF/pages/order/order_error.jsp</result>
			<interceptor-ref name="customerDefaultStack"/>
		</action>
	</package>
</struts>


3＞然后是在login 这个方法被调用的时候，就去验证session是不是空的，来判断是否有这个用户名和密码的匹配，然后放入了session中。

package com.lyq.action.user;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lyq.action.BaseAction;
import com.lyq.model.user.Customer;
import com.lyq.util.AppException;
import com.opensymphony.xwork2.ModelDriven;
/**
 * 顾客Action
 * @author Li Yongqiang
 */
@Scope("prototype")
@Controller("customerAction")
public class CustomerAction extends BaseAction implements ModelDriven<Customer>{
	private static final long serialVersionUID = 1L;
	public String login() throws Exception{
		return CUSTOMER_LOGIN;
	}
	/**
	 * 用户注册
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception{
		boolean unique = customerDao.isUnique(customer.getUsername());//判断用户名是否可用
		if(unique){//如果用户名可用
			customerDao.save(customer);//保存注册信息
			return CUSTOMER_LOGIN;//返回会员登录页面
		}else{
			throw new AppException("此用户名不可用");//否则返回页面错误信息
		}
	}
	/**
	 * 用户登录 
	 * @return
	 * @throws Exception
	 */
	public String logon() throws Exception{
		//验证用户名和密码是否正确
		Customer loginCustomer = customerDao.login(customer.getUsername(), customer.getPassword());
		if(loginCustomer != null){//如果通过验证
			session.put("customer", loginCustomer);//将登录会员信息保存在Session中
		}else{//验证失败
			addFieldError("", "用户名或密码不正确！");//返回错误信息
			return CUSTOMER_LOGIN;//返回会员登录页面
		}
		return INDEX;//返回网站首页
	}
	/**
	 * 用户退出
	 * @return String
	 * @throws Exception
	 */
	public String logout() throws Exception{
		if(session != null && session.size() > 0){
			session.clear();
		}
		return INDEX;
	}
	// 管理员
	private Customer customer = new Customer();
	// 确认密码
	private String repassword;
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	@Override
	public Customer getModel() {
		return customer;
	}
}