三种拦截方式分别为:

  javax.servlet.Filter
org.springframework.web.servlet.HandlerInterceptor
org.aspectj.lang.annotation.Aspect

拦截先后顺序

客户端请求 --》 Filter  --》 HandlerInterceptor  --》  Aspect  --》 目标方法  --》 Aspect  --》 HandlerInterceptor --》 Filter --》 客户端

示例如下:

1.   新建Maven项目  interceptor

2.   pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.java</groupId>
<artifactId>interceptor</artifactId>
<version>1.0.0</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent> <dependencies> <!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency> <!-- 热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency> </dependencies> <build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

3.   InterceptorStarter.java

package com.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class InterceptorStarter { public static void main(String[] args) {
SpringApplication.run(InterceptorStarter.class, args);
} }

4.   DemoController.java

package com.java.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/demo")
public class DemoController { @GetMapping("/getHostMessage")
public Map<String, Object> getHostMessage(String type, String age) {
Map<String, Object> map = new HashMap<>(); System.out.println();
System.out.println("type: " + type);
System.out.println(); // 测试异常情况
if ("exception".equals(type)) {
throw new RuntimeException("异常演习!");
}
try {
InetAddress serverHost = InetAddress.getLocalHost();
map.put("hostName", serverHost.getHostName());
map.put("hostAddress", serverHost.getHostAddress());
map.put("type", type);
map.put("age", age);
} catch (UnknownHostException e) {
e.printStackTrace();
} return map;
} }

5.   DemoFilter.java

package com.java.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; /**
* <blockquote>
*
* <pre>
* 请求拦截过滤器
*
* 1. 开启 @Component 注解便可启用拦截功能
* 2. 不开启 @Component 可通过FilterRegistrationBean 设置注册到 @Configuration 注解的配置类中
*
* </pre>
*
* </blockquote>
*
*/
//@Component // 不开启注解时可以通过配置启动
public class DemoFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化DemoFilter");
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println(String.format("[ DemoFilter ] [ Into %s ]", req.getRequestURI())); chain.doFilter(request, response); System.out.println(String.format("[ DemoFilter ] [ Exit %s ]", req.getRequestURI()));
} @Override
public void destroy() {
System.out.println("销毁DemoFilter");
} }

6.    DemoInterceptor.java

package com.java.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; @Component
public class DemoInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(String.format("\n[ DemoInterceptor ] [ Into %s ]", request.getRequestURI()));
System.out.println("[ preHandle ]"); System.out.println(((HandlerMethod) handler).getBeanType().getName());
System.out.println(((HandlerMethod) handler).getMethod().getName()); return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("[ postHandle ] 抛出异常时不执行");
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
System.out.println("[ afterCompletion ]");
System.out.println("Exception is " + e); // 抛出异常时Content-Type为 text/html;charset=ISO-8859-1
if (null != e) {
response.setContentType("text/html;charset=UTF-8");
} System.out.println(String.format("[ DemoInterceptor ] [ Exit %s ]\n", request.getRequestURI()));
} }

7.   DemoAspect.java

package com.java.interceptor;

import java.util.Arrays;

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.springframework.stereotype.Component; @Aspect
@Component
public class DemoAspect { @Around("execution(* com.java.controller..*.*(..))")
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println(String.format("\n[ DemoAspect ] [ Into %s ]", point.getSignature())); System.out.println(Arrays.toString(point.getArgs()));
Object object = point.proceed(); System.out.println(String.format("[ DemoAspect ] [ Exit %s ]\n", point.getSignature()));
return object;
} @AfterThrowing(pointcut = "execution(* com.java.controller..*.*(..))", throwing = "e")
public void afterThrowing(Throwable e) {
System.out.println(String.format("[ DemoAspect ] %s\n", e));
} }

8.   WebConfig.java

package com.java.config;

import javax.servlet.Filter;

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.WebMvcConfigurer; import com.java.interceptor.DemoFilter;
import com.java.interceptor.DemoInterceptor; @Configuration
public class WebConfig implements WebMvcConfigurer { @Autowired
private DemoInterceptor demoInterceptor; @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(demoInterceptor);
} @Bean
public FilterRegistrationBean<Filter> demoFilter() { FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); DemoFilter demoFilter = new DemoFilter();
registrationBean.setFilter(demoFilter);
registrationBean.addUrlPatterns("/*"); return registrationBean; } }

9.   运行InterceptorStarter.java, 启动测试

浏览器输入 http://localhost:8080/demo/getHostMessage?age=16&type=normal

返回结果如下:

{"hostName":"Logan","hostAddress":"192.168.1.101","type":"normal","age":"16"}

查看控制台打印信息如下:

[ DemoFilter ] [ Into /demo/getHostMessage ]

[ DemoInterceptor ] [ Into /demo/getHostMessage ]
[ preHandle ]
com.java.controller.DemoController
getHostMessage [ DemoAspect ] [ Into Map com.java.controller.DemoController.getHostMessage(String,String) ]
[normal, 16] type: normal [ DemoAspect ] [ Exit Map com.java.controller.DemoController.getHostMessage(String,String) ] [ postHandle ] 抛出异常时不执行
[ afterCompletion ]
Exception is null
[ DemoInterceptor ] [ Exit /demo/getHostMessage ] [ DemoFilter ] [ Exit /demo/getHostMessage ]

异常场景测试,浏览器输入http://localhost:8080/demo/getHostMessage?age=16&type=exception

返回结果自行研究。

三种拦截功能拦截顺序为:

客户端请求 --》 Filter  --》 HandlerInterceptor  --》  Aspect  --》 目标方法  --》 Aspect  --》 HandlerInterceptor --》 Filter --》 客户端

.

Spring boot 集成三种拦截方式的更多相关文章

  1. Spring boot 集成三种定时任务方式

    三种定时任务方式分别为 org.springframework.scheduling.annotation.Scheduled java.util.concurrent.ScheduledExecut ...

  2. Spring Boot实践——三种拦截器的创建

    引用:https://blog.csdn.net/hongxingxiaonan/article/details/48090075 Spring中的拦截器 在web开发中,拦截器是经常用到的功能.它可 ...

  3. spring Bean的三种配置方式

    Spring Bean有三种配置方式: 传统的XML配置方式 基于注解的配置 基于类的Java Config 添加spring的maven repository <dependency> ...

  4. Spring Boot 项目几种启动方式

    Spring Boot 项目几种启动方式 1. 使用 main 启动 jar xxxx.jar 2. 使用 mvn 启动 mvn spring-boot:run 3. 使用 Spring Boot c ...

  5. Spring IOC以及三种注入方式

    IOC是spring的最基础部分,也是核心模块,Spring的其他组件模块和应用开发都是以它为基础的.IOC把spring的面向接口编程和松耦合的思想体现的淋漓尽致. IOC概念 IOC(Invers ...

  6. Spring IOC 中三种注入方式

    项目错误知识点记录 正文 最近在项目的时候,用到Spring框架,Spring框架提供了一种IOC的自动注入功能,可以很轻松的帮助我们创建一个Bean,这样就省的我们四处写new Object()这样 ...

  7. Spring:Spring-IOC三种注入方式、注入不同数据类型

    一.Spring IOC(依赖注入的三种方式): 1.Setter方法注入 package com.jpeony.spring.setter; import com.jpeony.spring.com ...

  8. Spring常用的三种注入方式

    好文要收藏,摘自:https://blog.csdn.net/a909301740/article/details/78379720 Spring通过DI(依赖注入)实现IOC(控制反转),常用的注入 ...

  9. spring Bean的三种注入方式

    1.构造函数注入: 构造函数的注入方式分为很多种 (1)普通构造函数,空参数的构造函数 <bean id="exampleBean" class="examples ...

随机推荐

  1. 谷歌Chrome浏览器离线安装包

    下载地址(自选版本) 链接: https://pan.baidu.com/s/1_gVP32tBNTR0pHhQbbM8Iw 密码: rmak 有能力的可以自行到下方地址下载: 最新稳定版:https ...

  2. my.助战选择

    ZC:我的选项:铁扇.小白龙.北海龙女.北海龙子(涌浪).老鼠精(避敌锋芒).惠岸.银角 ZC:我的选择(日常速推不是我急需的,慢一点无所谓,我需要过难度):老鼠精(避敌锋芒).银角(首回合隐身,每回 ...

  3. vue proxyTable 接口跨域请求调试(五)

    在不同域之间访问是比较常见,在本地调试访问远程服务器....这就是有域问题. VUE解决通过proxyTable: 在 config/index.js 配置文件中 dev: { env: requir ...

  4. Android官方架构组件介绍之ViewModel(三)

    ViewModel 像Activity,Fragment这类应用组件都有自己的生命周期并且是被Android的Framework所管理的.Framework可能会根据用户的一些操作和设备的状态对Act ...

  5. HBuilder的常用快捷键

    Ctrl + d 删除整行内容 Ctrl + Shift +R 复制当前行到下一行 Ctrl + Shift +D 重新编辑 Ctrl + 方向键 当前行整行内容上移或下移 Alt + ↓ 跳转到下一 ...

  6. sql查询约束

    写作业的时候发现书上竟然找不到查询约束的语句,百度搜了好久的资料,终于查询成功,在这里记录下来 主键约束 SELECT   tab.name AS [表名],   idx.name AS [主键名称] ...

  7. input元素的blur事件与定位在其上面的元素的点击(click)事件冲突的解决方法

    在登录和注册框中,在input上定位一个清空内容的按钮. 但是给按钮的单击事件不生效. 解决的办法: 在blur的回调函数中加一个定时器,延迟blur回调函数的执行时间,这样的话虽然在点击div的时候 ...

  8. Java基础01-JVM内存分析

    JVM java虚拟机 java编译后的class文件就是在java虚拟机上运行的 1.栈区(stacksegment)存放函数的参数值,局部变量的值等,在超过这个变量的作用域时就会被系统自动释放掉存 ...

  9. vue进阶 --- 实例演示

    这篇博客将通过一个实例来对vue构建项目的过程有一个了解. 主要用到的知识点如下所示: vue-router 2.0路由配置 router-view 和 router-link的使用 transiti ...

  10. ruby中的类实例变量和实例的实例变量

    ruby中有实例变量这个语法,有点类似java的对象的属性,但是ruby中类也有实力变量, class Person @name = 'hello' def initialize(name,age) ...