Servlet过滤器介绍之实用过滤器 - 编程入门网
Servlet过滤器介绍之实用过滤器时间:2011-04-09 51cto zhangjunhd6.禁止站点过滤器 如果你希望在你的过滤器检测到不正常的异常而中途中断后面的过滤过程时,可这样做:
下例是一个禁止站点过滤器,如果不希望某些站点访问你的网站,你可以在web.xml的 param-value中列出它的站点,然后应用上面的原理跳出常规过滤,给出禁止访问的页面。 BannedAccessFilter.java package com.zj.sample; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.StringTokenizer; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class BannedAccessFilter implements Filter { private HashSet<String> bannedSiteTable; /** * Deny access if the request comes from a banned site or is referred here * by a banned site. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { System.out.println("Within BannedAccessFilter:Filtering the Request..."); HttpServletRequest req = (HttpServletRequest) request; String requestingHost = req.getRemoteHost(); String referringHost = getReferringHost(req.getHeader("Referer")); String bannedSite = null; boolean isBanned = false; if (bannedSiteTable.contains(requestingHost)) { bannedSite = requestingHost; isBanned = true; } else if (bannedSiteTable.contains(referringHost)) { bannedSite = referringHost; isBanned = true; } if (isBanned) { showWarning(response, bannedSite); } else { chain.doFilter(request, response); } System.out.println("Within BannedAccessFilter:Filtering the Response..."); } /** * Create a table of banned sites based on initialization parameters. * Remember that version 2.3 of the servlet API mandates the use of the * Java 2 Platform. Thus, it is safe to use HashSet (which determines * whether a given key exists) rather than the clumsier Hashtable * (which has a value for each key). */ public void init(FilterConfig config) throws ServletException { bannedSiteTable = new HashSet<String>(); String bannedSites = config.getInitParameter("bannedSites"); // Default token set: white space. StringT |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |