springboot 自定义一个简单拦截器

很多时候我们都需要自定义一个拦截器来拦截一些请求,那么在springboot中怎么自定义一个拦截器呢?

1、新建一个springboot的项目(略)

    项目结构:

    springboot 自定义一个简单拦截器_第1张图片

2、导入相应的依赖

xml version="1.0" encoding="UTF-8"?>
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   4.0.0

   com.example
   demo
   0.0.1-SNAPSHOT
   jar

   demo
   Demo project for Spring Boot

   
      org.springframework.boot
      spring-boot-starter-parent
      2.0.1.RELEASE
      
   

   
      UTF-8
      UTF-8
      1.8
   

   
      
         org.springframework.boot
         spring-boot-starter-thymeleaf
      
      
         org.springframework.boot
         spring-boot-starter-web
      

      
         org.springframework.boot
         spring-boot-devtools
         true
         true
      
      
         org.springframework.boot
         spring-boot-starter-test
         test
      
   

   
      
         
            org.springframework.boot
            spring-boot-maven-plugin
            
               true
            
         
      
   



3、在com.example下新建controller 和 interceptor 两个包 在两个包下分别新建 TestController.java 和 SpringInterceptor.java两      个类 

4、编写代码

    TestController.java

    

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
    @RequestMapping("/index")
    public String hello (){
        return "index";
    }
}

SpringInterceptor.java

package com.example.Interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class SpringInterceptor extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("自定义拦截器执行了。。。。。");
                return true;
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }


}

5、测试一下效果 在resources/templates下新建一个index.html

html>
lang="en">

    charset="UTF-8">
    </span>test<span style="color:#e8bf6a;">


    I'm a test !!!

运行 :

springboot 自定义一个简单拦截器_第2张图片

springboot 自定义一个简单拦截器_第3张图片

到这里一个自定义拦截器就完成了!

你可能感兴趣的:(springboot)