SpringMVCDay03 练习

1.练习:基于拦截器实现控制层方法监控,计算控制层方法执行时长
2.思路:方法上有TimeMonitor的做时间监控,不做注解的不做监控 【@TimeMonitor不存在】
新建注解@TimeMonitor

一、controller
@RequestMapping(“doStudyMVC”)
@ResponseBody
@TimeMonitor
public String doStudyMVC(){
String result =“do study MVC”;
System.out.println(result);
// 模拟耗时动作
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}

二、annotation
@Retention(RetentionPolicy.RUNTIME) //定义注解何时有效
//target用于描述注解用于修饰哪些元素
@Target(ElementType.METHOD) //用来描述方法的!
public @interface TimeMonitor {
}

三、timeInterceptor

// 控制层方法执行前执行
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println(“preHandle”);
// 对参数进行向下转型(目的是获取我们要执行的方法对象)
HandlerMethod hMethod = (HandlerMethod)o; //强转
// 获取目标方法上的注解
TimeMonitor tMonitor = hMethod.getMethodAnnotation(TimeMonitor.class); //绑定注解
if(tMonitor!=null){ //如果调用了 ,记录加载时间
long startTime = System.currentTimeMillis();
httpServletRequest.setAttribute(“startTime”,startTime);
}
return true; //false表示拦截 true表示不拦截
}

// 控制层方法执行后执行
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println(“postHandle”);
}

// 视图渲染结束后执行
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println(“afterCompletion”);

// 问 :是谁运行的时长
// System.out.println(o.getClass().getName()); //输出:org.springframework.web.method.HandlerMethod
HandlerMethod hMethod = (HandlerMethod)o; //强转为HandlerMethod类型对象
TimeMonitor tMonitor = hMethod.getMethodAnnotation(TimeMonitor.class);
if(tMonitor!=null){
long endTiem = System.currentTimeMillis();
long startTime = (Long)httpServletRequest.getAttribute(“startTime”); //为什么long类型是Long类型
long totalTime = endTiem-startTime;
Method method = hMethod.getMethod(); //这个对象有 .getMethod()方法 放入方法类
// 获得正在执行的方法的所在类名
String beanCls = hMethod.getBeanType().getName();
System.out.println(beanCls+“类的”+method.getName()+“方法执行总时长为:”+totalTime);
}

访问:http://localhost:8080/springmvcday3/doSomething
结果:
在这里插入图片描述
访问:http://localhost:8080/springmvcday3/doStudyIntercept
结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值