package com.otg.jason.filter.old; /** * Created by jason.guan on 2017/7/16. */ public class FilterProcessor { String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String process(){ //process html tag String r = msg.replace("<", "[") .replace(">", "]"); //process the sensitive words r=r.replace("敏感", "XXXX"); return r; } }
package com.otg.jason.filter.old; /** * Created by jason.guan on 2017/7/16. */ public class FilterProcessorTest { /** * @param args */ public static void main(String[] args) { String msg = "<html>,敏感信息,大家可以看见吗"; FilterProcessor filterProcessor = new FilterProcessor(); filterProcessor.setMsg(msg); String result = filterProcessor.process(); System.out.println(result); } }
[html],XXXX信息,大家可以看见吗
通过FilterProcessor的process对信息进行过滤,一旦发生新的需求,我们不得不修养这个方法,这就违背了对修改关闭,对扩张开发的设计思想,那么怎么办呢?
package com.otg.jason.filter; /** * Created by jason.guan on 2017/7/16. */ public interface Filter { void doFilter(Request request, Response response, FilterChain chain); }
package com.otg.jason.filter; import java.util.ArrayList; import java.util.List; /** * Created by jason.guan on 2017/7/16. */ public class FilterChain implements Filter { List<Filter> filters = new ArrayList<Filter>(); int index = 0; public FilterChain addFilter(Filter f) { this.filters.add(f); return this; } public void doFilter(Request request, Response response, FilterChain chain) { if(index == filters.size()) return ; Filter f = filters.get(index); index ++; f.doFilter(request, response, chain); } }
分化了各个校验规则,提高了可扩展性.我们要实现链条的拼接,其实我们想想,一个Filter链条本身就是一个Filter,所以我们使用FilterChain来模拟Filter链条,并且实现了Filter接口,
package com.otg.jason.filter; /** * Created by jason.guan on 2017/7/16. */ public class SesitiveFilter implements Filter { public void doFilter(Request request, Response response, FilterChain chain) { String requestStr = request.getRequestStr(); String responseStr = requestStr.replace("敏感", "XXXX"); request.setRequestStr(responseStr); response.setResponseStr(response.getResponseStr()+","+responseStr); chain.doFilter(request, response, chain); } }
这样我们的Filterchain不仅可以添加一个个Filter,还能直接添加Filter链条,现在的问题是如何让我们的Filter也可以处理返回的信息呢?
package com.otg.jason.filter; /** * Created by jason.guan on 2017/7/16. */ public class FilterMainTest { /** * @param args */ public static void main(String[] args) { String msg = "<html>,敏感信息,大家可以看见吗"; Request request = new Request(); request.setRequestStr(msg); Response response = new Response(); response.setResponseStr("response"); FilterChain fc = new FilterChain(); fc.addFilter(new HTMLFilter()) .addFilter(new SesitiveFilter()); fc.doFilter(request, response, fc); System.out.println(request.getRequestStr()); System.out.println(response.getResponseStr()); } }
要想让我们的Filter可以处理返回信息,很自然的想到让一个Filter去调用另外一个Filter,等到最后一个Filter返回,其余的也逐个返回,这里要完成这一过程,增加了
一个参数FilterChain,FilterChain里面记录了当前过滤器索引,巧妙的完成了一个Filter调用另外一个Filter的需求