SpringBoot入门(4)——Filter,Listener

          • 1.springboot 创建监听器和过滤器
          • 2.创建过滤器
          • 3.创建监听器
          • 4.结果

1.springboot 创建监听器和过滤器

使用 @WebListener 创建监听器
使用 @WebFilter(filterName="myfilter",urlPatterns="/*") 创建过滤器

2.创建过滤器

创建 过滤器类 MyFilter

package com.example.demo;

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;
/**
 * 过滤器
 * @author LENOVO
 *
 */
@WebFilter(filterName="myfilter",urlPatterns="/*")
public class MyFilter  implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("过滤器拦截");
        System.out.println(request.getCharacterEncoding());
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");

    }

}
3.创建监听器
  • 创建 ServletContextListener 监听器类
package com.example.demo;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
 * servlet 监听类
 * @author LENOVO
 *
 */
@WebListener
public class MyServletContextListener  implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("servletContextListenr initial");
        System.out.println(sce.getServletContext().getServerInfo());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("servletContextListener destroy");
    }

}
  • 创建 HttpSessionListener 监听类
package com.example.demo;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/*
 * 监听session
 */
@WebListener
public class MyHttpSessionListener  implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session create");

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session destroy");
    }

}
4.结果

SpringBoot入门(4)——Filter,Listener_第1张图片
SpringBoot入门(4)——Filter,Listener_第2张图片

完!

你可能感兴趣的:(springBoot,SpringBoot)