work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Zuul Pre和Post过滤器

Posted on 2019-02-16 20:08  work hard work smart  阅读(421)  评论(0编辑  收藏  举报

一、项目架构图

 

二、前置过滤器

@Component
public class TokenFilter  extends ZuulFilter{
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request =  requestContext.getRequest();

        //这里从url参数获取,也可以从cookie,header里获取
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            //不通过
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }
        return null;
    }
}

  

带了token就能正常访问

否则,无法访问,返回401

 

三、后置过滤器

1、增加后置过滤器

@Component
public class AddResponseHeaderFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
       HttpServletResponse response = requestContext.getResponse();
       response.setHeader("X-Foo", UUID.randomUUID().toString());
        return null;
    }
}

  在回复后里增加X-Foo,值为UUID

 

2、查看结果