Servlet Cookie Read And Remove Project

Click here to download eclipse supported ZIP file




 

    
package com.cv.servlet.cookie;

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

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

public class DeleteCookie extends HttpServlet {
  
  private static final Logger LOGGER = Logger.getLogger(DeleteCookie.class);

  /**
   * Constructor of the object.
   */
  public DeleteCookie() {
    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
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(HttpServletRequest, HttpServletResponse) of DeleteCookie 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
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    
    LOGGER.info("Entered into doPost(HttpServletRequest, HttpServletResponse) of DeleteCookie class... ");
     Cookie cookie = null;
      Cookie[] cookies = null;
        // Get an array of Cookies associated with this domain
        cookies = request.getCookies();
        
      // Set response content type
        response.setContentType("text/html");
   
        PrintWriter out = response.getWriter();
        String title = "Delete Cookies Example";
        String docType =
        "<!doctype html public \"-//w3c//dtd html 4.0 " +
        "transitional//en\">\n";
        out.println(docType +
                  "<html>\n" +
                  "<head><title>" + title + "</title></head>\n" +
                  "<body bgcolor=\"#f0f0f0\">\n" );
         ifcookies != null ){
           out.println("<h2> Cookies Name and Value</h2>");
           for (int i = 0; i < cookies.length; i++){
              cookie = cookies[i];
              if((cookie.getName( )).compareTo("first_name"== ){
                   cookie.setMaxAge(0);
                   response.addCookie(cookie);
                   out.print("Deleted cookie : " 
                                cookie.getName( ) "<br/>");
              }
              out.print("Name : " + cookie.getName( ) ",  ");
              out.print("Value: " + cookie.getValue( )+" <br/>");
           }
        }else{
            out.println(
              "<h2>No cookies founds</h2>");
        }
        out.println("</body>");
        out.println("</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.cookie;

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

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

public class MyCookie extends HttpServlet {
  private static final Logger LOGGER = Logger.getLogger(MyCookie.class);
  /**
   * Constructor of the object.
   */
  public MyCookie() {
    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
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    
    LOGGER.info("Entered into doGet(HttpServletRequest, HttpServletResponse) of MyCookie 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
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doPost(HttpServletRequest, HttpServletResponse) of MyCookie class... ");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out
        .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println("  <BODY>");
    out.print("    This is ");
    out.print(this.getClass());
  
    Cookie cookie = new Cookie("url","chote");
    cookie.setMaxAge(60*1)//1 hour
    response.addCookie(cookie);
 
    out.println("Cookies created");
    out.println(", using the POST method");
    out.println("  </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
  }

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

}


 

    
package com.cv.servlet.cookie;

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

import javax.servlet.RequestDispatcher;
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 org.apache.log4j.Logger;

public class MyCookie2 extends HttpServlet {
  
  private static final Logger LOGGER = Logger.getLogger(MyCookie2.class);
  /**
   * Constructor of the object.
   */
  public MyCookie2() {
    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
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(HttpServletRequest, HttpServletResponse) of MyCookie2 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
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doPost(HttpServletRequest, HttpServletResponse) of MyCookie2 class... ");
    // Set response content type
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String string1 = getServletContext().getInitParameter("first_name");
    String string2 = getServletContext().getInitParameter("last_name");
    System.out.println(string1);
    System.out.println(string2);
    // Create cookies for first and last names.
    Cookie firstName = new Cookie("first_name", string1);
    Cookie lastName = new Cookie("last_name", string2);

    // Set expiry date after 24 Hrs for both the cookies.
    // firstName.setMaxAge(60*1);
    // lastName.setMaxAge(60*6);

    // Add both the cookies in the response header.
    response.addCookie(firstName);
    response.addCookie(lastName);

    String title = "Setting Cookies Example";
    String docType = "<!doctype html public \"-//w3c//dtd html 4.0 "
        "transitional//en\">\n";
    out.println(docType + "<html>\n" "<head><title>" + title
        "</title></head>\n" "<body bgcolor=\"#f0f0f0\">\n"
        "<h1 align=\"center\">" + title + "</h1>\n" "<ul>\n"
        "  <li><b>First Name</b>: " + string1 + "\n"
        "  <li><b>Last Name</b>: " + string2 + "\n" "</ul>\n"
        "</body></html>");

    // request.setAttribute("mycoo",firstName );

    RequestDispatcher dispatcher = request
        .getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);

    /*
     * RequestDispatcher dispatcher = request
     * .getRequestDispatcher("/ReadCookie"); dispatcher.forward(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.cookie;

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

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

public class ReadCookie extends HttpServlet {
  private static final Logger LOGGER = Logger.getLogger(ReadCookie.class);
  /**
   * Constructor of the object.
   */
  public ReadCookie() {
    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
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(HttpServletRequest, HttpServletResponse) of ReadCookie class... ");
    System.out.println("control come to read");
      // Set response content type
        response.setContentType("text/html");
   
        PrintWriter out = response.getWriter();

        Cookie cookie = null;
      Cookie[] cookies = null;
        // Get an array of Cookies associated with this domain
        cookies = request.getCookies();
        
        String title = "Reading Cookies Example";
        String docType =
        "<!doctype html public \"-//w3c//dtd html 4.0 " +
        "transitional//en\">\n";
        out.println(docType +
                  "<html>\n" +
                  "<head><title>" + title + "</title></head>\n" +
                  "<body bgcolor=\"#f0f0f0\">\n" );
        ifcookies != null ){
           out.println("<h2> cv Found Cookies Name and Value</h2>");
           for (int i = 0; i < cookies.length; i++){
              cookie = cookies[i];
              out.print("Name : " + cookie.getName( ) ",  ");
              out.print("Value: " + cookie.getValue( )+" <br/>");
           }
        }else{
            out.println(
              "<h2>No cookies founds</h2>");
        }
        out.println("</body>");
        out.println("</html>");
  }

  /**
   * 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 response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doPost(HttpServletRequest, HttpServletResponse) of ReadCookie class... ");
    doGet(request, response);
  }

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

}



<html>
<body>
<form action="MyCookie2" method="POST" id='test'>
<fieldset>
<legend>Wow... Plz Enter login credentials...</legend>
<table align="center">
<tr>
<td><label>Enter First Name : </label><input type="text"
name="first_name" /></td>
</tr>

<tr>
<td><label>Enter last Name : </label><input type="text"
name="last_name" /></td>
</tr>
<tr>
<td align="right"><input type="submit" value="submit" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>



<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<fieldset>
<legend>Result page...</legend>
<table align="center">
<tr>
<td><label> I am from {cookie.first_name.value} : </label></td>

<td><font color="RED">${cookie.first_name.value}</font></td>
</tr>

<tr>
<td><label> I am from {cookie.last_name.value} : </label></td>

<td><font color="RED">${cookie.last_name.value}</font></td>
</tr>

<tr>
<td><label>With scripting : : </label></td>

<td><font color="RED"><%= getServletContext().getInitParameter("first_name") %></font></td>
</tr>

<tr>
<td><label>With implicit obj :  : </label></td>

<td><font color="RED"><%= application.getInitParameter("last_name") %></font></td>
</tr>

<tr>
<td><label>With EL first name :  : </label></td>

<td><font color="RED">${ initParam.first_name }</font></td>
</tr>
<tr>
<td><label>With EL last name :  : </label></td>

<td><font color="RED">${ initParam.last_name }</font></td>
</tr>

<tr>
<td><label> With EL mid name :  : </label></td>

<td><font color="RED"> ${ initParam.mid_name }</font></td>
</tr>

</table>
</fieldset>
</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>ServletCookieReadAndRemoveProject</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.ServletCookieReadAndRemoveProject</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>MyCookie</servlet-name> <servlet-class>com.cv.servlet.cookie.MyCookie</servlet-class> <init-param> <param-name>mid_name</param-name> <param-value>vardhan</param-value> </init-param> </servlet> <context-param> <param-name>mid_name</param-name> <param-value>vardhan</param-value> </context-param> <context-param> <param-name>first_name</param-name> <param-value>chandra</param-value> </context-param> <context-param> <param-name>last_name</param-name> <param-value>kodam</param-value> </context-param> <servlet> <servlet-name>MyCookie2</servlet-name> <servlet-class>com.cv.servlet.cookie.MyCookie2</servlet-class> </servlet> <servlet> <servlet-name>ReadCookie</servlet-name> <servlet-class>com.cv.servlet.cookie.ReadCookie</servlet-class> </servlet> <servlet> <servlet-name>DeleteCookie</servlet-name> <servlet-class>com.cv.servlet.cookie.DeleteCookie</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyCookie</servlet-name> <url-pattern>/MyCookie</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>MyCookie2</servlet-name> <url-pattern>/MyCookie2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ReadCookie</servlet-name> <url-pattern>/ReadCookie</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DeleteCookie</servlet-name> <url-pattern>/DeleteCookie</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>first.html</welcome-file> </welcome-file-list> </web-app>


No comments:

Post a Comment