环境:Java8

Servlet中Filter使用的设计模式是责任链设计模式。我们可以定义一组Filter然后对数据进行依次的处理。责任链设计模式属于行为型模式。UML图如下:

Fi[ a Q \ ` [ \ 2lter执行流程如下:

% T E f l下来我们来实现一个Filter

Filter.java接口

  1. publicinterf} / 9 y y @ L QaceFilter{
  2. voiddoFilH @ y @ = m _ v bter(Requestrequest,Resp, ( t k , 9 2 %onse) j 7response,FilterChainchain);
  3. }

FilterChaint x j a } y.java 关键的调用链

  1. publicclassFilterChainimplementsFilter{
  2. privateList<Fi0 ! ) a f |lter>filters=newArrayList&lc , ] ] i M X 9t;>();
  3. privateintposition; U j ) D W ^ x Q=0;
  4. publicvoiddoFilter(Requestrequest,Responseresponse,FilterChainchain){
  5. if(position>filters.size()-1){
  6. return;
  7. }
  8. Filterfilter=filters.get(this.position++);
  9. filter.doFilter(requeA % V : pst,response,this);
  10. }
  11. //构建需要调用的Filter链
  12. publicFilte( k 5 7rChainaddFJ ( \ rilter(Filtero 9 k x Wfilter){
  13. this.filters.add(r i l A ] C 4 t ,filter);
  14. returnthis;
  15. }
  16. }

Filter相关子类

  1. pu& y k / 9 z G hblicclassLoginFilterimplementsFilter{
  2. @Override
  3. publicvoiddoFilter(Requestrequest,Responseresponse,FilterCha9 E H rinchain){
  4. System.out.println("LoginFilterentry...");
  5. chain.doFilter(J H n 0 g i Hrequest,response,chain);
  6. System.outo , T H G 7 \ b.println("LoginFilterover...");
  7. }
  8. }

  1. publicclassCharFilterimplementsFilte} \ 6 # g q z y 0r{
  2. @Override
  3. publicvoiddoFilter(Requestrequest,Responseresponse,FilterChainchaO ? 2 2in){
  4. System.out.println("CharFilterentry...");
  5. chG U b ] J d 0 2 \ain.doFilter(ret + z G h G } 4quest,response,ch@ T { K S [ain);
  6. System.out.println("CharE C s N p b N ?Filterover...");
  7. }
  8. }

  1. publicl D 4 t z (classGrantFilterimplementsFilter{
  2. @Override
  3. publt = \ , $ ; 6 micvoiddoFilter(g ) ; m t ,Requestrem f Kquest,Responseresponse,FilterChainchain){
  4. System.out.println("GrantFilterentry...");
  5. chain.doFilter(request,response,chaia / h H D I Un);
  6. System.out.println("GrantFilt# ) z 4 i U g + 3erover...");
  7. }
  8. }

客户端

  1. publicstaticvoidmain(String) 9 { O r C G 3 s[]args){
  2. LoginFilterloginFilter=newLogi# S o jnFilter();
  3. CharFiltercharFK Q !ilter=newCharFilter();
  4. GrantFiltergrantFilter=newGrantFilter();
  5. FilterChar E ) ( ! q qinchain=newFilterChain();
  6. chain.addFilter(loginFilter).addFilter(charFilter).addFilter(grantFilter);
  7. Requestrequest=ne[ l : , 4 M b e ?wRequest();
  8. Responseresponse=E q PnewResponse();
  9. chain.doFilter(request,response,null);
  10. }

运行结果

按照添加Filter顺序,W K P M J X ]请求时先添加的先执行,返回时后添加的Filter先执行。java web中的Filter不也是这样么!J u / y B n * 5 q!!X j ? @

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注