天天看点

spring前置AOP拦截action

<!-- 实现BEFORE通知 配置 -->

   <bean id="autoProxyCreator"

   class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>

<bean id="checkCustomerBefore" class="com.egt.struts.action.CheckCustomerAction"></bean>

<bean id="checkCustomerBeforeAdvisor"

   class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

   <property name="advice">

    <ref bean="checkCustomerBefore" />

   </property>

   <property name="patterns">

   <value>.*.execute</value>

   </property>

</bean>

CheckCustomerAction 方法

package com.egt.struts.action;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import org.apache.log4j.Priority;

import org.apache.struts.action.ActionMapping;

import org.springframework.aop.MethodBeforeAdvice;

import com.egt.repository.Customer;

public class CheckCustomerAction implements MethodBeforeAdvice {

private Logger logger = Logger.getLogger(this.getClass().getName());

public void before(Method method, Object[] args, Object target)

    throws Throwable {

   System.out.println("test1");

   logger.log(Priority.INFO, "customer权限控制拦截...");

   System.out.println("test2");

   HttpServletRequest request = (HttpServletRequest) args[2];

   HttpServletResponse response = (HttpServletResponse) args[3];

   HttpSession session = request.getSession();

   ActionMapping mapping = (ActionMapping) args[0];

   if (session.getAttribute("customer") == null) {

    System.out.println("test3");

    try {

     String url = request.getContextPath() + "/index.jsp";

     response.sendRedirect(url);

    } catch (Exception e) {

     System.out.println("test4");

    }

   }

}

}

如果我们每次调用到action里面的execute方法时就会调用拦截器进行拦截判断,

public void before(Method method, Object[] args, Object target)

method指拦截的方法,Object[] args指拦截的方法对应的参数,target指拦截的对象

继续阅读