java filterchain


马士兵的filterchain练习一下,有点小改动
 

package filter;

import filterChain.FilterChain;
import information.Request;
import information.Response;

public interface Filter {
	public void doFilter(Request rq, Response rp, FilterChain fc);
}

 

package filterChain;

import information.Request;
import information.Response;

import java.util.ArrayList;
import java.util.List;

import filter.Filter;

public class FilterChain implements Filter {

	List<Filter> chain = new ArrayList<Filter>();
	int i = 0;

	public Filter addFilter(Filter f) {
		chain.add(f);
		return this;
	}

	public void doFilter(Request rq, Response rp){
		doFilter(rq, rp, this);
	}
	
	public void doFilter(Request rq, Response rp, FilterChain fc) {
		if (i == chain.size())
			return;
		Filter f = chain.get(i);
		i++;
		f.doFilter(rq, rp, fc);
	}
}

 

package filter.impl;

import information.Request;
import information.Response;
import filter.Filter;
import filterChain.FilterChain;

public class TextFilter implements Filter {

	public void doFilter(Request rq, Response rp, FilterChain fc) {
		rq.setS(rq.getS().replace("fang", "方"));
		fc.doFilter(rq, rp);
		rp.setS(rp.getS()+"TextFilter ");
	}
}

 

package filter.impl;

import information.Request;
import information.Response;
import filter.Filter;
import filterChain.FilterChain;

public class AddFilter implements Filter {

	public void doFilter(Request rq, Response rp, FilterChain fc) {
		rq.setS("姓名: "+rq.getS());
		fc.doFilter(rq, rp);
		rp.setS(rp.getS() + "AddFilter ");
	}

}

 

package information;

public class Request {
	String s;

	public String getS() {
		return s;
	}

	public void setS(String s) {
		this.s = s;
	}
}

 

package information;

public class Response {
	private String s;

	public String getS() {
		return s;
	}

	public void setS(String s) {
		this.s = s;
	}
	
}

 

package test;

import filter.impl.AddFilter;
import filter.impl.TextFilter;
import filterChain.FilterChain;
import information.Request;
import information.Response;

public class Test {
	public static void main(String[] args) {
		Request rq = new Request();
		Response rp = new Response();
		TextFilter f = new TextFilter();
		AddFilter af = new AddFilter();
		FilterChain fc = new FilterChain();
		
		rq.setS("fangshaowei");
		rp.setS("返回信息: ");
		fc.addFilter(f);
		fc.addFilter(af);
		fc.doFilter(rq, rp, fc);
		
		System.out.println(rq.getS());
		System.out.println(rp.getS());
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值