SpringBoot项目中添加过滤器Filter

一、步骤

  1、通过实现Filter接口,创建一个过滤器类

  2、通过@WebFilter注解,注册过滤器。urlPatterns属性代表需要被过滤的请求地址。filterName属性代表过滤器名称。

  3、在SpringBoot应用启动类中,添加@ServletComponentScan注解,表示项目启动自动扫描Servlet组件。Filter属于Servlet组件。

二、实现

package org.cm.channelmanage.web.filter;


import org.cm.channelmanage.web.handler.BodyReaderHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "channelFilter")
public class ChannelFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(ChannelFilter.class);

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

    }

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

    @Override
    public void destroy() {

    }
}
package org.cm.channelmanage;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class ChannelManageApplication {

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

 

你可能感兴趣的:(JAVA)