SpringBoot——过滤器、监听器(十)

简介

Filter, Listener 是 Java web 的核心内容,那么springBoot怎么使用它们那?

自定义过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.qn.filter;

import com.qn.interceptor.LogHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {

Logger logger = LoggerFactory.getLogger(LogHandlerInterceptor.class);

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("过滤器生效!!!");
filterChain.doFilter(servletRequest, servletResponse);
}
}

自定义监听器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.qn.listener;

import com.qn.interceptor.LogHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class LogListener implements ServletContextListener {

Logger logger = LoggerFactory.getLogger(LogHandlerInterceptor.class);

@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("监听器开始初始化");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("监听器开始销毁");
}
}

注册

添加到容器有两种方式,第一种使用注解扫描。

1
2
3
4
5
6
7
8
9
10
/**
* @ServletComponentScan 扫描Servlet,Filter,Listener 添加到容器
*/
@SpringBootApplication
@ServletComponentScan
public class SpringbootDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}

或者直接添加到容器中去:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.qn.config;

import com.qn.filter.LogFilter;
import com.qn.listener.LogListener;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class WebCoreConfig {
@Bean
public FilterRegistrationBean myFitler() {
return new FilterRegistrationBean<>(new LogFilter());
}

@Bean
public ServletListenerRegistrationBean myListener() {
return new ServletListenerRegistrationBean(new LogListener());
}
}
文章目录
  1. 1. 简介
  2. 2. 自定义过滤器
  3. 3. 自定义监听器
  4. 4. 注册
|