一、使用RegistrationBean注册

1、添加2个类实现filter和ServletContextListener

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
26
27
class MyFilter implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

}

@Override
public void destroy() {

}
}

class MyListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce) {
System.out.println("********监听器初始化********");
}

public void contextDestroyed(ServletContextEvent sce) {
System.out.println("********监听器销毁********");
}
}

2、RegistrationBean注册filter和listener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean<MyFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new MyFilter());
// filter过滤路径
bean.addUrlPatterns("/**");
return bean;
}

@Bean
public ServletListenerRegistrationBean ListenerRegistrationBean(){
ServletListenerRegistrationBean<MyListener> bean = newServletListenerRegistrationBean<>();
bean.setListener(new MyListener());
// 设置listener执行顺序
bean.setOrder(100);
return bean;
}

二、使用Servlet3.0注解添加

1、在实现filter,ServletContextListener接口的类上添加@WebFilter, @WebListener注解

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
26
27
28
29
30
31
32
33
34
 /**
* filterName: filter名称
* urlPatterns: filter过滤路径,是一个数组可添加多个路径
* eg: urlPatterns = {"/**", "/login"}
*/
@WebFilter(filterName = "myFilter", urlPatterns = {"/**"})
class MyFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

}

@Override
public void destroy() {

}
}

@WebListener(value = "myListener")
class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("********监听器初始化********");
}

public void contextDestroyed(ServletContextEvent sce) {
System.out.println("********监听器销毁********");
}
}

2、在springboot启动类上添加@ServletComponentScan注解

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableEurekaServer
/**
* value参数指定要扫描的包,即@WebFilter@WebListener所在类的包路径
* String[] value():value为数组可配置多个扫描路径
* @ServletComponentScan(value = {"", ""})
*/
@ServletComponentScan(value = {""})
public class EureakaServerApplication
相关文章
评论
分享
  • 如何从request数据流中多次取出数据

    ​ 我们知道在request输入流中,数据只能取一次,之后流中就没有数据了。那我们在之后还想要从request中获取就只有想办法把取出的值在放回去。 123456789101112131415161718192021222324...

    如何从request数据流中多次取出数据
  • 分布式唯一id:雪花算法

    结构 snowflake的结构如下(每部分用-分开): 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 第一位为未使用,...

    分布式唯一id:雪花算法