同servlet非常類似,F(xiàn)ilter就是JAVA組件,請求發(fā)送到servlet前,可以使用過濾器Filter截獲和處理請求,同時servlet結(jié)束以后,響應發(fā)回以前同樣可以使用過濾器Filter處理響應。WEB容器可以用web.xml部署文件聲明何時調(diào)用過濾器Filter。
過濾器Filter主要功能是:1、完成安全檢查;2、重新格式化請求首部或體;3、建立請求審計或記錄日志---請求過濾器Filter
1、壓縮響應流;2、追加或者修改響應流;3、創(chuàng)建一個定制響應---響應過濾器Filter
同servlet一樣,過濾器Filter也具有生命周期:init()->doFilter()->destroy().要實現(xiàn)模塊化,F(xiàn)ilterChain功不可末,它可以采用不同的方式組合過濾器,協(xié)調(diào)完成一些事情,它由部署文件中的filter元素驅(qū)動,和Filter都在javax.servlet包中。在servlet2.4中,過濾器同樣可以用于請求分派器,但須在web.xml中聲明,<dispatcher>INCLUDE或FORWARD或REQUEST或ERROR</dispatcher>該元素位于filter-mapping中。
1、實現(xiàn)一個Filter,代碼如下:
public class MyFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException{
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
CachedResponseWrapper wrapper = new CachedResponseWrapper(httpResponse);
// 寫入wrapper:
chain.doFilter(request, wrapper);
// 首先判斷status, 只對200狀態(tài)處理:
if(wrapper.getStatus()==HttpServletResponse.SC_OK) {
// 對響應進行處理,這里是進行GZip壓縮:
byte[] data = GZipUtil.gzip(wrapper.getResponseData());
httpResponse.setContentType(getContentType());
httpResponse.setContentLength(data.length);
httpResponse.setHeader("Content-Encoding", "gzip");
ServletOutputStream output = response.getOutputStream();
output.write(data);
output.flush();
}
}
public void destroy() {
}
}
2、實現(xiàn)一個HttpServletResponseWrapper
public class CheckFrameHttpServletResponseWrapper extends
HttpServletResponseWrapper {
public CheckFrameHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public PrintWriter getWriter() throws IOException{
return new CheckFrameWriter(super.getWriter());
}
}
3、實現(xiàn)一個Writer
public class CheckFrameWriter extends PrintWriter {
String checkString = "<script>\n if(window.top.frames.length==0){\n"
+ "window.location.href=\"https://aix:9080/sso/mainlayout.faces?"
+ "contentURL=http://aix:9080/security/paramsMaintain/"
+ "addParams.faces?roleId=0001\"\n" + "}\n</script>\n";
public CheckFrameWriter(Writer out) {
super(out);
}
public void write(int c) {
super.write((char) c);
}
public void write(char buf[], int off, int len) {
StringBuffer sb = new StringBuffer(len);
for (int i = 0; i < len; i++) {
sb.append(buf[off + i]);
}
String s = sb.toString();
int bodyIndex = s.indexOf("<body>");
if (bodyIndex > -1) {
String part1 = s.substring(0, bodyIndex);
String part2 = s.substring(bodyIndex );
s = part1 + checkString + part2;
}
for (int i = 0; i < s.length(); i++) {
write(s.charAt(i));
}
}
public void write(String s, int off, int len) {
for (int i = 0; i < len; i++) {
write(s.charAt(off + i));
}
}
}
在Writer中,你便可以隨心所欲的修改Response的內(nèi)容了。
4、在Web.xml中加入相應的配置元素,對JSP進行攔截。
凡是有該標志的文章,都是該blog博主Caoer(草兒)原創(chuàng),凡是索引、收藏
、轉(zhuǎn)載請注明來處和原文作者。非常感謝。