您的位置:首页 > 编程语言 > Java开发

springMVC aop

2015-11-01 16:09 381 查看
1.pom.xml 中添加依赖

版本号:<org.aspectj-version>1.8.7</org.aspectj-version>
<span style="white-space:pre">		</span><cglib-version>3.2.0</cglib-version>
<span style="white-space:pre">		</span><javax.annotation-version>1.2</javax.annotation-version>

<!-- aop start -->

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${org.aspectj-version}</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib-version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-version}</version>
</dependency>

<!-- aop end -->


2.application-context中增加配置

<aop:aspectj-autoproxy/>
<!-- 通知spring使用cgliber而不是jdk的来生成代理方法aop,可以拦截到controller -->
<aop:aspectj-autoproxy proxy-target-class="true" />


3.自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* 自定义注解,拦截service
*
* @author  2015年10月30日 下午7:49:10
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SysServiceLog {
String description() default "";
}


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* 自定义注解,拦截controller
*
* @author  2015年10月30日 下午7:49:10
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SysControllerTarget {
String description() default "";
}


4.定义切点

/**
* service切点类
*
*
*/
@Aspect
@Component
public class SystemServiceAspect {

@Resource
ISystemLogService systemLogService;
static final Logger log = Logger.getRootLogger();

/**
* Service切点
*
* @author  2015年10月31日 上午10:19:07
*/
@Pointcut("@annotation(com.poobo.api.sytem.target.SysServiceLog)")
public void sysServiceAspect() {
}

/**
* service异常通知
*
* @author  2015年10月31日 上午10:23:00
* @param joinPoint
*/
//@AfterThrowing(pointcut = "sysServiceAspect()", throwing = "e")
@AfterThrowing(pointcut = "execution(* com.poobo.api.service.*.*(..))", throwing = "e")
public void doAfterServiceThrowing(JoinPoint joinPoint, Throwable e) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();

String sessionId = (String) request.getSession().getAttribute("sessionId");
String params=request.getParameter("params");
JsonStr2Params jsonStr2Params = JsonStr2Params.getInstance(params);
String header = (String) jsonStr2Params.getParamFromJsonStr(
new String(""), "sessionId");
if(null == sessionId ||"".equals(sessionId) || !header.equals(sessionId)){

}

//获取登录用户
User user = (User) request.getSession().getAttribute("user");

String ip=request.getRemoteAddr();
if(null!=user){
log.error(ip+"的用户"+user.getMobilePhone()+"访问发生异常");

}else{
log.error(ip+"的未登录用户访问发生异常");
}
//获取用户请求方法的参数并序列化为JSON格式字符串
if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {
for ( int i = 0; i < joinPoint.getArgs().length; i++) {
//                params += JSONObject.fromObject(object).toJsonString(joinPoint.getArgs()[i]) + ";";
}
}
try {
/*========控制台输出=========*/
log.error("=====异常通知开始=====");
log.error("异常代码:" + e.getClass().getName());
log.error("异常信息:" + e.getMessage());
log.error("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
log.error("方法描述:" + AspectUtils.getServiceMthodDescription(joinPoint));
log.error("请求IP:" + ip);
log.error("请求参数:" + params);
//保存数据库
//TODO
log.error("=====异常通知结束=====");
}  catch (Exception ex) {
//记录本地异常日志
log.error("==异常通知异常==");
log.error(String.format("异常信息:%s", ex.getMessage()));
}
/*==========记录本地异常日志==========*/
log.error(String.format("异常方法:%s异常代码:%s异常信息:%s参数:%s",  joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params));

}

}


@Aspect
@Component
public class SystemLoginAspect {

static final Logger log = Logger.getRootLogger();

/**
* Controller层切点
*
* @author  2015年10月31日 上午10:18:26
*/
@Pointcut("@annotation(com.poobo.api.sytem.target.SysControllerTarget)")
public void sysControllerAspect() {
}

/**
* controller环绕通知,用于拦截用户操作
*
* @author  2015年10月31日 上午10:23:00
* @param joinPoint
* @throws Throwable
*/
@Around("sysControllerAspect()")
public Object doBasicProfiling(ProceedingJoinPoint point) throws Throwable{

//访问目标方法的参数:
Object[] args = point.getArgs();

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getResponse();
String ip=request.getRemoteHost();
String sessionId = (String) request.getSession().getAttribute("sessionId");
String params=request.getParameter("params");
JsonStr2Params jsonStr2Params = JsonStr2Params.getInstance(params);
String header = (String) jsonStr2Params.getParamFromJsonStr(
new String(""), "sessionId");
String methodDes=AspectUtils.getLoginControllerMethodDescription(point);

log.debug(ip+"访问【"+methodDes+"】");
//		//得到拦截的真实方法
//		Object target = point.getTarget();
//		//取得类名字
//		String className = target.getClass().getName();
//		log.debug("Run doAround with class " + className);

Object returnObj=null;
if(null == sessionId ||"".equals(sessionId) || !header.equals(sessionId)){
log.debug(ip+"未登录");
//用改变后的参数执行目标方法
response.reset();
ReturnBean rt=new ReturnBean();
rt.setResultCode(EnumResultCode.FAIL.name());
rt.setResultMsg("未登录");
returnObj=rt;
}else{
returnObj= point.proceed(args);
}
return returnObj;

}

}


/**
* 控制层切点类
*
* @author  2015年10月31日 上午10:10:06
*
*/
@Aspect
@Component
public class SystemControllerLogAspect {

@Resource
ISystemLogService systemLogService;
static final Logger log = Logger.getRootLogger();

@Around(value = "execution(* com.poobo.api.mobile.controller.*.*(..))")
public Object doBasicProfiling(ProceedingJoinPoint point) throws Throwable {
long time = System.currentTimeMillis();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();

String ip = request.getRemoteHost();
StringBuffer url = request.getRequestURL();
String queryString = request.getQueryString();
String params = (String) request.getParameter("params");
if (StringUtils.isNotEmpty(params)) {
if (SystemConf.getEnvironment().equals("formal")) {
params = "params" + "=" + Base64.decode(params);
}

}

log.info(CommonUtil.DateToString(new Date(),
CommonUtil.TIMESTAMP_PATTERN)
+ "	ip:"
+ ip
+ "  request "
+ url.toString() + (queryString == null ? "" : "?" + params));
// 访问目标方法的参数:
Object[] args = point.getArgs();
if (args != null && args.length > 0
&& args[0].getClass() == String.class) {
for (int i = 0; i < args.length; i++) {
log.debug("args["
+ i
+ "]"
+ ((null == args[i] || StringUtils.isEmpty(String
.valueOf(args[i]))) ? "" : String
.valueOf(args[i])));
}

}
// 用改变后的参数执行目标方法
Object returnValue = point.proceed(args);
//		log.debug("@Around:执行目标方法之后...");
//		log.debug("@Around:被织入的目标对象为:" + point.getTarget());

time = System.currentTimeMillis() - time;
log.debug(String.format("方法执行耗时:%s毫秒", String.valueOf(time)));
log.info("返回值:" + JSONObject.fromObject(returnValue).toString());
return returnValue;
}

}


工具类
public class AspectUtils {

/**
* 获取注解中对方法的描述信息 用于service层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public  static String getServiceMthodDescription(JoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SysServiceLog.class).description();
break;
}
}
}
return description;
}

/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public  static String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SysControllerTarget.class).description();
break;
}
}
}
return description;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param joinPoint 切点
* @return 方法描述
* @throws Exception
*/
public  static String getLoginControllerMethodDescription(ProceedingJoinPoint joinPoint)  throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SysControllerTarget.class).description();
break;
}
}
}
return description;
}

}


5.控制层使用

@RequestMapping(value = "/toPaymentOrders")
@SysControllerTarget(description="用户下单")
public ReturnBean toPaymentOrders(HttpServletRequest request,@PathVariable String userType,
@RequestParam(required=false) String params){                                                                                             }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: