IP Filter

IP Filter


Posted in : Servlet Posted on : December 2, 2010 at 6:32 PM Comments : [ 0 ]

This section contains the details about IP Filter.

IP Filter

A filter is an object that can transform a request or alter a response. Filters not create a response like servlet. It process request before it reaches to a servlet and can process response before it leaves to a servlet.

Given below filter provides a basic security  mechanism for a firewall to determining what traffic passes through the firewall based on IP address details :

IPFilterExample.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import java.io.IOException;
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.HttpServletResponse;

public class IPFilterExample implements Filter{
public IPFilterExample() {}
public final static String IP = "127.0.0.1";
private FilterConfig filterConfig;

public void init(FilterConfig config) throws ServletException{
this.filterConfig = config;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>IP Filter Example</title></head>");
String userip = request.getRemoteAddr();
HttpServletResponse httpResponse = null;
if (response instanceof HttpServletResponse){
httpResponse = (HttpServletResponse) response;
}
if (IP.equals(userip)) {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"You are not allowed 
to access the servlet!"); 
} else {
filterchain.doFilter(request, response);
out.println("<body><h3><font color='green'>Passed successfully from IP Filter
<font></h3></body></html>"+userip);
}
}
public void destroy() {}
}

CallIpFilter.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CallIpFilter extends HttpServlet{ 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>IP Filter Example</title></title>");
pw.println("<body>");
pw.println("<h1>Welcome, calling servlet successful</h1>");
pw.println("</body></html>");
}
}

Output

If IP is 127.0.0.1 , it will display following message :

If it is not 127.0.0.1, it will show the following message :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics