springboot中过滤器、拦截器、切片使用

直接贴代码:采用maven工程

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.theorydance</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springbootdemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加切片AOP依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

com.theorydance.springbootdemo.conf.DemoFilter.java

package com.theorydance.springbootdemo.conf;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * 这里添加WebFilter注解,然后再启动类上添加ServletComponentScan注解
 * 能匹配/demoController/*,不会匹配/demoController2/*
 */
@WebFilter(filterName="FirstFilter",urlPatterns = {"/demoController/*"})
public class DemoFilter implements Filter{

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("this is demoFilter before.....");
        chain.doFilter(req, resp);
        System.out.println("this is demoFilter after.....");
    }

}

 

com.theorydance.springbootdemo.conf.DemoHandlerInterceptor.java

package com.theorydance.springbootdemo.conf;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class DemoHandlerInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("this is DemoHandlerInterceptor preHandle.....");
     System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
     System.out.println(((HandlerMethod)handler).getMethod().getName());
return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("this is DemoHandlerInterceptor postHandle.....");
  }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("this is DemoHandlerInterceptor afterCompletion.....");
    }
    
}

 

 org.springframework.web.method.HandlerMethod由一个method和一个bean.组成

 

 

 

com.theorydance.springbootdemo.conf.DemoLogAspect.java, 切片参考博客:https://www.jianshu.com/p/efbc657e034c

package com.theorydance.springbootdemo.conf;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class DemoLogAspect {

//    Pointcut("execution(public * com.theorydance.springbootdemo..*.*(..))")
    @Pointcut("execution(public * com.theorydance.springbootdemo.service.DemoService.*(..))")
    public void demolog() {}
    
    @Before("demolog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("IP : " + request.getRemoteAddr());
        System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }
    
    @AfterReturning(returning = "ret", pointcut = "demolog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("RESPONSE : " + ret);
    }
    
}

 

com.theorydance.springbootdemo.conf.MvcInterceptorConfig.java

package com.theorydance.springbootdemo.conf;

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 MvcInterceptorConfig extends WebMvcConfigurationSupport{ // 或实现接口WebMvcConfigurer也是一样
    
    @Autowired
    private DemoHandlerInterceptor demoHandlerInterceptor;
    
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(demoHandlerInterceptor).addPathPatterns("/demoController/**")
        .excludePathPatterns("/demoController/demo2");    
        super.addInterceptors(registry);
    }
// 还可以在这里添加跨域控制
@Override
public void addCorsMappings(CorsRegistry registry) {.....} }

 

com.theorydance.springbootdemo.controller.DemoController.java

package com.theorydance.springbootdemo.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.theorydance.springbootdemo.service.DemoService;

@RestController
@RequestMapping("/demoController")
public class DemoController {

    @Resource
    private DemoService demoService;
    
    @RequestMapping(value="/demo1",method=RequestMethod.GET)
    public void demo1(){
        System.out.println("this is demoController.demo1()");
        demoService.doSomething();
    }
    
    @RequestMapping(value="/demo2",method=RequestMethod.GET)
    public void demo2(){
        System.out.println("this is demoController.demo2()");
        demoService.doSomething();
    }
    
}

 

com.theorydance.springbootdemo.controller.DemoController2.java

package com.theorydance.springbootdemo.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.theorydance.springbootdemo.service.DemoService;

@RestController
@RequestMapping("/demoController2")
public class DemoController2 {

    @Resource
    private DemoService demoService;
    
    @RequestMapping(value="/demo1",method=RequestMethod.GET)
    public void demo1(){
        System.out.println("this is demoController2.demo1()");
        demoService.doSomething();
    }
    
    @RequestMapping(value="/demo2",method=RequestMethod.GET)
    public void demo2(){
        System.out.println("this is demoController2.demo2()");
        demoService.doSomething("theorydance");
    }
    
}

 

com.theorydance.springbootdemo.service.DemoService.java

package com.theorydance.springbootdemo.service;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

    public String doSomething(String...strs) {
        System.out.println("this is DemoService.doSomething()");
        return null;
    }

}

启动类com.theorydance.springbootdemo.DemoApplication.java

package com.theorydance.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
}

 测试效果,主要是访问对应的url,来查看控制台输出日志的情况

 

三者同时采用,执行顺序

filter > interceptor > ControllerAdvice > aspect > controller

posted @ 2020-03-09 23:35  理舞  阅读(828)  评论(0编辑  收藏  举报