Spring boot 集成三种拦截方式
三种拦截方式分别为:
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 集成三种拦截方式的更多相关文章
- Spring boot 集成三种定时任务方式
三种定时任务方式分别为 org.springframework.scheduling.annotation.Scheduled java.util.concurrent.ScheduledExecut ...
- Spring Boot实践——三种拦截器的创建
引用:https://blog.csdn.net/hongxingxiaonan/article/details/48090075 Spring中的拦截器 在web开发中,拦截器是经常用到的功能.它可 ...
- spring Bean的三种配置方式
Spring Bean有三种配置方式: 传统的XML配置方式 基于注解的配置 基于类的Java Config 添加spring的maven repository <dependency> ...
- Spring Boot 项目几种启动方式
Spring Boot 项目几种启动方式 1. 使用 main 启动 jar xxxx.jar 2. 使用 mvn 启动 mvn spring-boot:run 3. 使用 Spring Boot c ...
- Spring IOC以及三种注入方式
IOC是spring的最基础部分,也是核心模块,Spring的其他组件模块和应用开发都是以它为基础的.IOC把spring的面向接口编程和松耦合的思想体现的淋漓尽致. IOC概念 IOC(Invers ...
- Spring IOC 中三种注入方式
项目错误知识点记录 正文 最近在项目的时候,用到Spring框架,Spring框架提供了一种IOC的自动注入功能,可以很轻松的帮助我们创建一个Bean,这样就省的我们四处写new Object()这样 ...
- Spring:Spring-IOC三种注入方式、注入不同数据类型
一.Spring IOC(依赖注入的三种方式): 1.Setter方法注入 package com.jpeony.spring.setter; import com.jpeony.spring.com ...
- Spring常用的三种注入方式
好文要收藏,摘自:https://blog.csdn.net/a909301740/article/details/78379720 Spring通过DI(依赖注入)实现IOC(控制反转),常用的注入 ...
- spring Bean的三种注入方式
1.构造函数注入: 构造函数的注入方式分为很多种 (1)普通构造函数,空参数的构造函数 <bean id="exampleBean" class="examples ...
随机推荐
- java字符串转Date
public static Date StrToDate(String str) { SimpleDateFormat format = new SimpleDateFormat("yyyy ...
- red5服务器基础之red5环境的安装配置
red5的官网地址http://red5.org/ 下载完成之后解压 在系统变量配置RED5_HOME 在浏览器里输入 http://localhost:5080/ 配置ip地址在安装目录D:\red ...
- Android Studio CMake 生成多个so
生成多个so案例 这里stringFromJNI和stringFromJNI11分别是调用one-lib和two-lib两个so package com.test.ndkmoreso; import ...
- 3d Max 2018安装失败怎样卸载3dsmax?错误提示某些产品无法安装
AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...
- java 多线程 yield方法的意义
Thread.yield( )方法: 使当前线程从执行状态(运行状态)变为可执行态(就绪状态).cpu会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一 ...
- keepalived双机热备实现故障时发送邮件通知
目前项目已经采用nginx来实现负载均衡,但是nginx调度器只有一台,上次还意外的down机一次,导致整个服务应用全部瘫痪,这次准备再加一个调度器来实现站点高可用性,也就是常说的双机热备了. mas ...
- hibernate课程 初探一对多映射1-1 课程简介
hibernate 常见映射类型 one-to-many many-to-one one-to-one many-to-many
- vue2 关于ref
1,VUE2子组件索引 <div id="app"> <navbar></navbar> <pagefooter></page ...
- HTML图片映射实用
大图的不同点击区域实现不同的超链接: <img src="planets.gif" width="145" height="126" ...
- sharepoint2007就地升级2010系列(五)升级到sharepoint2010
---恢复内容结束--- 大家下午好 今天我们来完成最后一步,sharepoint2007升级2010.其实我反倒没有那么紧张了,因为我最担心的数据库升级,已经过了. OK,话不多说,让我们直接开始吧 ...