当前位置: 首页 > news >正文

SpringBoot复习:(61)拦截器(HandlerInterceptor)的用法

一、自定义拦截器:

package cn.edu.tju.interceptor;import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class MyInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {System.out.println("Servlet path is : " +request.getServletPath());return true;}
}

二、通过WebMvcConfigurer配置拦截器

package cn.edu.tju.config;import cn.edu.tju.component.MyDateConverter;
import cn.edu.tju.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor());}
}

异常时,postHandle不会执行。afterCompletion会执行

过滤器先于拦截器执行。

package cn.edu.tju.config;import org.springframework.stereotype.Component;import javax.servlet.*;
import java.io.IOException;@Component
public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("in my filter【before]......");chain.doFilter(request, response);System.out.println("in my filter【after】......");}public void destroy() {System.out.println("after response......");}
}
package cn.edu.tju;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableScheduling
@ServletComponentScan
public class Start {public static void main(String[] args) {SpringApplication.run(Start.class, args);}
}
http://www.lryc.cn/news/159586.html

相关文章:

  • 【PyQT5教程】-01入门PyQT5
  • 判断字符串s是否为字符串t的子序列
  • 数据结构之队列的实现(附源码)
  • [A题]2023 年全国大学生数学建模比赛思路、代码更新中.....
  • Tailwind 练手项目
  • SpringMVC_SSM整合
  • 【操作系统】电脑上没有IIS怎么办
  • 【vue】vue项目中批量下载文件并打压缩包
  • Linux中的软件管家——yum
  • 安卓绘制原理概览
  • 接口测试工具开发文档
  • 面试题速记:JavaScript有哪些数据类型,它们的区别是?
  • Spring Cloud面试题
  • 计算机网络自顶向下-web页面请求历程
  • 打造西南交通感知新范式,闪马智能携手首讯科技落地创新中心
  • Android11去掉Settings中的网络和互联网一级菜单
  • 基于Python开发的五子棋小游戏(源码+可执行程序exe文件+程序配置说明书+程序使用说明书)
  • JDBC入门到精通-10w总结
  • Linux之查看so/bin依赖(三十一)
  • day-45 代码随想录算法训练营(19)动态规划 part 07
  • static关键字和final关键字
  • 使用Postman如何在接口测试前将请求的参数进行自定义处理
  • QT第二天
  • 鸿蒙应用程序入口UIAbility详解
  • 扫地僧站群·静态养站王:自动万站智能LOGO功能说明
  • 【Day-32慢就是快】代码随想录-二叉树-合并二叉树
  • 接口测试系列 —— 什么是接口测试?
  • qt作业day2
  • JWT一篇通
  • 【2023-09-01】vue中自定义按钮设置disabled属性后,异常触发click事件