1. 程式人生 > >Servlet過濾器——禁止未授權的IP訪問站點

Servlet過濾器——禁止未授權的IP訪問站點

在實際的應用中,我們會遇到這樣的情況,需要對某些Ip進行訪問限制,不讓非法的Ip訪問應用系統。只有合法的Ip才能可以繼續訪問!

1.下面就用一個例項FilterIP.java來禁止那些未授權的Ip

package com.msit.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FilterIP implements Filter {
	protected FilterConfig filterConfig;
	protected String FilteredIP;
	/**
	 * 初始化
	 */
	@Override
	public void init(FilterConfig conf) throws ServletException {
		this.filterConfig = conf;//過濾器初始化
		FilteredIP = conf.getInitParameter("FilteredIP");//獲取被過濾的Ip
		if (FilteredIP==null) {
			FilteredIP="";
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html");
		response.setCharacterEncoding("gb2312");//設定編碼格式
		RequestDispatcher dispatcher = request.getRequestDispatcher("ErrorInfo.jsp");//定義錯誤轉向頁面
		//讀出本地Ip
		String remoteIP = request.getRemoteAddr();
		//將其與要過濾掉的Ip比較,如果相同,就轉到錯誤處理介面
		if (remoteIP.equals(FilteredIP)) {
			dispatcher.forward(request, response);
		}else {
			chain.doFilter(request, response);
		}
	}
	
	@Override
	public void destroy() {
		this.filterConfig = null;
	}
}
2.再建立一個成功訪問頁面的Jsp檔案Success.jsp和失敗訪問錯誤的響應頁面ErroeInfo.jsp

成功訪問頁面(Success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
	<head>
		<title>歡迎登陸</title>
	</head>
	<body>
		<center>
			<font size = 4>歡迎登陸javaWeb伺服器</font><!-- 成功訪問輸出語句 -->
		</center>
	</body>
</html>
失敗訪問錯誤的響應頁面(ErroeInfo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
	<head>
		<title>錯誤報告</title>
	</head>
	<body>
		<%
			out.print("<center><font size = 4>對不起,您的IP不能登陸本網站!</font></center>");//被拒絕伺服器Ip顯示資訊
		%>
	</body>
</html>
3.配置過濾器的web.xml
<!-- 配置過濾器 儘可能把過濾器配置到web.xml最上面 -->
  <filter>
  	<filter-name>FilterIP</filter-name>
  	<filter-class>com.msit.servlet.FilterIP</filter-class>
  	<init-param>
  	<param-name>FilteredIP</param-name>	
  	<param-value>127.0.0.1</param-value><!-- 要過濾的Ip  127.0.0.1為本地 -->
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>FilterIP</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
4.最後在瀏覽器中輸入http://127.0.0.1:8080/Servlet/Succeed.jsp來測試這個程式,由於我設定的是本機Ip地址被拒絕訪問,所以執行結果如下圖






5.我把本機Ip地址設定為可以訪問後,我再在瀏覽器中輸入http://127.0.0.1:8080/Servlet/Succeed.jsp來測試這個程式,執行結果如下圖


以上就是使用Servlet過濾器過濾未授權的Ip禁止訪問的全過程