zoukankan      html  css  js  c++  java
  • Filter设计实现IP地址限制

    示例:创建一个IP过滤Filter,当一个用户发出访问请求的时候,首先通过过滤器进行判断,

    如果用户的IP地址被限制,就禁止访问,只有合法的IP才可以继续访问。IP过滤Filter代码如下:

    IPFilter.java

     1 package com.mhb;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.Filter;
     7 import javax.servlet.FilterChain;
     8 import javax.servlet.FilterConfig;
     9 import javax.servlet.ServletException;
    10 import javax.servlet.ServletRequest;
    11 import javax.servlet.ServletResponse;
    12 
    13 public class IPFilter implements Filter {
    14 
    15 protected FilterConfig filterConfig;
    16 protected String ip;
    17 
    18 public void init(FilterConfig filterConfig) throws ServletException {
    19 this.filterConfig = filterConfig;    //设置属性filterConfig
    20 this.ip = this.filterConfig.getInitParameter("ip");    //设置初始化参数IP
    21 }
    22 //过滤方法
    23 public void doFilter(ServletRequest request, ServletResponse response,
    24 FilterChain chain) throws IOException, ServletException {
    25 String remoteIP = request.getLocalAddr();    //获得客户端ip地址
    26 
    27 if(remoteIP.equals(ip)){    //判断IP是否被禁止
    28 response.setCharacterEncoding("gb2312");    //设置输出内容编码格式
    29 PrintWriter out = response.getWriter();
    30 out.println("<b>你的IP地址被禁止访问!</b>");
    31 }else{
    32 chain.doFilter(request, response);
    33 }
    34 }
    35 //销毁方法
    36 public void destroy() {
    37 }
    38 }

    web.xml配置

     <filter>
          <filter-name>IPFilter</filter-name>
          <filter-class>com.mhb.IPFilter</filter-class>
          <init-param>
           <param-name>ip</param-name>
           <param-value>127.0.0.1</param-value>
          </init-param>
      </filter>
      <filter-mapping>
           <filter-name>IPFilter</filter-name>
           <url-pattern>/*</url-pattern>
      </filter-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    浏览器显示:

  • 相关阅读:
    斯特林数及斯特林反演
    关于斯特林数的应用总结
    向量运算与几何意义
    linux shell——md5sum,sha1sum,sort,uniq (转)
    hudson配置教程
    linux下安装tomcat和部署web应用
    Tomcat Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
    《Ant权威指南》笔记(一)
    ant调用shell命令(Ubuntu)
    hudson--ant编写记录
  • 原文地址:https://www.cnblogs.com/tdcqma/p/4760434.html
Copyright © 2011-2022 走看看