模块功能
http://localhost:8080/car/get访问网页拦截器计算时间
结构
java.cn.tedu
controller//包
controller//类
MyConfig//类
MyInterlnterceptor//类
RunApp
pom.xml
RunApp
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
@SpringBootApplication
@Controller
public 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;
@Component
public class MyInterlnterceptor implements HandlerInterceptor {
long start;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
start= System.currentTimeMillis();
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long end = System.currentTimeMillis();
System.out.println("方法执行了"+(end-start)+"ms");
}
@Override
public 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;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//把自定义的拦截器,放入容器中
registry.addInterceptor(my);
}
}