prawn 发布系统中 Filter 的使用

一. 自定义 filter

1. AuditFilter
@Component
public class AuditFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //not care
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //logic1
    }
    //程序继续执行下一个 filter
    filterChain.doFilter(request, response);
    ......
}
2. AuditFilter2
@Component
public class AuditFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //not care
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //logic2
        String jwtToken = httpRequest.getHeader("jwt-token");
        JWT jwt = decodeToken(jwtToken);
        String userName = findUserInfoFromToken(jwt);
        //这里可以,AOP 中可以拦截到username,进而做权限控制
        request.setAttribute("username", username);
    }
    //程序继续执行下一个 filter
    if(true) {
        filterChain.doFilter(request, response);
    }else {
        //中断执行,返回response
        httpResponse.getWriter().write(mapper.writeValueAsString(result));
    }
    ......
}
3. AuditFilter3
@Component
public class AuditFilter3 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //not care
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //logic3
    }
    //程序继续执行下一个 filter
    filterChain.doFilter(request, response);
    ......
}

二. 组装 filter 到 spring 容器

@Configuration
@ComponentScan
public class FilterConfiguration {

    @Bean
    public FilterRegistrationBean filterAuthenticationBean(AuditFilter1 filter) { //filter1
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.setOrder(100);  //filter 执行顺序,数值越低越先执行
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean filterAuthorizationBean(AuditFilter2 filter) { //filter2
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.setOrder(200);  //filter 执行顺序
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean filterAuditBean(AuditFilter3 filter ) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(); //filter3
        registrationBean.setFilter(filter);
        registrationBean.setOrder(300);  //filter 执行顺序
        return registrationBean;
    }

}

你可能感兴趣的:(prawn 发布系统中 Filter 的使用)