Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

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

In this program, a resource (like MySQL database) is accessed in filter.Steps involved in 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>ResourceFilter</filter-name>
  <filter-class>r4r.Filter.ResourceFilter</filter-class>
  <init-param>
<param-name>className</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
  </init-param>
  <init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost</param-value>
  </init-param>
  <init-param>
<param-name>user</param-name>
<param-value>root</param-value>
  </init-param>
  <init-param>
<param-name>password</param-name>
<param-value>root</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>ResourceFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-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>Resource access Filter!R4R</h1>
  <form method="POST">
    Enter Name: <input type="text" name="name"
	    value="" size="20" maxlength="10" /><br/>
   <p> ---- OR ---- </p>
   Country: <input type="text" name="country"
      value="" size="20" maxlength="10"/><br/>
   <input type="submit" value="Submit Record" />
   <input type="reset" value="Reset Record" />
  </form>
 </body>
</html>

Filter Program

/*
 * Save as a ResourceFilter.java
 */
package r4r.Filter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
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 ResourceFilter implements Filter {

 private static final boolean debug = true;
 private FilterConfig filterConfig = null;
 private String sql_className = null;
 private String sql_url = null;
 private String sql_user = null;
 private String sql_password = null;

 // default constructor
 public ResourceFilter() {
 }

 /**
  * Init method for this filter 
  */
 @Override
 public void init(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  if (filterConfig != null) {
if (debug) {
 log("ResourceFilter:Initializing filter");
}
//get parameters value from  <param-value> in web.xml file
sql_className = filterConfig.getInitParameter("className");
sql_url = filterConfig.getInitParameter("url");
sql_user = filterConfig.getInitParameter("user");
sql_password = filterConfig.getInitParameter("password");
log("SQL: " + sql_className + " , " 
	+ sql_url + " , " + sql_user + " , " + sql_password);
  }
 }

 /**
  * doFilter method for this filter
  */
 @Override
 public void doFilter(ServletRequest request,
	 ServletResponse response, FilterChain chain)
throws IOException, ServletException {
  if (debug) {
log("ResourceFilter:doFilter()");
  }
  java.sql.Connection conn = null;
  PrintWriter out = response.getWriter();

  if (request instanceof HttpServletRequest) {
// get textField value from index.jsp page
String name = request.getParameter("name");
String country = request.getParameter("country");
log("Name: " + name + " & Countary: " + country);
if (name != null || country != null) 
{
// MySQL database connectivity and fetch specific data from table
 try {
  Class.forName(sql_className).newInstance();
  conn = DriverManager.getConnection
	    (sql_url, sql_user, sql_password);
  Statement s = conn.createStatement();
  ResultSet rs = s.executeQuery
	   ("Select * from R4R.CUSTOMER where name='" + name
 + "' or country='" + country + "'");

  out.println
("<table border=\"1\" cellspacing=\"2\" cellpadding=\"2\">");
  out.println("<thead><tr>");
  out.println("<td> Id </td>");
  out.println("<td> Name </td>");
  out.println("<td> Gender </td>");
  out.println("<td> Email </td>");
  out.println("<td> City </td>");
  out.println("<td> State </td>");
  out.println("<td> Country </td>");
  out.println("</thead></tr>");
  while (rs.next()) {
out.println("<tbody><tr>");
out.println("<td> " + "<b>" 
	 + rs.getInt(1) + "</b>" + "</td>");
out.println("<td> " + "<b>"
     + rs.getString(2) + "</b>" + "</td>");
out.println("<td> " + "<b>" 
	 + rs.getString(3) + "</b>" + "</td>");
out.println("<td> " + "<b>"
     + rs.getString(4) + "</b>" + "</td>");
out.println("<td> " + "<b>"
     + rs.getString(5) + "</b>" + "</td>");
out.println("<td> " + "<b>" 
	 + rs.getString(6) + "</b>" + "</td>");
out.println("<td> " + "<b>" 
	 + rs.getString(7) + "</b>" + "</td>");
out.println("</tr></tbody>");
  }
 } catch (Exception ex) {
  Logger.getLogger
	  (ResourceFilter.class.getName()).log(Level.SEVERE,
 "An exception occur", ex);
 } finally {
  try {
conn.close();
out.close();
  } catch (SQLException ex) {
Logger.getLogger
	(ResourceFilter.class.getName()).log(Level.SEVERE,
  "An SQLException occur", ex);
  }
 }
} 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;
  sql_className = null;
  sql_url = null;
 }

 /**
  * log method for print msg over server console 
  */
 public void log(String msg) {
  filterConfig.getServletContext().log(msg);
 }
}
Output of Program
Previous Home Next