SpringBoot自定义Filter

版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/yh_zeng2 https://blog.csdn.net/yh_zeng2/article/details/82356403

自定义Filter

我们常常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,并且我们可以自定义Filter。

两个步骤:

  1. 实现Filter接口,实现Filter方法
  2. 添加@Configuration 注解,将自定义Filter加入过滤链

好吧,直接上代码

  FilterConfiguration.java

package codex.terry.beanconfig;

import codex.terry.filter.PathFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 编写人: yh.zeng
 * 编写时间: 2018-8-28
 * 文件描述: 注册Filter Bean
 */
@Configuration
public class FilterConfiguration
{
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new PathFilter());
        registration.addUrlPatterns("/*");
        //registration.addInitParameter("paramName", "paramValue");
        registration.setName("PathFilter");
        registration.setOrder(1);
        return registration;
    }
}
PathFilter.java
package codex.terry.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 编写人: yh.zeng
 * 编写时间: 2018-8-28
 * 文件描述:
 */
public class PathFilter implements Filter{

    private static final Logger LOG = LoggerFactory.getLogger(PathFilter.class);
    private FilterConfig config;

    @Override
    public void init(final FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String basePath = request.getScheme()
                + "://" + request.getServerName()
                + ":" + request.getServerPort()
                + request.getContextPath();
        String servletPath = request.getServletPath();
        LOG.info("[PATH]: " + basePath + servletPath);

        chain.doFilter(request, response);
    }

}

猜你喜欢

转载自blog.csdn.net/yh_zeng2/article/details/82356403