切面,过滤器,拦截器的实现

1.实现一个切面:

1,通过@Aspect注释来声明一个切面。
2,通过@Component注释把切面注入到容器中。
3,通过@Around("execution(* com.springboot.filterinterceptoraspect.controller.TestController.*(..))")把切面通知的表达式绑定到某个类的方法
4,通过ProceedingJoinPoint连接点,获取方法的相关信息,如:命名,参数,返回值。

1.1.AspectHandler.java自定义一个切面

@Aspect
@Component
public class AspectHandler {
    @Around("execution(* com.springboot.filterinterceptoraspect.controller.TestController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
    System.out.println("time aspect start");
    Object[] args = proceedingJoinPoint.getArgs();
    for (Object arg : args ) {
      System.out.println(arg.getClass().getName());
      System.out.println("arg is:"+arg);
    }
    long startTime = new Date().getTime();
    Object obj = proceedingJoinPoint.proceed();
    System.out.println("aspect 耗时:" + (new Date().getTime() - startTime));
    System.out.println("aspect end");
    return obj;
    }
}

2.过滤器和拦截器的关系

在这里插入图片描述

在这里插入图片描述

3.实现一个过滤器

1,通过@Component注释,把过滤器注入到容器中。
2,通过实现Filter过滤器接口的doFilter方法,在方法中通过条件判断,满足条件就放行,执行filterChain.doFilter(servletRequest, servletResponse)方法,让请求进入到servlet中。否则返回拦截的结果,结束请求。

过滤器Filter基类接口的方法,自定义的过滤器只要实现doFilter的方法,在方法中进行放行(filterChain.doFilter(servletRequest, servletResponse))还是拦截就好。
在这里插入图片描述

3.1.FilterHandler.java自定义过滤器

package com.springboot.filterinterceptoraspect.common.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
//@WebFilter(filterName = "filterHandler",urlPatterns = {"/test"})
public class FilterHandler implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("filter init");
  }

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    System.out.println("filter start");
    long startTime = new Date().getTime();
    HttpServletRequest  httpServletRequest = (HttpServletRequest) servletRequest;
    String token = httpServletRequest.getHeader("token");
    String name = httpServletRequest.getParameter("name");
    if(name!=null){
    filterChain.doFilter(servletRequest, servletResponse);
    long endTime = System.currentTimeMillis();
    System.out.println("filter time:" + (endTime - startTime));
    System.out.println("filter finish");
    }else{
//      servletResponse.setCharacterEncoding("UTF-8");
      servletResponse.setContentType("application/json;charset=utf-8");
      PrintWriter writer =  servletResponse.getWriter();
      Map<String,Object> map = new HashMap<>();
      map.put("code", 1);
      map.put("message", "验证不通过,过滤器进行拦截");
      // 方法1:
      /* ObjectMapper om = new ObjectMapper();
      writer.write(om.writeValueAsString(map));*/
      //方法2:
      writer.write(JSON.toJSONString(map));
      writer.flush();
      writer.close();
    }
  }

  @Override
  public void destroy() {
    System.out.println("filter destroy");
  }
}

4.实现一个拦截器

1.通过实现HandlerInterceptor接口的方法preHandle,该方法返回true,即表示不拦截。返回false,即表示拦截。
2.通过注释@Component把拦截器的类注入到容器中。
3.再通过WebMvcConfigurationSupport的配置类,重写addInterceptors方法把自定义的拦截器添加到拦截器的注册列表中。

在这里插入图片描述

4.2.InterceptorHandler.java自定义拦截器

package com.springboot.filterinterceptoraspect.common.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class InterceptorHandler implements HandlerInterceptor {
    /**
     * 控制器方法处理之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    System.out.println("preHandle");
    System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
    System.out.println(((HandlerMethod) handler).getMethod().getName());
    request.setAttribute("startTime", new Date().getTime());
    return true;
    // return false:表示拦截,return true:表示不拦截
  }

    /**
     * 控制器方法处理之后 控制器方法调用不抛异常调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    System.out.println("postHandle");
    Long startTime = (Long) request.getAttribute("startTime");
    System.out.println("interceptor 耗时:" + (new Date().getTime() - startTime));
  }

    /**
     * 控制器方法抛不抛异常都会被调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    System.out.println("afterCompletion");
    Long startTime = (Long) request.getAttribute("startTime");
    System.out.println("interceptor 耗时:" + (new Date().getTime() - startTime));
  }
}

4.2.WebConfig.java

package com.springboot.filterinterceptoraspect.common.config;

import com.springboot.filterinterceptoraspect.common.interceptor.InterceptorHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Autowired
    private InterceptorHandler interceptorHandler;
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(interceptorHandler);
       // super.addInterceptors(registry);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值