过滤器(Filter)和 监听器(Listener)的注册方法和 Servlet 一样,不清楚的可以查看下上一篇文章

代码示例

package me.shijunjie.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; @WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter { @Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("MyFilter init");
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("MyFilter doFilter");
chain.doFilter(request, response);
} @Override
public void destroy() {
System.out.println("MyFilter destroy");
}
}
package me.shijunjie.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; @WebListener
public class MyHttpSessionListener implements HttpSessionListener { @Override
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("MyHttpSessionListener sessionCreated");
} @Override
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("MyHttpSessionListener sessionDestroyed");
} }
package me.shijunjie.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener; @WebListener
public class MyServletContextListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContex contextInitialized");
} @Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContex contextDestroyed");
} }
package me.shijunjie.testspringboot2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; /**
* Hello world!
*
*/
@SpringBootApplication
@ServletComponentScan("me.shijunjie")
public class App
{ /* *//**
* 注册Servlet.不需要添加注解:@ServletComponentScan
* @return
*//*
@Bean
public ServletRegistrationBean myServlet1(){ return new ServletRegistrationBean(new MyServlet1(),"/myServlet/*");
}*/ public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
05-11 19:33