Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for block client site through filter in servlet
Previous Home Next

In this servlet application, a Filter is created for filter client site request and block some requested resource in Servlet.Steps involved in create filter class and mapping into web.xml file.click here

Application directory structure

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
 xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <filter>
  <filter-name>BlockSiteFilter</filter-name>
  <filter-class>r4r.Filter.BlockSiteFilter</filter-class>
  <init-param>
<!-- Parameter values is call when filter initialize -->
<param-name>blockSite</param-name>
<param-value>http://localhost:8084/BlockSiteFilter/SiteServlet
      </param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>BlockSiteFilter</filter-name>
  <servlet-name>SiteServlet</servlet-name>
 </filter-mapping>
 <servlet>
  <servlet-name>SiteServlet</servlet-name>
  <servlet-class>r4r.Filter.SiteServlet</servlet-class>
 </servlet>
 <servlet>
  <servlet-name>TestServlet</servlet-name>
  <servlet-class>r4r.Filter.TestServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>SiteServlet</servlet-name>
  <url-pattern>/SiteServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>TestServlet</servlet-name>
  <url-pattern>/TestServlet</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>
30
  </session-timeout>
 </session-config>
</web-app>

Index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-Index</title>
 </head>
 <body>
  <h1>Client Site Filter!Access Servlet through Link</h1>
  Block Client Servlet through Filter
  <ol>
   <li><a href="SiteServlet">SiteServlet</a></li>
   <li><a href="TestServlet">TestServlet</a></li>
  </ol>
 </body>
</html>

Filter Program

/*
 * Save as a BlockSiteFilter.java
 */
package r4r.Filter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
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.HttpServletRequest;
/**
 *
 * @author R4R
 */
public class BlockSiteFilter implements Filter {

 private static final boolean debug = true;
 private FilterConfig filterConfig = null;
 private Set<String> blockSites = null;

 // constructor
 public BlockSiteFilter() {
 }

 /**
  * Init method for this filter 
  */
 @Override
 public void init(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  blockSites = new HashSet<String>();
  if (filterConfig != null) {
if (debug) {
 log("BlockSiteFilter:Initializing filter");
}
//get parameter value from web.xml file
String blockSite = filterConfig.getInitParameter("blockSite");
for (StringTokenizer st = 
	  new StringTokenizer(blockSite); st.hasMoreTokens();) {
 String token = st.nextToken();
 blockSites.add(token); // Add value into Set
}
log("Block Site: " + blockSites);
  }
 }

 /**
  *
  * @param request The servlet request we are processing
  * @param response The servlet response we are creating
  * @param chain The filter chain we are processing
  */
 @Override
 public void doFilter(ServletRequest request,
	  ServletResponse response, FilterChain chain)throws IOException,
	 ServletException {
  if (debug) {
log("BlockSiteFilter:doFilter()");
  }
  if (request instanceof HttpServletRequest) {
//take client URL and match with Set value
String clientURL = 
	((HttpServletRequest) request).getRequestURL().toString();
log("RequestedURL: " + clientURL);
if (blockSites.contains(clientURL)) {
 sendProcessingError(clientURL, response); //invoke method
} else {
 chain.doFilter(request, response);
   //send request|response to next phase of chain
}
  }
 }

 /**
  * Return the filter configuration object for this filter.
  */
 public FilterConfig getFilterConfig() {
  return (this.filterConfig);
 }

 /**
  * Set the filter configuration object for this filter.
  */
 public void setFilterConfig(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
 }

 /**
  * Destroy method for this filter 
  */
 @Override
 public void destroy() {
  filterConfig = null;
  blockSites = null;
 }

 // Method is used for construct a error page
 private void sendProcessingError
	   (String clientURL, ServletResponse response)
throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter pw = response.getWriter();

  try {
pw.print
("<html>\n<head>\n<title>Error Page</title>\n</head>\n<body>\n"); //NOI18N
pw.print
("<h1>Access Prohibited!Server declined to show thisWebpage</h1>\n<pre>\n");
pw.print("Sorry, access via this URL: <b>");
pw.print(clientURL);
pw.print("</b> \nis block by Administrator");
pw.print("</pre></body>\n</html>"); //NOI18N
  } finally {
pw.flush(); // free resource
pw.close();
  }
 }

 /**
  * log method for print msg over server console 
  */
 public void log(String msg) {
  filterConfig.getServletContext().log(msg);
 }
}

Servlet Program

/*
 * Save as a SiteServlet.java
 */
package r4r.Filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author R4R
 */
public class SiteServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException
{
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  try {
/* TODO output your page here */
out.println("<html>");
out.println("<head>");
out.println("<title>" + getServletInfo() + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet SiteServlet at " 
	 + request.getContextPath() + "</h1>");
out.println
  ("Never access this servlet, unless access is block in Filter!");
out.println("<a href=\"index.jsp\">Return to Index page</a>");
out.println("</body>");
out.println("</html>");
  } finally {
out.close();
  }
 }

 @Override
 protected void doGet(HttpServletRequest request,
	 HttpServletResponse response)throws ServletException,IOException 
{
  processRequest(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException
{
  processRequest(request, response);
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-SiteServlet";
 }
}

Test program

/*
 * Save as a TestServlet.java
 */
package r4r.Filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author R4R
 */
public class TestServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException 
	 {
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();
      try {
      /* TODO output your page here */
	out.println("<html>");
	out.println("<head>");
	out.println("<title>" + getServletInfo() + "</title>");
	out.println("</head>");
	out.println("<body>");
	out.println("<h1>Servlet TestServlet at " 
			+ request.getContextPath() + "</h1>");
	out.println("This servlet won't block through Filter, yet!");
	out.println("<a href=\"index.jsp\">Return to Index page</a>");
	out.println("</body>");
out.println("</html>");
  } finally {
out.close();
  }
 }

 @Override
 protected void doGet
	(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  processRequest(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request,
	 HttpServletResponse response)
throws ServletException, IOException {
  processRequest(request, response);
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-TestServlet";
 }
}
Output of Program
Previous Home Next