一、目标
1.用Filter模拟处理Request、Response
2.思路细节技巧:
(1)Filter的doFilter方法改为doFilter(Request,Resopnse,FilterChain),有FilterChain引用,为利用FilterChain调用下一个Filter做准备
(2)FilterChain继承Filter,这样,FilterChain既是FilterChain又是Filter,那么FilterChain就可以调用Filter的方法doFilter(Request,Resopnse,FilterChain)
(3)FilterChain的doFilter(Request,Resopnse,FilterChain)中,有index标记了执行到第几个Filter,当所有Filter执行完后request处理后,就会return,以倒序继续执行response处理
二、代码
1.Filter.java
2.HTMLFilter.java
3.SensitiveFilter.java
4.FilterChian.java
5.Request.java
6.Response.java
7.Test.java
1.Filter.java
public interface Filter {
public void doFilter(Request request, Response response, FilterChain filterChain);
}
2.HTMLFilter.java
public class HTMLFilter implements Filter { @Override
public void doFilter(Request request, Response response,
FilterChain filterChain) {
request.setRequestStr(request.getRequestStr().replace('<', '[').replace(">", "]")+"---HTMLFilter()");
filterChain.doFilter(request, response, filterChain);
response.setResponseStr(response.getResponseStr()+"---HTMLFilter()");
} }
3.SensitiveFilter.java
public class SensitiveFilter implements Filter { @Override
public void doFilter(Request request, Response response,
FilterChain filterChain) {
request.setRequestStr(request.getRequestStr().replace("敏感", "幸福")+"---SensitiveFilter()");
filterChain.doFilter(request, response, filterChain);
response.setResponseStr(response.getResponseStr()+"---SensitiveFilter()");
} }
4.FilterChian.java
public class FilterChain implements Filter { private List<Filter> filters = new ArrayList<Filter>();
int index = 0; //标记执行到第几个filter //把函数的返回值设为FilterChain,返回this,就能方便链式编写代码
public FilterChain addFilter(Filter filter) {
filters.add(filter);
return this;
} public void doFilter(Request request, Response response, FilterChain fc) {
if(index == filters.size()) return ;
Filter f = filters.get(index);
index++;
f.doFilter(request, response, fc);
} }
5.Request.java
public class Request { private String requestStr; public String getRequestStr() {
return requestStr;
} public void setRequestStr(String requestStr) {
this.requestStr = requestStr;
} }
6.Response.java
public class Response { private String responseStr; public String getResponseStr() {
return responseStr;
} public void setResponseStr(String responseStr) {
this.responseStr = responseStr;
} }
7.Test.java
public class Test { @org.junit.Test
public void testFilter(){ String msg = "<html>敏感字眼</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 SensitiveFilter()); fc.doFilter(request, response, fc);
System.out.println(request.getRequestStr());
System.out.println(response.getResponseStr()); } }
三、执行结果