今天学习一下RESTFul api拦截

大概有三种方式

一、通过Filter这个大家很熟悉了吧,这是java规范的一个过滤器,他会拦截请求。在springboot中一般有两种配置方式。

这种过滤器拦截并不知道你用的是哪一个Controller处理也不知道你用哪一个方法处理。

(1)第一种直接写类实现这个接口。代码如下这个要使用Component注解,当你你请求服务器的时候他会对每一个请求进行处理。

package com.nbkj.webFilter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.util.Date; @Component
public class TimerFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Time filter init");
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("Time filter start");
long startTime = new Date().getTime();
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("time filter:"+(new Date().getTime()-startTime));
System.out.println("time filter finish");
} @Override
public void destroy() {
System.out.println("Time filter destroy");
}
}

(2)第二种可以在WebConfig中配置,这种配置方式为了使用第三方的Filter没有@Compont注解所以使用。代码如下

package com.nbkj.config;

import com.nbkj.webFilter.TimerFilter;
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; /**
* Web配置
*
* @author hsj
* @Configuration 这个注解声明这个类是配置类
* @create 2017-11-11 18:00
**/ @Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean timeFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimerFilter timerFilter = new TimerFilter();
registrationBean.setFilter(timerFilter);
List<String> urls = new ArrayList<>();
urls.add("/*");
registrationBean.setUrlPatterns(urls);
return registrationBean;
}
}

二、使用Interceptor这种事spring框架自己带的拦截器,代码如下 它会处理自己写的拦截器,也会拦截的拦截BasicErrorController

可以拿到处理的Controller和拿到处理的方法 但是拿不到具体的请求参数。

package com.nbkj.interceptor;

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.persistence.Convert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date; /**
* this is spring interceptor
*
* @author hsj
* @create 2017-11-11 18:16
**/ @Component
public class TimeInterceptor implements HandlerInterceptor { /**
* 控制器方法处理之前
*
* @param httpServletRequest
* @param httpServletResponse
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
System.out.println("preHandle");
System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
System.out.println(((HandlerMethod) handler).getMethod().getName());
httpServletRequest.setAttribute("startTime", new Date().getTime());
return false;
} /**
* 控制器方法处理之后
* 控制器方法调用不抛异常调用
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
Long startTime = (Long) httpServletRequest.getAttribute("startTime");
System.out.println("time interceptor 耗时" + (new Date().getTime() - startTime));
} /**
* 控制器方法抛不抛异常都会被调用
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion");
Long startTime = (Long) httpServletRequest.getAttribute("startTime");
System.out.println("time interceptor 耗时" + (new Date().getTime() - startTime));
System.out.println("ex is" + e);
}
}
package com.nbkj.config;

import com.nbkj.interceptor.TimeInterceptor;
import com.nbkj.webFilter.TimerFilter;
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; /**
* Web配置
*
* @author hsj
* @Configuration 这个注解声明这个类是配置类
* @create 2017-11-11 18:00
**/ @Configuration
public class WebConfig extends WebMvcConfigurerAdapter { @Autowired
private TimeInterceptor timeInterceptor; @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timeInterceptor);
} }

三、使用Aspect切片,代码如下

使用环绕通知,切入要切入的类,当请求的时候回拦截下来,这样可以获取拦截的方法的参数

package com.nbkj.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; import java.util.Date; /**
* this is a acpect
* 切入点
* 在那些方法上起作用
* 在什么时候起作用
*
* @author hsj
* @create 2017-11-11 20:52
**/
@Aspect
@Component
public class TimeAspect {
@Around("execution(* com.nbkj.controller.UserController.*(..))")
public Object handleControllerMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("time aspect start");
Object[] args = proceedingJoinPoint.getArgs();
for (Object arg : args) {
System.out.println(arg.getClass().getName());
System.out.println("arg is " + arg);
}
long startTime = new Date().getTime();
Object obj = proceedingJoinPoint.proceed();
System.out.println("time aspect 耗时" + (new Date().getTime() - startTime));
System.out.println("time aspect end");
return obj;
}
}

过滤器(Filter)         :可以拿到原始的http请求,但是拿不到你请求的控制器和请求控制器中的方法的信息。

拦截器(Interceptor):可以拿到你请求的控制器和方法,却拿不到请求方法的参数。

切片   (Aspect)       :  可以拿到方法的参数,但是却拿不到http请求和响应的对象

spring boot RESTFul API拦截 以及Filter和interceptor 、Aspect区别的更多相关文章

  1. 使用 JSONDoc 记录 Spring Boot RESTful API

    这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...

  2. 过滤器和拦截器filter和Interceptor的区别

    1.创建一个Filter过滤器只需两个步骤 创建Filter处理类 web.xml文件中配置Filter 2.Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的 ...

  3. Spring Boot & Restful API 构建实战!

    作者:liuxiaopeng https://www.cnblogs.com/paddix/p/8215245.html 在现在的开发流程中,为了最大程度实现前后端的分离,通常后端接口只提供数据接口, ...

  4. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值

    本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器. 如果对Spring中的RESTful不太明白,请查看相关书籍 1.创建一个数据对象, ...

  5. Spring Boot - Restful API

    基本用法 @GetMapping与@PostMapping不指定参数时就是指直接使用到controller一级的url就行 @GetMapping与@PathVariable对应,前者{}中的字符串和 ...

  6. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】06、Mybatis+SQLServer集成

    1.增加POM依赖 注意pagehelper插件,我重写过,可以到我的这篇文章了解https://www.cnblogs.com/LiveYourLife/p/9176934.html <dep ...

  7. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】05、Shiro集成

    1.POM文件中加入Shiro和fastJSON依赖 <dependency> <groupId>org.apache.shiro</groupId> <ar ...

  8. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】04、统一处理异常

    本节讨论如何使用Spring的异常处理机制,当我们程序出现错误时,以相同的一种格式,把错误信息返回给客户端 1.创建一些自定义异常 public class TipsException extends ...

  9. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】01、环境准备

    开发环境 windows+STS(一个针对Spring优化的Eclipse版本)+Maven+SQLServer 环境部署 1.安装SQLServer(使用版本2008R2) 自行安装,此处略过 2. ...

随机推荐

  1. Protocol Buffer序列化对比Java序列化.

    初识 Protocol Buff是谷歌推出的一种序列化协议. 而Java序列化协议也是一种协议. 两者的目的是, 将对象序列化成字节数组, 或者说是二进制数据, 那么他们之间有什么差异呢. proto ...

  2. JavaScript tips ——搞定闰年

    前言 处理时间时,常常要考虑用户的输入是否合法,其中一个很典型的场景就是平闰年的判断,网上其实有很多类似的算法,但是其实不必那么麻烦,下面我讲讲的我的思路. 规则 公元年数可被4整除为闰年,但是整百( ...

  3. Spring Boot系列(一) Spring Boot介绍和基础POM文件

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过 ...

  4. html页面高度自适应

    本文实现的效果是依据浏览器分辨率的不同.页面底端背景色自适应浏览器高度,也就是能够自己主动填充背景色. <script type="text/javascript"> ...

  5. 爬虫新手学习2-爬虫进阶(urllib和urllib2 的区别、url转码、爬虫GET提交实例、批量爬取贴吧数据、fidder软件安装、有道翻译POST实例、豆瓣ajax数据获取)

    1.urllib和urllib2区别实例 urllib和urllib2都是接受URL请求相关模块,但是提供了不同的功能,两个最显著的不同如下: urllib可以接受URL,不能创建设置headers的 ...

  6. 获取spring容器上下文(webApplicationContext)的几种方法

    在很多情况,我们需要先获取spring容器上下文,即webApplicationContext,然后通过webApplicationContext来获取其中的bean.典型的情况是,我想在一个并未委托 ...

  7. Spring Boot [使用 Druid 数据库连接池]

    导读 最近一段时间比较忙,以至于很久没有更新Spring Boot系列文章,恰好最近用到Druid, 就将Spring Boot 使用 Druid作为数据源做一个简单的介绍. Druid介绍: Dru ...

  8. IIS 5.x与ASP.NET

    转自:http://www.cnblogs.com/artech/archive/2009/06/20/1507165.html 我们先来看看IIS 5.x是如何处理基于ASP.NET资源(比如.as ...

  9. ES6作用域和解构赋值

    ES6 强制开启严格模式 作用域 var 声明局部变量,for/if花括号中定义的变量在花括号外也可访问 let 声明的变量为块作用域,变量不可重复定义 const 声明常量,块作用域,声明时必须赋值 ...

  10. qt调用simsimi api实现小黄鸡

    项目地址:https://github.com/racaljk/xiaojianji 好吧我把它命名为小贱鸡.,下面说一说他的实现. 由于官方的simsimi api需要收费,免费试用版有各种限制,所 ...