模块功能
http://localhost:8080/car/get访问网页拦截器计算时间
结构
java.cn.teducontroller//包controller//类MyConfig//类MyInterlnterceptor//类RunApppom.xml
RunApp
package cn.tedu;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;@SpringBootApplication@Controllerpublic class RunApp {public static void main(String[] args) {SpringApplication.run(RunApp.class);}}
测试CarController
package cn.tedu.controller;import cn.tedu.RunApp;import org.springframework.boot.SpringApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/car")public class CarController {@RequestMapping("/save")public String save( ) {System.out.println("save方法");return "save方法";}@RequestMapping("/get")public String get() {for (int i = 0; i < 10; i++) {System.out.println("get执行中");}return "get方法";}}
MyInterlnterceptor创建拦截器
package cn.tedu.controller;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;import javax.xml.ws.handler.Handler;@Componentpublic class MyInterlnterceptor implements HandlerInterceptor {long start;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {start= System.currentTimeMillis();return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {long end = System.currentTimeMillis();System.out.println("方法执行了"+(end-start)+"ms");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("资源释放完成");}}
MyConfig注册拦截器
package cn.tedu.controller;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.WebMvcConfigurer;@Configuration//告诉spring容器,我是一个配置类public class MyConfig implements WebMvcConfigurer {@Autowired//自动装配private MyInterlnterceptor my;@Overridepublic void addInterceptors(InterceptorRegistry registry) {//把自定义的拦截器,放入容器中registry.addInterceptor(my);}}

