springboot-監聽器,過濾器,攔截器,aop,自定義註解
阿新 • • 發佈:2018-11-19
springboot基礎-監聽器,過濾器,攔截器,aop,自定義註解
文章目錄
環境
idea2018,jdk1.8,
springboot版本:1.5.9.RELEASE
程式碼下載:
https://github.com/2010yhh/springBoot-demos.git
測試:啟動專案後,訪問:
http://localhost:8080/springboot-demo2/test1 http://localhost:8080//springboot-demo2/test2
1.監聽器
listen的作用:可以在listen中完成一些如資料庫、建立、資料庫載入等一些初始化操作
@Component public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> { public static AtomicInteger count=new AtomicInteger(0); protected Logger log = LoggerFactory.getLogger(StartApplicationListener.class); private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); @Override public void onApplicationEvent(ContextRefreshedEvent event) { //防止重複執行 if (event.getApplicationContext().getParent() == null && count.incrementAndGet()<=1) { //這裡一個定時任務的初始化 this.service.scheduleAtFixedRate(new LogTask(),1000, 1000*60,TimeUnit.MILLISECONDS ); log.info("Listener系統配置載入完成..."); } } }
2.過濾器
filter的作用:攔截請求,對請求或響應(Request、Response)統一設定,對請求、響應頭加密、解密,對請求、響應壓縮,過濾掉非法url,做閘道器轉發等
@WebFilter(urlPatterns = "/test1/*", filterName = "indexFilter1") @Order(Integer.MAX_VALUE-1) public class MyFilter1 implements Filter { protected Logger log = LoggerFactory.getLogger(MyFilter1.class); @Override public void destroy() { log.info("----->:indexFilter1 destroy method"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); log.info("----->:indexFilter1 doFilter method"); } @Override public void init(FilterConfig arg0) throws ServletException { log.info("----->:indexFilter1 init method"); } }
3.攔截器
攔截器作用: * 作用於controller層,攔截到請求,對請求或響應(Request、Response)統一設定 * 進行邏輯判斷,如使用者是否已經登陸、有沒有許可權訪問該頁面等 和filter的作用有些類似,但二者又有不同的應用場景。
public class MyInterceptor implements HandlerInterceptor {
protected Logger log = LoggerFactory.getLogger(MyInterceptor.class);
//在請求處理之前進行呼叫(Controller方法呼叫之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
log.info("preHandle被呼叫");
return true; //如果false,停止流程,api被攔截
}
//請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
log.info("postHandle被呼叫");
}
//在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行(主要是用於進行資源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
log.info("afterCompletion被呼叫");
}
}
4.aop
aop的作用:橫切面,代表的是一個普遍存在的與業務關係不大的卻各個模組共有功能 * 橫切關注點:經常發生在核心關注點的多處,而各處都基本相似。比如許可權認證、日誌、方法耗時 * 、事務處理
@Aspect //宣告切面
@Component
public class LogAspect {
protected Logger log = LoggerFactory.getLogger(LogAspect.class);
//定義橫切點,標記方法
@Pointcut("execution(* com.ctg.test.controller..*.*(..))")
public void webLog(){}
//前置通知,切點之前執行
@Before("webLog()")
public void deBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 記錄下請求內容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
//切點執行成功之後執行
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 處理完請求,返回內容
log.info("方法的返回值 : " + ret);
}
//後置異常通知,切點丟擲異常後執行
@AfterThrowing("webLog()")
public void throwss(JoinPoint jp){
log.info("方法異常時執行.....");
}
//後置最終通知,final增強,不管是丟擲異常或者正常退出都會執行;切點執行之後執行
@After("webLog()")
public void after(JoinPoint jp){
log.info("方法最後執行.....");
}
}
5.自定義註解
自定義註解可以避免程式碼的冗餘,無侵害
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Inherited
public @interface MethodTime {
//自定義屬性
}