Spring-AOP

面向切面编程
什么叫面向切面编程呢,就是说监听一切相关的类或者方法,这个被监听者就是切面

常见的切面

  • 方法的切面
  • interceptor拦截器
  • filter过滤器

在ssm文件夹下创建一个叫aop的文件夹

方法的切面
可以在被监听的方法的前后或者环绕进行拦截,下面是环绕的示例代码

// aop/aop.java

@Component
@Aspect
public class aop {

    // Pointcut定义切点函数
    @Pointcut("execution(* com.pdt.ssm.service.*.*(..))")
    private void myPointcut() { }

    @Around("myPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("--->BindingResultAop start...");
        String className = jp.getTarget().getClass().getName();
        String methodName = jp.getSignature().getName();
        System.out.println("before " + className + "." + methodName + "() invoking!");
        // 执行目标方法
        return jp.proceed();
    }
}

interceptor拦截器
这个最常用在对未登陆用户的监听

// aop/interceptor.java

public class interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
                             Object arg2) throws Exception {
//        在这个可以判断访问路径,
//        常用于 判断req是不是有指定的token或者session表示登录状态
//        也可以用来判断访问路径存不存在,没有返回404页面
//        返回true是放行,false就是
//        如果不放行,先用req.getRequestDispatcher(路径).forword(req,res),再return false
        return true;
    }
}

filter过滤器
我设定了3个过滤器

  • whiteList,白名单过滤器
// config.java 添加白名单
public class config {
    public static final ArrayList whiteList = new ArrayList();
    static {
        whiteList.add("127.0.0.1:80");
        whiteList.add("127.0.0.1:3000");
        whiteList.add("127.0.0.1:8080");
        whiteList.add("127.0.0.1:8848");
        whiteList.add("127.0.0.1:9528");
        whiteList.add("localhost:9528");
    }
    public static boolean isWhiteList(String ip) {
       if(whiteList.indexOf(ip)==-1){
           return false;
       }
        return true;
    }
}


// WebFilter注解就不需要去web.xml里配置filter标签
@WebFilter(filterName = "whiteListFilter",
        urlPatterns = "/*",/*通配符(*)表示对所有的web资源进行拦截*/
        initParams = {
                @WebInitParam(name = "charset", value = "utf-8")/*这里可以放一些初始化的参数*/
        })
public class whiteListFilter implements Filter {

    private String filterName;

    public void destroy() {
        /*销毁时调用*/
        System.out.println(filterName + "销毁");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest httpreq = (HttpServletRequest)req;
        String Origin =  httpreq.getHeader("Origin");
        System.out.println(Origin);
//        String Referer =  httpreq.getHeader("Referer");
        if(StringUtils.isEmpty(Origin)){
            chain.doFilter(req,resp);  //放行
        }else{
            Origin = Origin.split("//")[1];
            System.out.println(Origin);
            if(config.isWhiteList(Origin)){
                chain.doFilter(req,resp);  //放行
            }else{
                System.out.println("不在白名单之内");
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
        filterName = config.getFilterName();
        System.out.println("过滤器:" + filterName + "启动");
    }
}
  • 日记过滤器
// WebFilter注解就不需要去web.xml里配置filter标签
@WebFilter(filterName = "loggerFilter",
        urlPatterns = "/*",/*通配符(*)表示对所有的web资源进行拦截*/
        initParams = {
                @WebInitParam(name = "charset", value = "utf-8")/*这里可以放一些初始化的参数*/
        })
public class loggerFilter implements Filter {

    private String filterName;
    final Logger log = Logger.getLogger(loggerFilter.class);

    public void destroy() {
        /*销毁时调用*/
        System.out.println(filterName + "销毁");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpreq = (HttpServletRequest)req;
        System.out.println(new Date().getTime()+"---"+httpreq.getMethod()+"---"+httpreq.getRequestURL());
        /*过滤方法 主要是对request和response进行一些处理,然后交给下一个过滤器或Servlet处理*/
        log.info("这是日志")
        chain.doFilter(req,resp);  //放行
    }

    public void init(FilterConfig config) throws ServletException {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
        filterName = config.getFilterName();
        System.out.println("过滤器:" + filterName + "启动");

    }
}
  • 跨域过滤器
// WebFilter注解就不需要去web.xml里配置filter标签
@WebFilter(filterName = "crosFilter",
        urlPatterns = "/*",/*通配符(*)表示对所有的web资源进行拦截*/
        initParams = {
                @WebInitParam(name = "charset", value = "utf-8")/*这里可以放一些初始化的参数*/
        })
public class crosFilter implements Filter {

    private String filterName;

    public void destroy() {
        /*销毁时调用*/
        System.out.println(filterName + "销毁");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println(filterName);
        /*过滤方法 主要是对request和response进行一些处理,然后交给下一个过滤器或Servlet处理*/
        HttpServletResponse httpResponse = (HttpServletResponse)resp;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "1800");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type,Accept,accept,Access-Control-Request-Method,Access-Control-Request-Headers,token,x-token");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
          chain.doFilter(req,resp);  //放行
    }

    public void init(FilterConfig config) throws ServletException {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
        filterName = config.getFilterName();
        System.out.println("过滤器:" + filterName + "启动");
    }
}
posted @ 2020-01-29 16:19  一个年轻淫  阅读(185)  评论(0编辑  收藏  举报