RSS

Monthly Archives: March 2013

Declarative Security

Declarative Security Download

 
Leave a comment

Posted by on March 30, 2013 in Material

 

Session Tracking

Session Tracking Download

 
Leave a comment

Posted by on March 26, 2013 in Material

 

Another Example of Session Tracking

Orderform.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>Order Form</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>Order Form</H1>
<FORM ACTION="ShowItems">
  New Item to Order:
  <INPUT TYPE="TEXT" NAME="newItem" VALUE="Pen"><P>
  <INPUT TYPE="SUBMIT" VALUE="Order and Show All Purchases">
</FORM>
</CENTER></BODY></HTML>

ShowItems.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ShowItems extends HttpServlet
{
  public void doGet(HttpServletRequest request,HttpServletResponse response)
      throws ServletException, IOException 
	  {
	 // getSession() 
     // Returns the current session associated with this request,
     //	or if the request does not have a session, creates one.
	 
    HttpSession session = request.getSession();
    ArrayList previousItems =
      (ArrayList)session.getAttribute("previousItems");
    if (previousItems == null) {
      previousItems = new ArrayList();
      session.setAttribute("previousItems", previousItems);
    }
    String newItem = request.getParameter("newItem");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Items Purchased";
    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=\"#FDF5E6\">\n" +
                "<H1>" + title + "</H1>");
    synchronized(previousItems) {
      if (newItem != null) {
        previousItems.add(newItem);
      }
      if (previousItems.size() == 0) {
        out.println("<I>No items</I>");
      } else {
        out.println("<UL>");
        for(int i=0; i<previousItems.size(); i++) {
          out.println("<LI>" + (String)previousItems.get(i));
        }
        out.println("</UL>");
      }
    }
    out.println("</BODY></HTML>");
  }
}
 
Leave a comment

Posted by on March 26, 2013 in Example

 

Example of Session Tracking

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Date;

public class SessionServlet extends HttpServlet implements Servlet {
       
  public SessionServlet() {}

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Demo";
    String heading;
    Integer accessCount = new Integer(0); 
    if (session.isNew()) 
    {
      heading = "Welcome, Newcomer";
    } 
    else 
   {
      heading = "Welcome Back";
      Integer oldAccessCount = (Integer)session.getAttribute("accessCount"); 
      if (oldAccessCount != null)
      {
        accessCount = new Integer(oldAccessCount.intValue() + 1);
      }
    }
    session.setAttribute("accessCount", accessCount); 
      
    out.println(""+title+"\n" +
                "\n" +
                "<H1>" + heading + "</H1>\n" +
                "<H2>Information on Your Session:</H2>\n" +
                "<TABLE BORDER="1" ALIGN="CENTER">\n" +
                "<TR>\n" +
                "  <TH>Info Type<TH>Value\n" +
                "<TR>\n" +
                "  <TD>ID\n" +
                "  <TD>" + session.getId() + "\n" +
                "<TR>\n" +
                "  <TD>Creation Time\n" +
                "  <TD>" + new Date(session.getCreationTime()) + "\n" +
                "<TR>\n" +
                "  <TD>Time of Last Access\n" +
                "  <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
                "<TR>\n" +
                "  <TD>Number of Previous Accesses\n" +
                "  <TD>" + accessCount + "\n" +
                "</TABLE>\n" +
                "");

  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException 
   {
    doGet(request, response);
  }
}

 
Leave a comment

Posted by on March 26, 2013 in Example

 

Cookie

Cookie Download

 
Leave a comment

Posted by on March 6, 2013 in Material

 

Using Cookies to Remember User Preferences

RegistrationForm.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Servlet that displays an HTML form to collect user's
 *  first name, last name, and email address. Uses cookies
 *  to determine the initial values of each of those
 *  form fields.
 */

public class RegistrationForm extends HttpServlet {
  public void doGet(HttpServletRequest request,HttpServletResponse response)
      throws ServletException, IOException 
	  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String actionURL ="/RegistrationServlet";
    String firstName =CookieUtilities.getCookieValue(request, "firstName", "");
    String lastName =CookieUtilities.getCookieValue(request, "lastName", "");
    String emailAddress =CookieUtilities.getCookieValue(request, "emailAddress","");
    String title = "Please Register";
    out.println(
       "<HTML>\n" +
       "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
       "<BODY BGCOLOR=\"#FDF5E6\">\n" +
       "<CENTER>\n" +
       "<H1>" + title + "</H1>\n" +
       "<FORM ACTION=\"" + actionURL + "\">\n" +
       "First Name:\n" +
       "  <INPUT TYPE=\"TEXT\" NAME=\"firstName\" " +
                 "VALUE=\"" + firstName + "\"><BR>\n" +
       "Last Name:\n" +
       "  <INPUT TYPE='TEXT' NAME='lastName' " +
                        "VALUE=\"" + lastName + "\"><BR>\n" +
       "Email Address: \n" +
       "  <INPUT TYPE=\"TEXT\" NAME=\"emailAddress\" " +
                 "VALUE=\"" + emailAddress + "\"><P>\n" +
       "<INPUT TYPE=\"SUBMIT\" VALUE=\"Register\">\n" +
       "</FORM></CENTER></BODY></HTML>");
  }
}

RegistrationServlet.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Servlet that processes a registration form containing
 *  a user's first name, last name, and email address.
 *  If all the values are present, the servlet displays the
 *  values. If any of the values are missing, the input
 *  form is redisplayed. Either way, the values are put
 *  into cookies so that the input form can use the
 *  previous values.
 */

public class RegistrationServlet extends HttpServlet
 {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException
	  {
    response.setContentType("text/html");
    boolean isMissingValue = false;
    String firstName = request.getParameter("firstName");
    if (isMissing(firstName)) {
      firstName = "Missing first name";
      isMissingValue = true;
    }
    String lastName = request.getParameter("lastName");
    if (isMissing(lastName)) {
      lastName = "Missing last name";
      isMissingValue = true;
    }
    String emailAddress = request.getParameter("emailAddress");
    if (isMissing(emailAddress)) {
      emailAddress = "Missing email address";
      isMissingValue = true;
    }
    Cookie c1 = new LongLivedCookie("firstName", firstName);
    response.addCookie(c1);
    Cookie c2 = new LongLivedCookie("lastName", lastName);
    response.addCookie(c2);
    Cookie c3 = new LongLivedCookie("emailAddress",
                                    emailAddress);
    response.addCookie(c3);
    String formAddress =
      "/RegistrationForm";
    if (isMissingValue) 
	{
      response.sendRedirect(formAddress);
    } else {
      PrintWriter out = response.getWriter();
      String docType =
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
        "Transitional//EN\">\n";
      String title = "Thanks for Registering";
      out.println
        (docType +
         "<HTML>\n" +
         "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
         "<BODY BGCOLOR=\"#FDF5E6\">\n" +
         "<CENTER>\n" +
         "<H1 ALIGN>" + title + "</H1>\n" +
         "<UL>\n" +
         "  <LI><B>First Name</B>: " +
                firstName + "\n" +
         "  <LI><B>Last Name</B>: " +
                lastName + "\n" +
         "  <LI><B>Email address</B>: " +
                emailAddress + "\n" +
         "</UL>\n" +
         "</CENTER></BODY></HTML>");
    }
  }

  /** Determines if value is null or empty. */

  private boolean isMissing(String param) {
    return((param == null) ||
           (param.trim().equals("")));
  }
}

LongLivedCookie.java

import javax.servlet.http.*;

/** Cookie that persists 1 year. Default Cookie doesn't
 *  persist past current browsing session.
 */
public class LongLivedCookie extends Cookie {
  public static final int SECONDS_PER_YEAR = 60*60*24*365;

  public LongLivedCookie(String name, String value) {
    super(name, value);
    setMaxAge(SECONDS_PER_YEAR);
  }
}

CookieUtilities.java

import javax.servlet.*;
import javax.servlet.http.*;

/** Two static methods for use in cookie handling. */

public class CookieUtilities
 {
  /** Given the request object, a name, and a default value,
   *  this method tries to find the value of the cookie with
   *  the given name. If no cookie matches the name,
   *  the default value is returned.
   */
  public static String getCookieValue
                           (HttpServletRequest request,
                            String cookieName,
                            String defaultValue) 
	{
    Cookie[] cookies = request.getCookies();
    if (cookies != null) 
	{
      for(int i=0; i<cookies.length; i++) 
	  {
        Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
          return(cookie.getValue());
        }
      }
    }
    return(defaultValue);
  }

  /** Given the request object and a name, this method tries
   *  to find and return the cookie that has the given name.
   *  If no cookie matches the name, null is returned.
   */

  public static Cookie getCookie(HttpServletRequest request,
                                 String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for(int i=0; i<cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
          return(cookie);
        }
      }
    }
    return(null);
  }
}

 
Leave a comment

Posted by on March 5, 2013 in Example

 

Differentiating session cookies from persistent cookies

Differentiating session cookies from persistent cookies

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Creates a table of the cookies associated with
 *  the current page. Also sets six cookies: three
 *  that apply only to the current session
 *  (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless
 *  of whether the browser is restarted).
 */
public class CookieTest extends HttpServlet
{
  public void doGet(HttpServletRequest request,HttpServletResponse response)
      throws ServletException, IOException 
	  {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
	for(int i=0; i<3; i++) 
	{
     		Cookie cookie = new Cookie("Session-Cookie-" + i,"Cookie-Value-S" + i);
		response.addCookie(cookie);
		cookie = new Cookie("Persistent-Cookie-" + i,"Cookie-Value-P" + i);
                cookie.setMaxAge(60*60);  //1 hour
		response.addCookie(cookie);
	}
    String docType =
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
      "Transitional//EN\">\n";
    String title = "Active Cookies";
    out.println(docType +
                "<HTML>\n" +
                "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
                "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
                "<TR BGCOLOR=\"#FFAD00\">\n" +
                "  <TH>Cookie Name\n" +
                "  <TH>Cookie Value");
			
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
      out.println("<TR><TH COLSPAN=2>No cookies");
    } else
     {
      Cookie cookie;
      for(int i=0; i<cookies.length; i++) {
        cookie = cookies[i];
        out.println("<TR>\n" +
                    "  <TD>" + cookie.getName() + "\n" +
                    "  <TD>" + cookie.getValue());
      }
    }
    out.println("</TABLE></BODY></HTML>");
 }
}

 
Leave a comment

Posted by on March 2, 2013 in Example

 

Example of cookie

Example of Cookie
//set the cookie

import java.io.*;
import javax.servlet.http.*;
public class CookieDemo extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
 		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
 		Cookie cookie = new Cookie("username","admin");
		cookie.setMaxAge(60*60); //1 hour
		response.addCookie(cookie);
 		pw.println("Cookies created");
	}
}

//To retrieve the value of cookie

import java.io.*;
import javax.servlet.http.*;
public class RetCookie extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
        {
 
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
 		Cookie[] cookie = request.getCookies();
		pw.println("All Cookies in your browsers\n");
 		for(Cookie obj : cookie)
                {
 
			if(obj.getName().equals("username"))
                        {
				pw.println(obj.getName() + " : " + obj.getValue());
				break;
			}
		}
	}
}
 
Leave a comment

Posted by on March 2, 2013 in Example