Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Cookies

Cookies allows storage on the client's machine information that is to be included in subsequent requests. To create and manipulate cookies from Jython, use the javax.Servlet.http.Cookie class. Creating a new cookie requires instantiating javax.servlet.http.Cookie with a name and value as parameters. If you were using cookies to track book purchases, you could set the author and title with a cookie like this:

from javax.servlet import http
name = "book1"
value = "Lewis Carroll, Alice In Wonderland"
MyNewCookie = http.Cookie(name, value)

Now you have a new cookie with a name of book1, the value is the Rev. Dodgson's pen name, and the title Alice in Wonderland. To send this cookie to the client you need to use HttpServletResponse's addCookie(cookie) method:

res.addCookie(MyNewCookie)

Adding cookies should take place before sending other content through the response stream.

Cookies often require more attention than that, thus the cookie instance has methods to set the specifics of the cookie. Each cookie instance can use get and set methods or Jython's automatic bean properties for each of the following properties:

  • comment
  • domain
  • maxAge
  • name
  • path
  • secure
  • value
  • version

Listing 12.7 makes use of the cookie object's automatic bean properties to create and read cookies defined in a web form.

Listing 12.7 Cookies with Jython

# File: cookies.py
from javax import servlet
from javax.servlet import http

class cookies(http.HttpServlet):
  def doGet(self, req, res):
    res.setContentType("text/html")
    out = res.getOutputStream()

    print >>out, "<html><head><title>Cookies with Jython</title></head>"
    print >>out, """
      <body>\n<H2>Cookie list:</H2>
      Remember, cookies must be enabled in your browser.<br><br>"""

    # Here's the list of Cookies
    for c in req.cookies:
      print >>out, """
        <b>Cookie Name</b>= %s &nbsp; 
        <b>Value</b>= %s<br><br>""" % (c.name,c.value)

    print >>out, """<br><br><br>
      <HR><P>Use this form to add a new cookie</P>
      <form action="cookies.py" method="POST">
      <P>Name:<br><INPUT type="text" name="name" size="30"></P>
      <P>Value:<br><INPUT type="text" name="value" size="30"></P>
      <P>Use the MaxAge field to set the cookie's time-to-expire.
        A value of "0" deletes the cookie immediately, a value of 
        "-1" saves the cookie until the browser exits, and
        any other integer represents seconds until it expires 
        (i.e.- using "10" would expire 10 seconds after being set).</P>
      <P>MaxAge:<br><INPUT type="text" name="maxAge" size="30"></P>
      <INPUT type="submit" name="button" value="submit">
      \n</body>
      \n</html>
      """

  def doPost(self, req, res):
    res.setContentType("text/html");
    out = res.getWriter()
    name = req.getParameterValues("name")[0]
    value = req.getParameterValues("value")[0]
    maxAge = req.getParameterValues("maxAge")[0]
    
    if name:
      newCookie = http.Cookie(name, value)
      newCookie.maxAge = int(maxAge or -1)
      newCookie.comment = "Jython test cookie"
      res.addCookie(newCookie)

      print >>out, """
        <html><body>Cookie set successfully\n\n
        <P>click <a href="cookies.py">here</a>
        to view the new cookie.</P>
        <P>If cookies are enabled in your
        browser that is.</P>
        \n</body>
        \n</html>"""
	else:
      print >>out, """
        <html>\n<body>
        Cookie not set
        <P>No cookie "Name" provided</P>
        <P>click <a href="cookies">here</a>
        to try again</P>
        \n</body>
        /n</html>"""

To test the jylet in Listing 12.7, first make sure your browser is set to allow cookies. Then place the cookies.py file in the directory %TOMCAT_HOME%\webapps\jython and point your browser to http://localhsot:8080/jython/cookies.py. You should only see a heading and a form on your first visit to this servlet. Proceed to add a form entry—possibly "Jython Cookie" for the name and "My first Jython cookie" for the value, and click the Submit button (maxAge is optional). You should see confirmation that adding the cookie was successful. To confirm that the cookie was truly added, return to doGet method and see if it shows up in the cookie list. Figure 12.3 shows what a browser might display after returning to the doGet method. Note that Figure 12.3 assumes certain cookie names and values were entered, and your result page will depend on the names and values you use.

Figure 12.3. Defined Cookies with cookies.py.

  • + Share This
  • 🔖 Save To Your Account