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 ...
随机推荐
- java中对于浮点型数据操作
java的基本数据类型-浮点型:单精度(float)和双精度(double). float:单精度浮点数在机内占4个字节.有效数字8位.表示范围:-3.40E+38 ~ +3.40E+38; doub ...
- 这篇SpringBoot整合JSON的学习笔记,建议收藏起来,写的太细了
前言 JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛. 采用完全独立于编程语言的文本格式来存储和表示数据. 简洁和清晰 ...
- TA-Lib技术指标分析
import talib as tb from talib import * print(tb.get_functions()) print(tb.get_function_groups()) 指标大 ...
- 详解CorelDRAW中刻刀工具的具体运用
通过CorelDRAW,我们可以将一个对象拆分为两个对象,使用刻刀工具就可以将对象一分为二,保存为一个由两个或者多个子路径组成的对象,可以指定是否要自动闭合路径,或者是否一直将它们打开. CDR刻刀工 ...
- 【linux】串口通讯工具-minicom简介+简单操作
目录 前言 简介 尝试运行 配置 minicom 运行 minicom minicom 其它操作 前言 windows 上有不少的串口通信工具了,今天介绍一个linux下的一个串口通信工具-minic ...
- F - LCS 题解(最长公共子序列记录路径)
题目链接 题目大意 给你两个字符串,任意写出一个最长公共子序列 字符串长度小于3e3 题目思路 就是一个记录路径有一点要注意 找了好久的bug 不能直接\(dp[i][j]=dp[i-1][j-1]+ ...
- IPv6 Rapid Deployment, IPv6 6rd初探
IPv6 Rapid Deployment: Provide IPv6 Access to Customers over an IPv4-Only Network 原文地址:https://www.c ...
- 企业安全04-phpstudy最新版本nginx 默认存在任意文件解析漏洞
phpstudy最新版本nginx 默认存在任意文件解析漏洞 一.漏洞描述 phpStudy是一个PHP调试环境的程序集成包.该程序包集成最新的Apache+PHP+MySQL+phpMyAdmin+ ...
- 7-1 Hashing
The task of this problem is simple: insert a sequence of distinct positive integers into a hash tabl ...
- java顺序、选择、循环结构
一.顺序结构 二.选择结构 1.if都执行 2.if else if else 条件满足才执行 3.选择结构switch 一个case后有多条语句要加花括号 多个case的值不能相同 case中要加b ...