Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for accessing TokenizingFilter in Servlet
Previous Home Next

In this program, a Tokenizing Filter is used for accessing StringTokenizer property for breaking a continuous string into tokens.Steps involved into creating filter class and mapping into web.xml file.check 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>TokenFilter</filter-name>
  <filter-class>r4r.Filter.TokenFilter</filter-class>
  <init-param>
<param-name>sites</param-name>
<param-value>
 www.r4r.co.in 
 www.google.com
 www.google.co.in
 www.bing.com
 </param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>TokenFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <servlet>
  <servlet-name>TokenServlet</servlet-name>
  <servlet-class>r4r.Filter.TokenServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>TokenServlet</servlet-name>
  <url-pattern>/TokenServlet</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>Tokenizing Filter!R4R</h1>
  <form action="TokenServlet" method="POST">
   Enter WebURL: <input type="text" 
     name="webURL" value="" size="30" /><br/>
    <input type="submit" value="Process URL" />
    <input type="reset" value="Reset " />
  </form>
 </body>
</html>

Filter Program

/*
 * Save as a TokenFilter.java
 */
package r4r.Filter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
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 TokenFilter implements Filter {

 private static final boolean debug = true;
 private FilterConfig filterConfig = null;
 private HashSet<String> hashSet = null;

 //default constructor
 public TokenFilter() {
 }

 /**
  * Init method for this filter 
  */
 @Override
 public void init(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  hashSet = new HashSet<String>();
  if (filterConfig != null) {
if (debug) {
 log("TokenFilter:Initializing filter");
}
//get parameters value from  <param-value> in web.xml file
String blockSites = filterConfig.getInitParameter("sites");
// store all value into HashSet<String>
for (StringTokenizer st =
	new StringTokenizer(blockSites); st.hasMoreTokens();) {
 String token = st.nextToken();
 hashSet.add(token);
}
log("Block Sites List: " + hashSet); 
//print list into server console
  }
 }

 /**
  * doFilter method for this filter
  */
 @Override
 public void doFilter(ServletRequest request,
	 ServletResponse response, FilterChain chain)
throws IOException, ServletException {
  if (debug) {
log("TokenFilter:doFilter()");
  }
  if (request instanceof HttpServletRequest) {
// get test field value from index.jsp page
String webURL = 
	((HttpServletRequest) request).getParameter("webURL");
log("Requested URL: " + webURL);
if (webURL != null) {
 // is user input value match with hastSet list value
 if (hashSet.contains(webURL)) {
  sendProcessingError(webURL, response); //invoke method
 } else {
  //send request|response to next phase of chain
  chain.doFilter(request, response);
 }
} else {
 chain.doFilter(request, response);
}
  }
 }

 /**
  * 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;
  hashSet = null;
 }

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

 // Method is used for construct a error page
 protected void sendProcessingError(String webURL,
	 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 Denied!Server declined to show this Webpage</h1>\n<pre>\n");
pw.print("Sorry, access via this URL: <b>");
pw.print(webURL);
pw.print("</b> is block by Administrator!");
pw.print("</pre></body>\n</html>"); //NOI18N
  } finally {
pw.flush();
pw.close();
  }
 }
}

Servlet Program

/*
 * Save as a TokenServlet.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 TokenServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request,
	 HttpServletResponse response)
throws ServletException, IOException {
  // doGet Role play in index.jsp
 }

 @Override
 protected void doPost(HttpServletRequest request,
	  HttpServletResponse response)
throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  //get TextField value from index.jsp page
  String webURL = request.getParameter("webURL");

  try {
//user won't allow to leave textFiled empty
if (!webURL.equals("")) {
 /*redirect response to the client to requested
 specified redirect location URL*/
 response.sendRedirect("http://" + webURL);
} else {
 out.println("Please Don't leave TextField empty!");
 out.println
	 ("<a href=\"index.jsp\">Return to Index page</a>");
}
  } finally {
out.flush(); //free resource 
out.close();
  }
 }

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