一、定义拦截器 MyIntercepter
package com.example._09intercepter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Package: com.example._09intercepter
* @ClassName: MyIntercepter
* @Description: <p>Description: </p>
* @author: zq
* @since: 2020/5/5 19:27
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
public class MyIntercepter extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyIntercepter 拦截器");
return true;
}
}
二、定义测试controller
package com.example._09intercepter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Package: com.example._09intercepter
* @ClassName: IntercepterController
* @Description: <p>Description: </p>
* @author: zq
* @since: 2020/5/5 19:31
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
@Controller
public class IntercepterController {
@RequestMapping("/helloIntercepter")
@ResponseBody
public String helloIntercepter() {
return "helloIntercepter";
}
}
三、定义启动类,继承 WebMvcConfigurerAdapter,注册拦截器
package com.example._09intercepter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Package: com.example._09intercepter
* @ClassName: AppConfig
* @Description: <p>Description: </p>
* @author: zq
* @since: 2020/5/5 19:28
* @version: 1.0
* @Copyright: 2020 zq. All rights reserved.
*/
@SpringBootApplication
public class AppConfig extends WebMvcConfigurerAdapter {
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myIntercepter()).addPathPatterns("/*");
}
@Bean
public MyIntercepter myIntercepter() {
return new MyIntercepter();
}
public static void main(String[] args) {
SpringApplication.run(AppConfig.class, args);
}
}
四、测试验证;http://localhost:8084/helloIntercepter