M87星云

导航

springboot配置mvc拦截器

1、导入依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/>
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

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

2、配置controller

@Controller
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/show")
    @ResponseBody
    public String show(){
        return "hello world!";
    }

}

3、创建Interceptor拦截器

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器执行中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器执行后");
    }
}

4、配置拦截器

@Configuration
public class MyWebConfiguration implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         *  addPathPatterns 拦截的资源,/** 表示拦截所有多级资源
         *  excludePathPatterns 不拦截的资源 aa.js
         */
        registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/aa.js");
    }
}

5、springboot目录结构

 

 6、测试拦截器

访问 http://localhost:8080/hello/show,提示如图信息表示拦截器配置成功

 

posted on 2021-06-20 03:19  挽留匆匆的美丽  阅读(342)  评论(0编辑  收藏  举报