1. spring 注解切面
主要代码,参考《spring 实战》110页。
@Aspect
public class Audience {
@Pointcut("execution(* com.example.demo.asp.Sing.*(..))")
public void perform(){
}
@Around("perform()")
public void silenceCellPhone(ProceedingJoinPoint joinPoint){
// 解析参数
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
String[] parameterNames = methodSignature.getParameterNames();
}
@Before("perform()")
public void takeSeat(){
System.out.println("take seat=========>");
}
@AfterReturning("perform()")
public void applause(){
System.out.println("applause=========>");
}
@AfterThrowing("perform()")
public void demandRefund(){
System.out.println("Demand a Refund========>");
}
}
public class Sing implements Performance {
@Override
public void perform() throws Exception {
System.out.println(" this is a good singer,and this is a good song!");
throw new Exception("ccc");
}
}
代码参考:https://github.com/LM917178900/aspect-test.git
2. springBoot 接口拦截器
可以直接获取到接口的所有请求对象、请求参数、返回结果、异常。
public class SessionInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("brefore ==================>");
if(!(handler instanceof HandlerMethod)) {
System.out.println(0);
return true;
}
HandlerMethod handlerMethod = (HandlerMethod)handler;
Mytest methodAnnotation = handlerMethod.getMethodAnnotation(Mytest.class);
if(methodAnnotation == null){
System.out.println(1);
return true;
}
String str = methodAnnotation.value();
System.out.println("拦截value:"+str);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("after<=======*=======*========*======华丽的请求分割线======*=========*========*=======>");
}
}
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Bean
public SessionInterceptor getSessionInterceptor() {
System.out.println("bean加载了!");
return new SessionInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSessionInterceptor());
addInterceptor.addPathPatterns("/**");
}
}
代码参考:
https://github.com/LM917178900/interceptor.git
3.springMVC 接口拦截器
上面一种拦截器在springMVC中可能会失败,但是使用xml配置必定可行。
xml 配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.lenovo.mqm.log.MyHandlerInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
系统日志拦截器业务代码
public class MyHandlerInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(MyHandlerInterceptor.class);
/**
* 日志业务方法,包含多线程队列
*/
@Resource
private DataCollectService dataCollectService;
@Resource
private PortalUserUtil portalUserUtil;
@Resource
private PortalRoleUtil portalRoleUtil;
private ThreadLocal<Long> requestStartTime = new ThreadLocal<Long>();
/**
* 记录接口调用时间,日志用
*
* @param request 请求对象
* @param response 相应对象
* @param handler 方法处理对象
* @return 返回成功/失败
* @throws Exception 异常
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("===========HandlerInterceptor1 preHandle");
requestStartTime.set(System.nanoTime());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
System.out.println("===========HandlerInterceptor1 postHandle");
}
/**
* 接口处理完成后,获取接口参数、接口注释参数,用于系统日志记录
*
* @param request 请求对象
* @param response 相应对象
* @param handler 方法处理对象
* @param ex 捕捉到的异常
* @throws Exception 异常
* @author: leiming5
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
System.out.println("===========HandlerInterceptor1 afterCompletion");
// 拦截了两种注解,获取注解信息
LogApi logApi = null;
LogMenu logMenu = null;
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
logApi = h.getMethodAnnotation(LogApi.class);
logMenu = h.getMethod().getDeclaringClass().getAnnotation(LogMenu.class);
}
if (logMenu != null) {
//the exception might be null
Exception exception = (Exception) request.getAttribute(CommonConstant.Key.EXCEPTION);
// String userName = portalUserUtil.getUserName(request);
String userName = "leiming5";
SysLog sysLog = SysLog.build(logMenu, logApi, userName, exception);
try {
// dataCollectService.log(sysLog);
List<SysLog> logs = new ArrayList<>();
logs.add(sysLog);
if (CollectionUtils.isEmpty(logs)) {
return;
}
String jsonString = JSONArray.toJSONString(logs);
String json = portalRoleUtil.saveDataLogs(jsonString);
} catch (Exception e) {
LOGGER.error("save sys log error:", e);
}
String url = request.getServletPath();
Long startTime = requestStartTime.get();
long endTime = System.nanoTime();
LOGGER.info("API: Message[{}], url: {}, 耗时: {}毫微秒, {}毫秒, {}秒", sysLog.getMessage(),
url, (endTime - startTime), (endTime - startTime) / 1000000, (endTime - startTime) / 1000000000f);
}
}
}