


Introduction to methods of implementing filters, listeners, and interceptors through SpringBoot in java
This article mainly introduces SpringBoot's method of defining filters, listeners, and interceptors. It has certain reference value. Those who are interested can learn more.
1. Custom filter
Create a filter, implement the javax.servlet.Filter interface, and rewrite the init, doFilter, destroy methods.
package com.example.filter; 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.annotation.WebFilter; /** * 实现javax.servlet.Filter,覆盖其三个方法 * @author Administrator * */ @WebFilter(filterName="customFilter",urlPatterns="/*") public class CustomFilter implements Filter{ @Override public void destroy() { System.out.println("CustomFilter过滤器销毁"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("CustomFilter指定过滤器操作......"); //执行操作后必须doFilter chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("CustomFilter初始化......"); } }
2. Custom listener
Create a filter and implement the ServletContextListener interface
package com.example.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * 实现ServletContextListener,覆盖其两个方法 * @author Administrator * */ @WebListener public class CustomListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent servletContext) { System.out.println("servletContext销毁......"); } @Override public void contextInitialized(ServletContextEvent servletContext) { System.out.println("servletContext初始化......"); } }
Create asessionListener, monitors the creation and destruction of session
package com.example.listener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * 实现HttpSessionListener接口,监视session的动态 * @author Administrator * */ @WebListener public class SessionListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent session) { System.out.println("session创建成功......"); } @Override public void sessionDestroyed(HttpSessionEvent session) { System.out.println("session销毁......"); } }
3. Custom interceptor
Steps:
1. Create your own interceptor to implement the HandlerInterceptor interface
2. Create your own interceptor chain, inherit the WebMvcConfigurerAdapter class, and override the addInterceptors method.
3. Instantiate your own interceptor and add it to the interceptor chain.
Interceptor one:
package com.example.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class CustomInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception { //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作) System.out.println("3. 整个请求结束之后被调用......CustomInterceptor1......"); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView view) throws Exception { // 请求处理之后进行调用,但是在视图被渲染之前 System.out.println("2. 请求处理之后进行调用,但是在视图被渲染之前......CustomInterceptor1......"); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { // 在请求处理之前进行调用 System.out.println("1. 在请求处理之前进行调用......CustomInterceptor1......"); // 只有返回true才会继续向下执行,返回false取消当前请求 return true; } }
Interceptor two:
package com.example.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class CustomInterceptor2 implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception { //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作) System.out.println("3. 整个请求结束之后被调用......CustomInterceptor2......"); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView view) throws Exception { // 请求处理之后进行调用,但是在视图被渲染之前 System.out.println("2. 请求处理之后进行调用,但是在视图被渲染之前......CustomInterceptor2......"); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { // 在请求处理之前进行调用 System.out.println("1. 在请求处理之前进行调用......CustomInterceptor2......"); // 只有返回true才会继续向下执行,返回false取消当前请求 return true; } }
Customize the interceptor chain and add the custom interceptor
package com.example.adapter; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.example.Interceptor.CustomInterceptor; import com.example.Interceptor.CustomInterceptor2; /** * 继承WebMvcConfigurerAdapter,复写addInterceptors方法 * @author Administrator * */ @Configuration public class WebAdapter extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { //众多的拦截器组成了一个拦截器链 /** * 主要方法说明: * addPathPatterns 用于添加拦截规则 * excludePathPatterns 用户排除拦截 */ registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/*"); registry.addInterceptor(new CustomInterceptor2()).addPathPatterns("/*"); super.addInterceptors(registry); } }
The above is the detailed content of Introduction to methods of implementing filters, listeners, and interceptors through SpringBoot in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![Windows ISO file too large BootCamp error [Fixed]](https://img.php.cn/upload/article/000/887/227/170831702395455.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
If you get the error message "The Windows ISO file is too large" when using BootCampAssistant on a Mac computer, this may be because the ISO file size exceeds the limit supported by BootCampAssistant. The solution to this problem is to use other tools to compress the ISO file size to ensure that it can be processed in BootCamp Assistant. BootCampAssistant is a convenient tool provided by Apple for installing and running Windows operating system on Mac computers. It helps users set up a dual-boot system, allowing them to easily choose to use MacOS or Wind at startup

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Interceptor is a design pattern that allows custom behavior to be inserted before and after method execution. In Go, it can be implemented through net/http middleware. It has the advantages of scalability, reusability, testability, etc., and can be used in scenarios such as authentication, authorization, caching, logging, and custom error handling.

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

Detailed explanation of the Bean acquisition method in Spring In the Spring framework, Bean acquisition is a very important part. In applications, we often need to use dependency injection or dynamically obtain instances of beans. This article will introduce in detail how to obtain beans in Spring and give specific code examples. Obtaining the Bean@Component annotation through the @Component annotation is one of the commonly used annotations in the Spring framework. We can do this by adding @Compone on the class
