1.使用过滤器Filter:

我们可以在建立的springboot的项目中建立新的类来是先Filter的接口,doFilter是过滤器中的主要方法,用来做处理逻辑,最后我们只需要在类上加@Component注解就可以让过滤器生效了.

package com.city.web;

import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
import java.util.Date; @Component
public class TimeFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("time filter init!");
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("time filter start");
long start = new Date().getTime(); chain.doFilter(request,response);
System.out.println("time filter:"+(new Date().getTime()-start)); System.out.println("time filter finish");
} @Override
public void destroy() {
System.out.println("time filter destroy!");
}
}

当然我们也可以不用@Component注解,但是需要建一个配置类,也可以让过滤器生效,如下:

package com.city.web.configer;

import com.city.web.TimeFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.ArrayList;
import java.util.List; @Configuration
public class WebConfig { @Bean
public FilterRegistrationBean timeFilter2(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); TimeFilter timeFilter = new TimeFilter(); filterRegistrationBean.setFilter(timeFilter); List<String> urls = new ArrayList<>(); urls.add("/*"); filterRegistrationBean.setUrlPatterns(urls); return filterRegistrationBean;
}
}

2.使用拦截器HandlerInterceptor

建立TimeInterecepter实现HandlerInterceptor,如下:

package com.city.web.interecepter;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date; @Component
public class TimeInterecepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
request.setAttribute("startTime", new Date().getTime());
System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
System.out.println(((HandlerMethod) handler).getMethod().getName());
return true; //这里控制是否调用后面的方法 建议返回true
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("preHandle");
Long start = (Long) request.getAttribute("startTime");
System.out.println("time intercepter 耗时:" + (new Date().getTime() - start));
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
Long start = (Long) request.getAttribute("startTime");
System.out.println("time intercepter 耗时:" + (new Date().getTime() - start));
System.out.println("ex is "+ex); } }

这里的类写好后还必须在配置类中配置这个拦截器才会使其生效,如下所示:

package com.city.web.configer;

import com.city.web.TimeFilter;
import com.city.web.interecepter.TimeInterecepter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.ArrayList;
import java.util.List; @Configuration
public class WebConfig extends WebMvcConfigurerAdapter { @Autowired
private TimeInterecepter timeInterecepter; @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timeInterecepter);
} }

3.使用切片:

比如我们要切入DemoApplication这个类中:

package com.city.web.aspect;

import com.navercorp.pinpoint.common.annotations.InterfaceAudience;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.security.PublicKey;
import java.util.Date; @Aspect
@Component
public class TimeAspect { @Around("execution(* com.city.DemoApplication.*(..))")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable { long start = new Date().getTime();
Object[] args = pjp.getArgs();
for (Object arg : args) {
System.out.println("arg is "+arg);
} System.out.println("time aspect start");
Object object = pjp.proceed(); System.out.println("time aspect 耗时:"+(new Date().getTime()-start)); System.out.println("time aspect end"); return object;
} }

关于restful的API拦截的处理层级关系:

使用切片拦截Rest服务的更多相关文章

  1. Spring Security构建Rest服务-0400-使用切片拦截rest服务

    Restful API的拦截: 1,过滤器(Filter) 2,拦截器(Interceptor) 3,切片(Aspect) 1,过滤器 和传统javaweb一鸟样,例,记录controller执行时间 ...

  2. springboot中使用Filter、Interceptor和aop拦截REST服务

    在springboot中使用rest服务时,往往需要对controller层的请求进行拦截或者获取请求数据和返回数据,就需要过滤器.拦截器或者切片. 过滤器(Filter):对HttpServletR ...

  3. 使用tcpdump拦截linux服务端网络数据

    语法范例: tcpdump -vv -i ens3 '((tcp)&&(host 183.239.240.48)&&(port 3001))'  -c 100 -w 1 ...

  4. arcgis10.0 切片并发布服务及验证

    1.切片参考网址:https://jingyan.baidu.com/article/fa4125accc6bef28ac7092d7.html 2.通过下面代码验证  参考网址https://www ...

  5. springMvc接口开发--对访问的restful api接口进行拦截实现功能扩展

    1.视频参加Spring Security开发安全的REST服务\PART1\PART1 3-7 使用切片拦截REST服务三通it学院-www.santongit.com-.mp4 讲的比较的经典,后 ...

  6. 关于ArcGIS Server修改数据源是否对切片服务有影响

    感谢一路走来默默支持和陪伴的你~~~ ------------------欢迎来访,拒绝转载------------------- (一)问题: 一直有人问一个问题: 1.我发布了切片的地图服务一以后 ...

  7. 使用GeoServer+OpenLayers发布和调用WMTS、Vector Tile矢量切片服务 | Publishing and Calling WMTS, Vector Tile Service Using GeoServer + OpenLayers

    Web GIS系列: 1.搭建简易Web GIS网站:使用GeoServer+PostgreSQL+PostGIS+OpenLayers3 2.使用GeoServer+QGIS发布WMTS服务 3.使 ...

  8. 【springboot】过滤器、监听器、拦截器,Aspect切片

    转自: https://blog.csdn.net/cp026la/article/details/86501019 简介: 本章介绍拦截器.过滤器.切片对请求拦截的使用与区别,以及监听器在 spri ...

  9. Struts2拦截器的使用 (详解)

    Struts2拦截器的使用 (详解) 如何使用struts2拦截器,或者自定义拦截器.特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈default ...

随机推荐

  1. 对话框改变颜色 宽度沾满屏幕 Dialog

    首先在style.xml中定义一个对话框样式,这里可以修改颜色: //对话框沾满整个屏幕的宽度 <style name="DialogShareTheme" parent=& ...

  2. TZOJ 1693 Silver Cow Party(最短路+思维)

    描述 One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big ...

  3. 373. Find K Pairs with Smallest Sums 找出求和和最小的k组数

    [抄题]: You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. D ...

  4. redis使用规范文档 20170522版

    运维redis很久了,一直是口头给rd说各种要求,尝试把这些规范总结成文档 摘选一些可能比较通用的规则如下: 强制:所有的key设置过期时间(最长可设置过期时间10天,如有特殊要求,联系dba说明原因 ...

  5. [字符串][NOIP2012]Vigenère密码

    Vigenère密码 题目描述 16世纪法国外交家Blaise de Vigenère设计了一种多表密码加密算法——Vigenère密码.Vigenère密码的加密解密算法简单易用,且破译难度比较高, ...

  6. 模板学习实践二 pointer

    c++ template学习记录 使用模板将实际类型的指针进行封装 当变量退出作用域 自动delete // 1111.cpp : 定义控制台应用程序的入口点. // #include "s ...

  7. ibatis (六) dynamic的用法

    view plain copy print? dynamic可以去除第一个prepend="and"中的字符(这里为and),从而可以帮助你实现一些很实用的功能.具体情况如下: 1 ...

  8. Alpha 冲刺 (10/10)

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 测试整体软件 展示GitHub当 ...

  9. HTML5 添加新的标签 input属性

    <!-- 新增 有语意标签 --> <nav></nav> <!-- 导航标签 --> <seclion></seclion> ...

  10. GDB基础学习

    GDB基础学习 要调试C/C++程序,首先在编译时,我们必须要把调试信息加到可执行文件中.使用编译器(cc/gcc/g++)的-g参数可以做到这一点,比如: gcc -g test.c -o test ...