欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Filter, Interceptor, Validator, Aop 执行顺序

程序员文章站 2022-03-08 16:43:04
...

顺序如下
 

1 filter
    2.1 interceptor-pre
        3 valid参数校验
            4.1 aop-pre
                5.1 业务方法
            4.2 aop-post(校验失败时_不执行)
    2.2 interceptor-post(校验失败时_不执行)
    2.3 interceptor-afterCompletion(校验失败时_任然执行)

============================================

filter 过滤器 https://www.cnblogs.com/huanzi-qch/p/11239167.html
filter: post拿不到参数? POST的请求是在请求体body中,而POST请求中的body参数是已流形式存在的    https://blog.csdn.net/qq_40866897/article/details/111404480

Interceptor 拦截器 https://blog.csdn.net/worilb/article/details/114194446

Validator 参数校验 https://www.cnblogs.com/mooba/p/11276062.html

aop https://ld246.com/article/1551866577094

===========================================

Filter

@WebFilter(filterName = "testFilter", urlPatterns = {"/test"})
@Component
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取post时, 请求中的body参数是流的形式存在 request.getRequestParams()拿不到值
        // 所以需要自行封装
        RequestWrapper requestWrapper = new RequestWrapper(request);

        System.out.println("TestFilter," + request.getRequestURI());
        System.out.println(requestWrapper.getBodyString());
        //执行
        filterChain.doFilter(requestWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

RequestWrapper 防止读取流后, controller获取不到值

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;


public class RequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //保存一份InputStream,将其转换为字节数组
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }

    //转换成String
    public String getBodyString(){
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    //把保存好的InputStream,传下去
    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}

Interceptor

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...1");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...3");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("postafterCompletionHandle...4");
    }
}

注册拦截器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class MyInterceptorConfig implements WebMvcConfigurer {

    @Autowired
    MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/test").excludePathPatterns("/admin");

    }
}

aop

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

@Aspect
@Component
public class MyLogAspect {

    @Pointcut("@annotation(com.xxx.annotation.MyLog)")
    public void logCut() {
    }

    @Around("logCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("aop start");
        Object result = point.proceed();
        System.out.println("aop end");
        return result;
    }

}

controller

@RestController
@RequestMapping("")
public class TestController {
    @RequestMapping("/test")
    public String test() {
        System.out.println("业务逻辑....2");
        return "success";
    }
}