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. 整合SpringMVC框架和Spring框架

    -------------------------siwuxie095                                 整合 SpringMVC 框架和 Spring 框架       ...

  2. 关于java中分割字符串

    例子:String path = "123.456.789"; 如果要使用“.”将path分割成String[], path.split("//."); or ...

  3. [leetcode]339. Nested List Weight Sum嵌套列表加权和

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  4. [leetcode]49. Group Anagrams变位词归类

    Given an array of strings, group anagrams together. Example: Input: ["eat", "tea" ...

  5. PAT 甲级 1002 A+B for Polynomials (25 分)

    1002 A+B for Polynomials (25 分) This time, you are supposed to find A+B where A and B are two polyno ...

  6. C++学习札记(2)

    重载构造函数 #include <iostream> using namespace std; class rectangle { public: rectangle(){cout< ...

  7. unbuntu 安装 teamviewer

    下载 teamviewer 安装包 使用 dpkg 安装 deb 安装包 使用 sudo apt-get install -f 解决依赖问题

  8. 走进JDK(二)------String

    本文基于java8. 基本概念: Jvm 内存中 String 的表示是采用 unicode 编码 UTF-8 是 Unicode 的实现方式之一 一.String定义 public final cl ...

  9. okhttp 调用相机 上传服务器

    MainActivity package com.bwie.lianxi1; import android.content.Intent; import android.database.Cursor ...

  10. Java并发编程:CountDownLatch、CyclicBarrier和 Semaphore

    原文出处: 海子 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch,CyclicBarrier和Semaphore,今天我们就来学习一下这三个辅 ...