Servlet Advanced Filter Project

Click here to download eclipse supported ZIP file




 

    
package com.cv.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;


/**
 * Servlet implementation class AuthenticationFilter
 
 @author Chandra Vardhan
 
 */
public class AuthenticationFilter implements Filter {

  
  private static final Logger LOGGER = Logger.getLogger(AuthenticationFilter.class);

  private ServletContext context;

  public void init(FilterConfig fConfigthrows ServletException {
    LOGGER.info("LOGGER : init(FilterConfig) called... AuthenticationFilter initialized...");
    this.context = fConfig.getServletContext();
    this.context.log("AuthenticationFilter initialized");
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    LOGGER.info("LOGGER : doFilterr(ServletRequest, ServletResponse, FilterChain) called... AuthenticationFilter");
    HttpServletRequest httpRequest = (HttpServletRequestrequest;
    HttpServletResponse httpResponse = (HttpServletResponseresponse;
    String uri = httpRequest.getRequestURI();
    this.context.log("Requested Resource URI is :: " + uri);
    LOGGER.info("LOGGER : Requested Resource URI is :: " + uri);
    HttpSession session = httpRequest.getSession(false);
    if (session == null && !(uri.endsWith("html"|| uri.endsWith("LoginServlet"))) {
      this.context.log("Unauthorized access request");
      LOGGER.info("Unauthorized access request!!! Redirecting to the login.html...");
      httpResponse.sendRedirect("login.html");
    else {
      // pass the request along the filter chain      
      LOGGER.info("Authorized access request!!! Redirecting to the Another Filter/Servlet...");
      chain.doFilter(request, response);
    }
  }

  public void destroy() {
    LOGGER.info("destroy called... AuthenticationFilter");
    // close any resources here
  }

}


 

    
package com.cv.servlet.filter;

import java.io.IOException;

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 org.apache.log4j.Logger;

/**
 * Servlet implementation class AuthenticationFilter
 
 @author Chandra Vardhan
 
 */
public class BasicFilter implements Filter {
  private static final Logger LOGGER = Logger.getLogger(BasicFilter.class);

  public void init(FilterConfig fConfigthrows ServletException {
    LOGGER.info("init(FilterConfig) called... BasicFilter");

  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chainthrows IOException, ServletException {
    LOGGER.info("Before doFilter((ServletRequest,ServletResponse,FilterChain) called... BasicFilter");

    chain.doFilter(request, response);
    
    LOGGER.info("After doFilter((ServletRequest,ServletResponse,FilterChain) called... BasicFilter");

  }

  public void destroy() {
    LOGGER.info("destroy() called... BasicFilter");
    
  }

}


 

    
package com.cv.servlet.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class LoginServlet
 
 *  @author Chandra Vardhan
 *  
 */

public class LoginServlet extends HttpServlet {
  

  
  private final String userID = "chandra";
  private final String password = "kodam";

  


  private static final Logger LOGGER = Logger.getLogger(LoginServlet.class);

  /**
   * Constructor of the object.
   */
  public LoginServlet() {
    super();
  }

  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy()// Just puts "destroy" string in log
    // Put your code here
  }

  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   
   @param request
   *            the request send by the client to the server
   @param response
   *            the response send by the server to the client
   @throws ServletException
   *             if an error occurred
   @throws IOException
   *             if an error occurred
   */
  
  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    LOGGER.info("Entered into doGet(HttpServletRequest ,HttpServletResponse ) of LoginServlet class... ");
  
    String user = request.getParameter("userName");
    String pwd = request.getParameter("password");

    if (userID.equals(user&& password.equals(pwd)) {      
      ServletContext context = getServletContext();      
      context.setAttribute("user2""chandra");
            
      HttpSession session = request.getSession();
      session.setAttribute("user1""chandra");      
      session.setMaxInactiveInterval(30 60);
      
      Cookie userName = new Cookie("user", user);
      userName.setMaxAge(30 60);
      response.addCookie(userName);
      response.sendRedirect("success.jsp");
    else {
      RequestDispatcher rd = getServletContext().getRequestDispatcher(
          "/login.html");
      PrintWriter out = response.getWriter();
      out.println("<font color=red>Either user name or password is wrong. Please look at logs... </font>");
      LOGGER.info("Enter username = 'chandra' and password = 'kodam' ... ");
      
      rd.include(request, response);
    }

  }
  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to
   * post.
   
   @param request
   *            the request send by the client to the server
   @param response
   *            the response send by the server to the client
   @throws ServletException
   *             if an error occurred
   @throws IOException
   *             if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {

    LOGGER.info(
        "Entered into doPost(HttpServletRequest ,HttpServletResponse ) of LoginServlet class... ");
    doGet(request, response);
  }

  /**
   * Initialization of the servlet. <br>
   *
   @throws ServletException
   *             if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }

}


 

    
package com.cv.servlet.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class LogoutServlet
 
 *  @author Chandra Vardhan
 *  
 */

public class LogoutServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  private static final Logger LOGGER = Logger.getLogger(LogoutServlet.class);

  /**
   * Constructor of the object.
   */
  public LogoutServlet() {
    super();
  }

  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy()// Just puts "destroy" string in log
    // Put your code here
  }

  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   
   @param request
   *            the request send by the client to the server
   @param response
   *            the response send by the server to the client
   @throws ServletException
   *             if an error occurred
   @throws IOException
   *             if an error occurred
   */

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(HttpServletRequest ,HttpServletResponse ) of LoginServlet class... ");
    doPost(request, response);

  }

  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to
   * post.
   
   @param request
   *            the request send by the client to the server
   @param response
   *            the response send by the server to the client
   @throws ServletException
   *             if an error occurred
   @throws IOException
   *             if an error occurred
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doPost(HttpServletRequest ,HttpServletResponse ) of LoginServlet class... ");
    response.setContentType("text/html");
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie != null && cookie.getName().equals("JSESSIONID")) {
          LOGGER.info("JSESSIONID=" + cookie.getValue());
          break;
        }
      }
    }
    // invalidate the session if exists
    HttpSession session = request.getSession(false);
    LOGGER.info("User=" + session.getAttribute("user"));
    if (session != null) {
      session.invalidate();
    }
    response.sendRedirect("login.html");
  }

  /**
   * Initialization of the servlet. <br>
   *
   @throws ServletException
   *             if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }

}


 

    
package com.cv.servlet.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * Servlet Filter implementation class RequestLoggingFilter
 
 @author Chandra Vardhan
 
 */

public class RequestLoggingFilter implements Filter {
  
  private static final Logger LOGGER = Logger.getLogger(RequestLoggingFilter.class);

  private ServletContext context;
  
  public void init(FilterConfig fConfigthrows ServletException {
    LOGGER.info("LOGGER : init(FilterConfig) RequestLoggingFilter initialized... ");
    this.context = fConfig.getServletContext();
    this.context.log("RequestLoggingFilter initialized");
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chainthrows IOException, ServletException {
    LOGGER.info("LOGGER : doFilter(ServletRequest, ServletResponse, FilterChain) ... RequestLoggingFilter");
    HttpServletRequest req = (HttpServletRequestrequest;
    Enumeration<String> params = req.getParameterNames();
    while(params.hasMoreElements()){
      String name = params.nextElement();
      String value = request.getParameter(name);
      this.context.log(req.getRemoteAddr() "::Request Params::{"+name+"="+value+"}");
      LOGGER.info("LOGGER : "+req.getRemoteAddr() "::Request Params::{"+name+"="+value+"}");
    }
    
    Cookie[] cookies = req.getCookies();
    if(cookies != null){
      for(Cookie cookie : cookies){
        this.context.log(req.getRemoteAddr() "::Cookie::{"+cookie.getName()+","+cookie.getValue()+"}");
        LOGGER.info("LOGGER : "+req.getRemoteAddr() "::Cookie::{"+cookie.getName()+","+cookie.getValue()+"}");
      }
    }
    // pass the request along the filter chain
    chain.doFilter(request, response);
  }

  public void destroy() {
    //we can close resources here
    LOGGER.info("destroy ... RequestLoggingFilter");
  }

}



<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%String userName = null;
if (session.getAttribute("user1") == null) {
if(application.getAttribute("user2") != null) {
userName = (String)application.getAttribute("user2");
} else {
response.sendRedirect("login.html");
}
}

String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user")) {
userName = cookie.getValue();
}
}
}
%>
<h3>Hi ${userName}, do the checkout.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout">
</form>
</body>
</html>



<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="userName"> <br> Password:
<input type="password" name="password"> <br> <input
type="submit" value="Login">
</form>
</body>
</html>



<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = null;
if (session.getAttribute("user1") == null) {
if (application.getAttribute("user2") != null) {
user = (String) application.getAttribute("user2");
} else {
response.sendRedirect("login.html");
}
} else
user = (String) session.getAttribute("user1");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user"))
userName = cookie.getValue();
if (cookie.getName().equals("JSESSIONID"))
sessionID = cookie.getValue();
}
}
if(user != null && userName == null) {
userName=user ;
}
%>
<h3>
Hi
<%=userName%>, Login successful. Your Session ID=<%=sessionID%></h3>
<br> User=<%=user%>
<br>
<a href="CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout">
</form>
</body>
</html>



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n




<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>ServletAdvancedtFilterProject</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <log4j.version>1.2.16</log4j.version> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <groupId>com.cv.servlet.zip</groupId> </project>




 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.cv.servlet.filter.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.cv.servlet.filter.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/LogoutServlet</url-pattern> </servlet-mapping> <filter> <filter-name>RequestLoggingFilter</filter-name> <filter-class>com.cv.servlet.filter.RequestLoggingFilter</filter-class> </filter> <filter> <filter-name>AuthenticationFilter</filter-name> <filter-class>com.cv.servlet.filter.AuthenticationFilter</filter-class> </filter> <filter> <filter-name>BasicFilter</filter-name> <filter-class>com.cv.servlet.filter.BasicFilter</filter-class> </filter> <filter-mapping> <filter-name>RequestLoggingFilter</filter-name> <url-pattern>/LoginServlet</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenticationFilter</filter-name> <url-pattern>/LoginServlet</url-pattern> </filter-mapping> <filter-mapping> <filter-name>BasicFilter</filter-name> <url-pattern>/LoginServlet</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.html</welcome-file> </welcome-file-list> </web-app>


No comments:

Post a Comment