/**
* Simple Shopping Cart V3
*
* Session tracking with cookies. Note that the simplified
* session number generation here is not safe (easy to guess) or
* thread-safe.
*/
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart3 extends HttpServlet {
int sss;
HashMap cart;
/**
* Create a form
*/
String createForm()
{
String form="";
String method = "method=get";
String action = "action=Cart3";
String e1 = "Item:
";
String e2 = "";
String e3 = "
";
form += "
";
return form;
}
/**
* Create a list of items already bought
*/
String createList( String sess )
{
Vector v = (Vector) cart.get(sess);
String list = "";
for( int i=0 ; i < v.size() ; ++i )
if( v.elementAt(i) != null )
list += (String) v.elementAt(i) + "
";
return list;
}
/** show the content of cookies */
String showCookies( HttpServletRequest r )
{
String s = "
";
Cookie cookies[] = r.getCookies();
if( cookies == null ) return "
No cookies
";
else
for( int i=0 ; i < cookies.length ; ++i )
s += cookies[i].getName() + " " + cookies[i].getValue() + "
";
return s;
}
/** init() */
public void init() throws ServletException
{
sss = 0;
cart = new HashMap();
}
/**
* Note that a) getCookies() may return null if no cookies have been
* set, and b) getCookies() != null does not mean the "sess" cookie
* was set, so we have to go through all cookies and look for
* cookie name "sess".
*/
String getSession( HttpServletRequest r )
{
Cookie cookies[] = r.getCookies();
if( cookies == null ) return null;
for( int i=0 ; i < cookies.length ; ++i )
if( cookies[i].getName().equals("sess") ) return cookies[i].getValue();
return null;
}
/** doGet() */
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
String sess = getSession( request );
if( sess == null )
{
sess = "" + sss++;
cart.put( sess, new Vector() );
}
response.addCookie( new Cookie("sess", sess) );
if( request.getParameter("buy") != null )
((Vector) cart.get(sess)).add( request.getParameter("item") );
// doc type, html, title, body
response.setContentType("text/html");
String doc = "\n";
doc += "Simple Shopping Cart\n";
if( request.getParameter("done") != null ) doc += createList(sess);
else doc += createForm();
// doc += showCookies(request);
// closing body and html. set content type to be html and write out
doc += "";
PrintWriter out = response.getWriter();
out.println( doc );
}
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doGet( request, response );
}
}