<bean id="auth" class="com.leo.security.MyDecisoinVoter">
</bean>
<aop:config proxy-target-class="true">
<aop:aspect id="authAspect" ref="auth">
[color=red]<aop:pointcut id="authP" expression="execution(* com.leo.control.*.*(..))" />[/color]
<aop:around pointcut-ref="authP" method="authPermission" />
</aop:aspect>
</aop:config>
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
public class MyDecisoinVoter {
/**
* 得到request的方法 1.HttpServletRequest request = ((ServletRequestAttributes)
* RequestContextHolder .getRequestAttributes()).getRequest(); 2.如下
*/
@Autowired(required = true)
private HttpServletRequest request;
public Object authPermission(JoinPoint joinPoint) throws Throwable {
MethodInvocationProceedingJoinPoint methodJoinPoint = (MethodInvocationProceedingJoinPoint) joinPoint;
MethodSignature methodSignature = (MethodSignature) methodJoinPoint
.getSignature();
Method method = methodSignature.getMethod();
int range = Integer.parseInt(request.getParameter("range"));
if (range > 10)
return new ModelAndView("addUserInput");
return new ModelAndView("index");
}
}
在使用spring mvc时,通常用它的aop来记录日志(或者拦截其它的操作),但在spring mvc采用@Controller注解时,对Controller进行Aop拦截不起作用(上面的配置不起作用,[color=red]<aop:pointcut id="authP" expression="execution(* com.leo.control.*.*(..))" />[/color]上面的红色是配置自己controller所有的方法),原因是该注解的Controller已被spring容器内部代理了.
查网上的资料如下两种配置起作用
1.xml
<bean id="auth" class="com.leo.security.MyDecisoinVoter">
</bean>
<aop:config proxy-target-class="true">
<aop:aspect id="authAspect" ref="auth">
<aop:pointcut id="authP"
expression="execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(..))" />
<aop:around pointcut-ref="authP" method="authPermission" />
</aop:aspect>
</aop:config>
2.annonation
package com.autoabacus.dal.controller;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aop {
public Aop() {
System.out.println("Aop");
}
// @Around("within(org.springframework.web.bind.annotation.support.HandlerMethodInvoker..*)")
@Around("execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(..))")
public Object aa(ProceedingJoinPoint pjp) throws Throwable
{
try {
Object retVal = pjp.proceed();
System.out.println(retVal);
return retVal;
} catch (Exception e) {
System.out.println("异常");
return null;
}
}
}