首页 > 代码库 > Tomcat过滤器模拟
Tomcat过滤器模拟
直接上代码Filter.java
public interface Filter { //过滤器 public void doFilter(Request request,Response response,FilterChain chain);}
FilterChain.java
public class FilterChain { //存放所有的过滤器 private List<Filter> filters ; //记录当前过滤索引 private int index; //过滤链初始化 public FilterChain() { filters = new ArrayList<Filter>(10); } public void addFilter(Filter filter) { filters.add(filter); } /** * 迭代过滤 */ public void doFilter(Request request,Response response) { if ( index >= filters.size() ) return; filters.get( index++ ).doFilter(request, response, this); }}
Request.java
public class Request { private String value; public String getValue() { return value; } public void setValue(String value) { this.value =http://www.mamicode.com/ value; } @Override public String toString() { return this.value; }}
Response.java
public class Response { private String value; public String getValue() { return value; } public void setValue(String value) { this.value =http://www.mamicode.com/ value; } @Override public String toString() { return this.value; }}
FilterOne.java
public class FilterOne implements Filter{ /** * 过滤FUCK字符 */ @Override public void doFilter(Request request, Response response, FilterChain chain) { System.out.println("进入过滤器FilterOne---------------------------------------"); //执行下一个过滤器 chain.doFilter(request, response); System.out.println("出去过滤器FilterOne---------------------------------------"); }}
FilterTwo.java
public class FilterTwo implements Filter{ @Override public void doFilter(Request request, Response response, FilterChain chain) { System.out.println("进入过滤器FilterTwo---------------------------------------"); //执行下一个过滤器 chain.doFilter(request, response); System.out.println("出去过滤器FilterTwo---------------------------------------"); } }
Test.java
public class Test { public static void main(String[] args) { FilterChain chain = new FilterChain(); chain.addFilter(new FilterOne()); chain.addFilter(new FilterTwo()); chain.doFilter(new Request(), new Response() ); }}
运行结果
进入过滤器FilterOne---------------------------------------进入过滤器FilterTwo---------------------------------------出去过滤器FilterTwo---------------------------------------出去过滤器FilterOne---------------------------------------
Tomcat过滤器模拟
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。