赞
踩
自定义注解实现对controller层对标注了该注解的方法统计请求次数
CustomAnnotation
- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- public @interface CustomAnnotation {
- }
CustomHandlerInterceptor
- @Component
- public class CustomHandlerInterceptor implements HandlerInterceptor {
-
- private Map<String,Integer> count = new HashMap<>();
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- Method method = handlerMethod.getMethod();
-
- if (method.isAnnotationPresent(CustomAnnotation.class)){
- String requestURI = request.getRequestURI();
- if (requestURI!=null || !"".equals(requestURI)){
- if (count.containsKey(requestURI)){
- count.put(requestURI,count.get(requestURI)+1);
- }else {
- count.put(requestURI,1);
- }
- }
- System.out.println(requestURI+"请求次数为:"+count.get(requestURI));
- }
-
- return HandlerInterceptor.super.preHandle(request, response, handler);
- }
- }
WebConfig
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
-
- @Resource
- private CustomHandlerInterceptor customHandlerInterceptor;
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(customHandlerInterceptor).addPathPatterns("/**");
- }
- }
HelloController
- @RestController
- public class HelloController {
-
- @CustomAnnotation
- @RequestMapping("/hello")
- public String hello(){
- return "hello";
- }
-
- @RequestMapping("/hello2")
- public String hello2(){
- return "hello2";
- }
- }
localhost:8080/hello:连续点击两次,控制台输出
- 2022-04-25 13:46:12.268 INFO 1935 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 858 ms
- 2022-04-25 13:46:12.561 INFO 1935 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
- 2022-04-25 13:46:12.570 INFO 1935 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.489 seconds (JVM running for 2.096)
- 2022-04-25 13:46:16.786 INFO 1935 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
- 2022-04-25 13:46:16.786 INFO 1935 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
- 2022-04-25 13:46:16.787 INFO 1935 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
- /hello请求次数为:1
- /hello请求次数为:2
localhost:8080/hello2:控制台无输出
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。