spring boot 如何配置Filter过滤器

今天想添加一个邀请注册功能,就是所有页面只要有邀请的参数,注册后就会被调用,开始想到了用拦截器,后来发现拦截器我设置不拦截的页面就无法获取了,后来想到了用spring boot的过滤器。

关注者
被浏览

个回答

默认排序
飞舞九天
免费开源问答源码
人赞同了该回答

首先要准备一个实现了Filter的接口的类 FlyFilter:

package com.flycms.filter;

import com.flycms.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 * Open source house, All rights reserved
 * 版权:28844.com<br/>
 * 开发公司:28844.com<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 9:51 2018/9/12
 */

@WebFilter(filterName="myFilter",urlPatterns="/*")
public class FlyFilter 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 {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String invite=request.getParameter("invite");
        if(!StringUtils.isBlank(invite)){
            CookieUtils.writeCookie(httpResponse,"invite",invite,60*60*24*7);
        }
        System.out.println("MyFilter doFilter.........before");
        chain.doFilter(request, response);
        System.out.println("MyFilter doFilter.........after");
    }

    @Override
    public void destroy() {
        System.out.println("MyFilter destroy..........");
    }
}

在启动类里加上启动注解:

@ServletComponentScan