springboot中过滤器、拦截器、切片使用
直接贴代码:采用maven工程
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.theorydance</groupId>
<artifactId>springbootdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springbootdemo</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加切片AOP依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
com.theorydance.springbootdemo.conf.DemoFilter.java
package com.theorydance.springbootdemo.conf; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter; /**
* 这里添加WebFilter注解,然后再启动类上添加ServletComponentScan注解
* 能匹配/demoController/*,不会匹配/demoController2/*
*/
@WebFilter(filterName="FirstFilter",urlPatterns = {"/demoController/*"})
public class DemoFilter implements Filter{ @Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
System.out.println("this is demoFilter before.....");
chain.doFilter(req, resp);
System.out.println("this is demoFilter after.....");
} }
com.theorydance.springbootdemo.conf.DemoHandlerInterceptor.java
package com.theorydance.springbootdemo.conf; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; @Component
public class DemoHandlerInterceptor implements HandlerInterceptor{ @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("this is DemoHandlerInterceptor preHandle.....");
return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("this is DemoHandlerInterceptor postHandle.....");
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("this is DemoHandlerInterceptor afterCompletion.....");
} }
com.theorydance.springbootdemo.conf.DemoLogAspect.java, 切片参考博客:https://www.jianshu.com/p/efbc657e034c
package com.theorydance.springbootdemo.conf; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; @Aspect
@Component
public class DemoLogAspect { // Pointcut("execution(public * com.theorydance.springbootdemo..*.*(..))")
@Pointcut("execution(public * com.theorydance.springbootdemo.service.DemoService.*(..))")
public void demolog() {} @Before("demolog()")
public void doBefore(JoinPoint joinPoint) throws Throwable{
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
} @AfterReturning(returning = "ret", pointcut = "demolog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
System.out.println("RESPONSE : " + ret);
} }
com.theorydance.springbootdemo.conf.MvcInterceptorConfig.java
package com.theorydance.springbootdemo.conf; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration
public class MvcInterceptorConfig extends WebMvcConfigurationSupport{ @Autowired
private DemoHandlerInterceptor demoHandlerInterceptor; @Override
protected void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
// excludePathPatterns 用户排除拦截
registry.addInterceptor(demoHandlerInterceptor).addPathPatterns("/demoController/**")
.excludePathPatterns("/demoController/demo2");
super.addInterceptors(registry);
} }
com.theorydance.springbootdemo.controller.DemoController.java
package com.theorydance.springbootdemo.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.theorydance.springbootdemo.service.DemoService; @RestController
@RequestMapping("/demoController")
public class DemoController { @Resource
private DemoService demoService; @RequestMapping(value="/demo1",method=RequestMethod.GET)
public void demo1(){
System.out.println("this is demoController.demo1()");
demoService.doSomething();
} @RequestMapping(value="/demo2",method=RequestMethod.GET)
public void demo2(){
System.out.println("this is demoController.demo2()");
demoService.doSomething();
} }
com.theorydance.springbootdemo.controller.DemoController2.java
package com.theorydance.springbootdemo.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.theorydance.springbootdemo.service.DemoService; @RestController
@RequestMapping("/demoController2")
public class DemoController2 { @Resource
private DemoService demoService; @RequestMapping(value="/demo1",method=RequestMethod.GET)
public void demo1(){
System.out.println("this is demoController2.demo1()");
demoService.doSomething();
} @RequestMapping(value="/demo2",method=RequestMethod.GET)
public void demo2(){
System.out.println("this is demoController2.demo2()");
demoService.doSomething("theorydance");
} }
com.theorydance.springbootdemo.service.DemoService.java
package com.theorydance.springbootdemo.service; import org.springframework.stereotype.Service; @Service
public class DemoService { public String doSomething(String...strs) {
System.out.println("this is DemoService.doSomething()");
return null;
} }
启动类com.theorydance.springbootdemo.DemoApplication.java
package com.theorydance.springbootdemo; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication
@ServletComponentScan
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }
测试效果,主要是访问对应的url,来查看控制台输出日志的情况
springboot中过滤器、拦截器、切片使用的更多相关文章
- 在springboot中使用拦截器
在springMVC中可以实现拦截器,是通过实现HandlerInterceptor接口,然后在springmvc-web.xml中配置就可以使用拦截器了.在springboot中拦截器也是一样的思想 ...
- springmvc以及springboot中的拦截器配置
拦截器两种实现 如果不同的controller中都需要拦截器,不能使用相同的拦截器,因为拦截器不能跨controller,这个时候只能为不同的controller配置不同的拦截器,每一个拦截器只能 ...
- springboot中使用拦截器、监听器、过滤器
拦截器.过滤器.监听器在web项目中很常见,这里对springboot中怎么去使用做一个总结. 1. 拦截器(Interceptor) 我们需要对一个类实现HandlerInterceptor接 ...
- Springboot中SpringMvc拦截器配置与应用(实战)
一.什么是拦截器,及其作用 拦截器(Interceptor): 用于在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,其实就是AOP的一种实现策略.它通过动态拦截Action调用的对 ...
- springboot jsp,过滤器,拦截器
springboot使用jsp,过滤器,拦截器(拦截器与过滤器区别重点) jsp使用配置 一 创建springboot项目在maven中暂时只添加两个Dependencies :devtools(热部 ...
- 解决 Springboot中Interceptor拦截器中依赖注入失败
问题: 在Springboot拦截器Interceptor中使用@Resource依赖注入时,发现运行的时候被注解的对象居然是null,没被注入进去 原配置为: @Configurationpubli ...
- springboot中使用拦截器
5.1 回顾SpringMVC使用拦截器步骤 自定义拦截器类,实现HandlerInterceptor接口 注册拦截器类 5.2 Spring Boot使用拦截器步骤 5.2.1 按照S ...
- springboot(五).如何在springboot项目中使用拦截器
在每个项目中,拦截器都是我们经常会去使用的东西,基本上任一一个项目都缺不了拦截器的使用. 如日志记录.登录验证,session验证等,都需要拦截器来拦截URL请求,那springboot中的拦截器是如 ...
- 过滤器 ;spring拦截器 切片 小结
1. springMVc的拦截器 实现HandlerInterceptor接口,如下: public class HandlerInterceptor1 implements HandlerInter ...
- JavaWeb中监听器+过滤器+拦截器区别、配置和实际应用
JavaWeb中监听器+过滤器+拦截器区别.配置和实际应用 1.前沿上一篇文章提到在web.xml中各个元素的执行顺序是这样的,context-param-->listener-->fil ...
随机推荐
- Spring源码之IOC容器创建、BeanDefinition加载和注册和IOC容器依赖注入
总结 在SpringApplication#createApplicationContext()执行时创建IOC容器,默认DefaultListableBeanFactory 在AbstractApp ...
- 基于Docker UI 配置ceph集群
前言 前一篇介绍了docker在命令行下面进行的ceph部署,本篇用docker的UI进行ceph的部署,目前来说市面上还没有一款能够比较简单就能直接在OS上面去部署Ceph的管理平台,这是因为OS的 ...
- 如何获取流式应用程序中checkpoint的最新offset
对于流式应用程序,保证应用7*24小时的稳定运行,是非常必要的.因此对于计算引擎,要求必须能够适应与应用程序逻辑本身无关的问题(比如driver应用失败重启.网络问题.服务器问题.JVM崩溃等),具有 ...
- 免费|申请谷歌云服务器|msf安装
apt-get install -y wget 参考链接 知乎-免费|申请谷歌云服务器 知乎-免费|申请谷歌云服务器 cnblogs-debian.ubuntu安装metasploit通用方法 谷歌云 ...
- 使用ABBYY FineReader 手动校正文档复杂结构
ABBYY FineReader 15(Windows系统)拥有强大的OCR识别功能,能对扫描仪或者数码相机等光学工具获取的图像进行识别,解析其中的文本.图像.表格.条形码等,方便用户进一步获取图像中 ...
- 使用javaxmail发送文字邮件
package com.rupeng.javaMail; import java.util.Properties; import javax.mail.Authenticator;import jav ...
- python应用(2):写个python程序给自己用
用python写一个程序,然后在命令行上执行,看不到界面(UI),这种程序很常见了,叫命令行程序.然而很多人,特别是不懂程序的人,更需要看到的是一个有界面的,能通过鼠标操作的程序,毕竟已经迈进&quo ...
- 【ACwing 95】费解的开关——枚举 + 搜索
(题面来自ACwing) 你玩过"拉灯"游戏吗?25盏灯排成一个5x5的方形.每一个灯都有一个开关,游戏者可以改变它的状态.每一步,游戏者可以改变某一个灯的状态.游戏者改变一个灯的 ...
- 三. Vue组件化
1. 认识组件化 1.1 什么是组件化 人面对复杂问题的处理方式 任何一个人处理信息的逻辑能力都是有限的,所以当面对一个非常复杂的问题时我们不太可能一次性搞定一大堆的内容. 但是我们人有一种天生的能力 ...
- CentOS6.5&7更改开机启动时的CentOS标题
#现有CentOS6.5改以下配置文件 sed -i 's/CentOS/DntOS/g' /etc/centos-release sed -i 's/CentOS/DntOS/g' /etc/iss ...