Filter,攔截器,aop攔截的實現與區別


Filter,攔截器,aop攔截的實現與區別

 

實現
1 Filter
直接實現Filter接口,重寫攔截方法,再到@WebFilter注解上配置攔截規則即可實現

@Component
@WebFilter(urlPatterns = { "/**" }, filterName = "tokenAuthorFilter")
public class ConfigurationFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("我是Filter,我攔截到了請求");
chain.doFilter(request, response);//到下一個鏈
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}
}

攔截器
和filter類似 實現HandlerInterceptor接口並重寫攔截方法

public class MyInterceptor implements HandlerInterceptor{

//在請求處理之前進行調用(Controller方法調用之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.printf("我是攔截器:preHandle被調用");

HandlerMethod handlerMethod = (HandlerMethod) o;
Method method = handlerMethod.getMethod();
if (method.getAnnotation(interceptorLog.class) != null) {
return true;
}else{
return false;
}
}

//請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("我是攔截器:postHandle被調用");
}

//在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用於進行資源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("我是攔截器:afterCompletion被調用");
}

}

像spring容器內將創建的攔截器注冊進去

@Configuration
public class interceptorConfig extends WebMvcConfigurerAdapter{
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new MyInterceptor()) //指定攔截器類
.addPathPatterns("/**"); //指定該類攔截的url
}
}

自定義一個注解用於攔截標識

@Retention(RetentionPolicy.RUNTIME) // 表示注解在運行時依然存在
@Target(ElementType.METHOD)
@Documented
public @interface interceptorLog {

}

aop攔截
pom

<!--AOP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--druid -->

配置aop

@Component
@Aspect
public class HttpAspect {
@Pointcut("execution(* spring.controller..*.*(..)) && @annotation(spring.annotation.aopLog)")
// @Pointcut("public * *(..)")

//@Pointcut("execution(* spring.*.controller.*.*(..))")

public void log(){
}

@Around("log()")
public void aroundLogCalls(JoinPoint joinPoint) throws Throwable {

System.out.println("我是aop:方法環繞start.....");


System.out.println("我是aop:方法環繞end.....");

}
/**
* 打印請求的ur l method ip 類方法 參數
* @param joinPoint
*/
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request =attributes.getRequest();

System.out.println("我是aop:方法開始");

}


// @After("execution(public * com.tg.controller.GirlController.*(..))")
@After("log()")
public void doAfter(){
System.out.println("我是aop:方法結束");
}

/**
* 打印請求的具體內容
* @param objects
*/
@AfterReturning(returning = "objects",pointcut = "log()")
public void doAfterReturning(Objects objects){

}


@AfterThrowing("log()")
public void cathInfo(){
System.out.println("異常信息");
}

}

自定義注解用於攔截標識

@Retention(RetentionPolicy.RUNTIME) // 表示注解在運行時依然存在
@Target(ElementType.METHOD)
@Documented
public @interface aopLog {

}

被請求方法

@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
@ApiOperation("登錄")
@ResponseBody
@aopLog
@interceptorLog
public Map<String, Object> login(
@RequestParam(value="useName", required=true) String useName,
@RequestParam(value="passWord", required=true) String passWord
){
Map<String,Object> result=new HashMap<String,Object>();
try{
//查詢
userInfo selectedUser= dao.selectUserInfo(useName);
//更新
dao.updateFrequency(useName);
if(selectedUser.getPassWord().equals(passWord)){
result.put("userInfo", selectedUser);
result.put("code", "200");
}else{
result.put("msg", "賬號密碼錯誤");
}
}catch(Exception e){
result.put("code", "404");
}
return result;
}}

 


總結:

這是swagger連接到服務器所觸發的攔截信息,可以看到所有的請求都會被filter首先攔截,並可以預處理request,
而攔截器可以調用IOC容器中的各種依賴,filter就不能獲取注解信息並攔截,因為它和框架無關,但攔截器不能修改request,filter基於回調函數,我們需要實現的filter接口中doFilter方法就是回調函數,而interceptor則基於java本身的反射機制,而@Aspect與Interceptor的都是基於spring aop的實現,@Aspect粒度更細
攔截順序:filter—>Interceptor—->@Aspect

---------------------
作者:白馬湖小龍王
來源:CSDN
原文:https://blog.csdn.net/weixin_39168678/article/details/80987539
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM