IP过滤器例子
直接上代码,先上web.xml
里面包含初始化参数,在启动tomcat的时候会直接把要过滤的IP加载到tomcat容器中。
web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6 <!-- 配置过滤器 -->
7 <filter>
8 <filter-name>IPFilter</filter-name>
9 <filter-class>sunyang.IPFilter</filter-class>
10 <init-param>
11 <param-name>filterIP</param-name>
12 <param-value>127.0.0.1</param-value>
13 </init-param>
14 </filter>
15 <!-- 配置过滤器的映射路径 -->
16 <filter-mapping>
17 <filter-name>IPFilter</filter-name>
18 <url-pattern>/*</url-pattern>
19 </filter-mapping>
20 </web-app>
然后是过滤器方法:IPFilter.java
1 package sunyang;
2
3 import java.io.IOException;
4 import javax.servlet.Filter;
5 import javax.servlet.FilterChain;
6 import javax.servlet.FilterConfig;
7 import javax.servlet.RequestDispatcher;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11
12 public class IPFilter implements Filter
13 {
14
15 protected FilterConfig filterConfig;
16
17 protected String filterIP; // 要过滤的IP
18
19 /* 初始化 */
20 public void init(FilterConfig config) throws ServletException
21 {
22
23 this.filterConfig = config;
24 filterIP = config.getInitParameter("filterIP");// 从web.xml中获取初始化参数
25 System.out.println("要过滤的IP:"+filterIP);
26 if (filterIP == null)
27 filterIP = "";
28
29 }
30
31 /* 过滤器方法 */
32 public void doFilter(ServletRequest reg, ServletResponse res,
33 FilterChain chain) throws IOException, ServletException
34 {
35
36 RequestDispatcher reqDispatcher = reg.getRequestDispatcher("error.jsp");
37 String remoteIP = reg.getRemoteAddr();// 获取访问服务器的IP
38 System.out.println("访问服务器的IP:"+remoteIP);
39 if (remoteIP.equals(filterIP))
40 {// 如果是要过滤的IP,就通过reqDispatcher跳转到错误页面。
41 reqDispatcher.forward(reg, res);
42 }
43 else
44 {// 如果不是要过滤的IP就放行,交给下一个Filter
45 chain.doFilter(reg, res);
46 }
47 }
48
49 /*销毁方法 */
50 public void destroy()
51 {
52 this.filterConfig = null;
53 }
54 }
index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
2 <%
3 String path = request.getContextPath();
4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
5 %>
6 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
7 <html>
8 <head>
9 <base href="<%=basePath%>">
10 <title>My JSP 'index.jsp' starting page</title>
11 </head>
12
13 <body>
14 <a href="success.jsp">测试过滤器</a> <br>
15 </body>
16 </html>
success.jsp
1 <%@ page language="java" pageEncoding="GBK"%>
2 <html>
3 <head>
4 <title>欢迎页面</title>
5 </head>
6 <body>
7 <center><h2>欢迎访问xxx</h2></center>
8 </body>
9 </html>
error.jsp
<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<title>拒绝访问</title>
</head>
<body>
<center><h2>对不起,您的IP地址禁止访问该网站!</h2></center>
</body>
</html>