Creating a simple Filter for a J2EE Java Web App. source; (Filter)

package com.web.filterexample;

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;
import javax.servlet.http.HttpServletResponse;

public class IPFilter implements Filter {

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest)servletRequest;

HttpServletResponse response = (HttpServletResponse)servletResponse;

String IP = request.getRemoteAddr(); //getting user’s IP address

System.out.println(“Your IP address is>>> ” + IP);

//Nothing to do here
//allowing user to enter the system
//continue to filter by calling doFilter method

filterChain.doFilter(servletRequest, servletResponse);
else //other IP addresses are not allowed to use the WEB application
response.sendError(403, “You are not authorized to enter the web site (SERVER talks)”);

filterChain.doFilter(servletRequest, servletResponse);

public void init(FilterConfig filterConfig) throws ServletException {
//throw new UnsupportedOperationException(“Not supported yet.”);
public void destroy() {
//throw new UnsupportedOperationException(“Not supported yet.”);


web.xml file

<xmlversion=”1.0″ encoding=”UTF-8″?>
<xmlns=”” xmlns:xsi=”” xsi:schemaLocation=”“>

index.jsp file

Document : index
Created on : May 6, 2011, 5:19:10 PM
Author : tunatore

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN””&gt;
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Calling Filter</title>
<h1>Calling Filter</h1>
<a href=”http://localhost:8084/FilterExample”>Call</a&gt;

Download WEB application source code(FilterExample)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s