当前位置:   article > 正文

spring Filter,Interseptor,Aspect使用场景比较_执行了 aspect界面优先级比 spring security 高

执行了 aspect界面优先级比 spring security 高
学习笔记

Spring 常用拦截器

我将以记录访问EESTFul API 访问者的ip地址为例

常见的三种拦截机制是实现以下三种实现的
1.过滤器 Filter
2.拦截器 Interceptor
3.切片Aspect


先让我们写一个简单的Filter


但是还是会有一些需要使我们不得应用启动项目的组件,那如何做到这一步了
这里我不找其他的过滤器我就用我写的Filter做Demo

//@Component 注释掉
public class IpFilter implements Filter 

@Configuration
public class FilterConfig  {

    @Bean
    public FilterRegistrationBean IpFilter(){
        //声明FilterRegistrationBean
        FilterRegistrationBean registrationBean=new FilterRegistrationBean();
        //声明IpFilter 第三方Filter
        IpFilter ipFilter=new IpFilter();

        registrationBean.setFilter(ipFilter);
        //设置拦截路径
        List<String> url=new ArrayList<>();
        //all
        url.add("/*");
        registrationBean.setUrlPatterns(url);
        return  registrationBean;
    }
}
Filter是可以拿到request,responst,但是他是不知道是哪个contrllor 哪个方法传过来的

  1. /**
  2. * createUser:JAVA_TOM
  3. * FileName: IpFilter
  4. * Author: 14562
  5. * Date: 2018/11/4 13:22
  6. * Description: Filter
  7. */
  8. package com.zwl.security.demo.filter;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.springframework.stereotype.Component;
  11. import javax.servlet.*;
  12. import javax.servlet.http.HttpServletRequest;
  13. import java.io.IOException;
  14. //实现javax.servlet.Filter
  15. public class IpFilter implements Filter {
  16. @Override
  17. public void init(FilterConfig filterConfig) throws ServletException {
  18. //初始化Filter
  19. System.out.println("my filtr init");
  20. }
  21. @Override
  22. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  23. //业务代码
  24. System.out.println("my filtr start");
  25. HttpServletRequest reque = (HttpServletRequest)request;//;
  26. String ipString =reque.getHeader("x-forwarded-for");
  27. if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString))
  28. { ipString = reque.getHeader("Proxy-Client-IP"); }
  29. if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString))
  30. { ipString = reque.getHeader("WL-Proxy-Client-IP"); }
  31. if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString))
  32. { ipString = reque.getRemoteAddr(); }
  33. System.out.println(ipString);
  34. chain.doFilter(request,response);//业务代码处理完毕执行后续代码
  35. System.out.println("my filtr finish");
  36. }
  37. @Override
  38. public void destroy() {
  39. //销毁Filter
  40. System.out.println("my filtr destroy");
  41. }
  42. }

 

 

但是用Interceptor可以解决

  1. /**
  2. * createUser:JAVA_TOM
  3. * FileName: IpInterceptor
  4. * Author: 14562
  5. * Date: 2018/11/4 19:32
  6. * Description: Interceptor
  7. */
  8. package com.zwl.security.demo.interceptor;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.web.method.HandlerMethod;
  11. import org.springframework.web.servlet.HandlerInterceptor;
  12. import org.springframework.web.servlet.ModelAndView;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.util.Date;
  16. @Component
  17. public class IpInterceptor implements HandlerInterceptor {
  18. @Override
  19. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  20. //在进contrllor的末个方法调用
  21. System.out.println("my IpInterceptor preHandle");
  22. System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
  23. System.out.println(((HandlerMethod)handler).getMethod().getName());
  24. request.setAttribute("time",new Date().getTime());
  25. return false;
  26. }
  27. @Override
  28. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  29. System.out.println("my IpInterceptor postHandle");
  30. Long time=(Long)request.getAttribute("time");
  31. System.out.println("耗时=》"+(new Date().getTime()-time));
  32. //在进入方法执行。但是调用的方法出现了异常,就不会调用
  33. }
  34. @Override
  35. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  36. System.out.println("my IpInterceptor afterCompletion");
  37. //后执行,多会执行
  38. //这里由于有个Exception,所以我们可以对这里做一些Exception的处理
  39. }
  40. }
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  @Autowired
  private IpInterceptor ipInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipInterceptor);

    }
}
最终执行的结果
my IpInterceptor preHandle
org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController
errorHtml
my IpInterceptor preHandle
com.zwl.security.demo.controller.userController
hello


如果我们还想拿到传参,那么就需要用切片


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class IpAspect  {
 //Around中的表达式不会请访问这个网址
//https://docs.spring.io/spring/docs/4.3.21.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#aop-pointcuts


    @Around("execution(* com.zwl.security.demo.controller.userController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("my IpAspect start");
        long start=System.currentTimeMillis();
        Object[] args=pjp.getArgs();
        for(Object arg : args){
            System.out.println("start =>"+arg);
        }
        Object object=pjp.proceed();
        System.out.println("time=>"+(System.currentTimeMillis()-start));
        System.out.println("my IpAspect end");
;


        return  null;
    }
}

总结的以上几种问题,我们来谈谈着三种的执行速度
我通过打印得到
1.Filter
2.Interseptor
3.controllerAdvice
4.Aspect
5.controller

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/342129
推荐阅读
相关标签
  

闽ICP备14008679号