Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

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

In this program, an AuthenticationFilter is used for authenticating user through login name and password through filter. Steps involved in creating 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>AuthenticateFilter</filter-name>
  <filter-class>r4r.Filter.AuthenticateFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>AuthenticateFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <servlet>
  <servlet-name>AuthenticateServlet</servlet-name>
  <servlet-class>r4r.Filter.AuthenticateServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>AuthenticateServlet</servlet-name>
  <url-pattern>/AuthenticateServlet</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>Authentication Filter!R4R</h1>
  <form action="AuthenticateServlet" method="POST">
  Login As: <select name="loginType">
  <option>Administration</option>
  <option>Client</option>
  </select><br/>
  Username: <input type="text" name="user" 
        value="" size="20" maxlength="10" /><br/>
  Password: <input type="password" name="pass"
        value="" size="20" maxlength="10" /><br/>
  <input type="submit" value="Log In" />
  <input type="reset" value="Reset" />
  </form>
<p>Administration: admin, admin| Client: client, client</p> 
 </body>
</html>

Filter Program

/*
 * Save as a AuthenticateFilter.java
 */
package r4r.Filter;

import java.io.IOException;
import java.io.PrintWriter;
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 AuthenticateFilter implements Filter {

 private static final boolean debug = true;
 private FilterConfig filterConfig = null;

 // default constructor
 public AuthenticateFilter() {
 }

 /**
  * Init method for this filter 
  */
 @Override
 public void init(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  if (filterConfig != null) {
if (debug) {
 log("AuthenticateFilter:Initializing filter");
}
  }
 }

 /**
  * doFilter method for this filter 
  */
 @Override
 public void doFilter(ServletRequest request,
	 ServletResponse response, FilterChain chain)
  throws IOException, ServletException 
	{
  boolean isAuthenticate = false;
  String username = null, password = null;
  if (debug) {
log("AuthenticateFilter:doFilter()");
  }

  if (request instanceof HttpServletRequest) {
// get value from index.jsp page
String loginAs = 
	((HttpServletRequest) request).getParameter("loginType");
log("Login Type: " + loginAs); // display over server console
if (loginAs != null) {
 // get value from index.jsp page
 username = ((HttpServletRequest) request).getParameter("user");
 password = ((HttpServletRequest) request).getParameter("pass");
 log("Username: " + username + " && Password: " + password);
 if (loginAs.equals("Administration")) {
  if (username.equals("admin") && password.equals("admin")) {
isAuthenticate = true;
  } else {
isAuthenticate = false;
  }
 } else {
  if (username.equals("client") && password.equals("client")) {
isAuthenticate = true;
  } else {
isAuthenticate = false;
  }
 }
 // check is user authenticate
 if (isAuthenticate) {
  //send request|response to next phase of chain
  chain.doFilter(request, response);
 } else {
  sendProcessingError(username, password, 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;
 }

 /**
  * 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
 private void sendProcessingError
	 (String username, String password, ServletResponse response)
throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter pw = response.getWriter();

  try {
pw.print("<html>\n<head>\n<title>Login Error</title>\n</head>\n<body>\n"); //NOI18N
pw.print("<h1>Access Denied! Login Failure</h1>\n<pre>\n");
pw.print("Username: <b>");
pw.print(username);
pw.print("</b> and Password: <b>");
pw.print(password);
pw.print("</b> doesn't match!");
pw.print("</pre></body>\n</html>"); //NOI18N
  } finally {
pw.flush(); // free resource
pw.close();
  }
 }
}

Servlet Program

/*
 * Save as a AuthenticateServlet.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 AuthenticateServlet 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();

  try {
out.write("<html>");
out.write("<head>");
out.write("<title>" + getServletInfo() + "</title>");
out.write("</head>");
out.write("<body>");
out.write("<h1>Login Success! Welcome to R4R</h1>");
out.write("Access account type: <b>"
           + request.getParameter("loginType") + "</b><br/>");
out.write("Username: <b>"
           + request.getParameter("user") + " </b>");
out.write("Password: <b>" 
	        + request.getParameter("pass") + " </b>");
out.write("</body>");
out.write("</html>");
out.println("<br/><a href=\"index.jsp\">Return to index page</a>");
  } finally {
out.flush();
out.close();
  }
 }

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