Programming Server side with Sevlet


Published on

Published in: Business, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Programming Server side with Sevlet

  1. 1. IADCS Diploma Course Java Servlet Programming U Nyein Oo COO/Director (IT) Myanma Computer Co., Ltd(MCC)
  2. 2. Road Map <ul><li>Servlet Architecture Overview </li></ul><ul><li>Servlets in Context </li></ul><ul><ul><li>Other options for server side development </li></ul></ul><ul><li>Advantages of Servlets </li></ul><ul><li>Introduction to Java Server Pages (JSP) </li></ul><ul><ul><li>Servlets v. JSP </li></ul></ul>
  3. 3. What is a Servlet? <ul><li>Java’s answer to the Common Gateway Interface (CGI). </li></ul><ul><li>Applet : a java program that runs within the web browser. </li></ul><ul><li>Servlet : a java program that runs within the web server. </li></ul><ul><li>Rapidly becoming the standard for building web applications. </li></ul>
  4. 4. Life of a Servlet <ul><li>Regardless of the application, servlets usually carry out the following routine: </li></ul><ul><li>Read any data sent by the user </li></ul><ul><ul><li>Capture data submitted by an HTML form. </li></ul></ul><ul><li>Look up any HTTP information </li></ul><ul><ul><li>Determine the browser version, host name of client, cookies, etc. </li></ul></ul><ul><li>Generate the Results </li></ul><ul><ul><li>Connect to databases, connect to legacy applications, etc. </li></ul></ul>
  5. 5. Life of a Servlet (cont.) <ul><li>Format the Results </li></ul><ul><ul><li>Generate HTML on the fly </li></ul></ul><ul><li>Set the Appropriate HTTP headers </li></ul><ul><ul><li>Tell the browser the type of document being returned or set any cookies. </li></ul></ul><ul><li>Send the document back to the client </li></ul>
  6. 6. Life of a Servlet Web Browser Web Server Java Servlet Database 1,2 3 4,5 6
  7. 7. What can you build with Servlets? <ul><li>Search Engines </li></ul><ul><li>Personalization Systems </li></ul><ul><li>E-Commerce Applications </li></ul><ul><li>Shopping Carts </li></ul><ul><li>Product Catalogs </li></ul><ul><li>Intranet Applications </li></ul><ul><li>Groupware Applications: bulletin boards, file sharing, etc. </li></ul>
  8. 8. Server Side Options <ul><li>There are many options for creating server side applications. </li></ul><ul><li>We will examine some of these options briefly. </li></ul><ul><li>This better enables us to understand servlets within the broader context of web development. </li></ul><ul><li>Also enables us to better understand the advantages and disadvantages of servlets. </li></ul>
  9. 9. Server Side Options <ul><li>Common Gateway Interface (CGI) </li></ul><ul><li>Fast CGI </li></ul><ul><li>Mod Perl </li></ul><ul><li>ASP </li></ul><ul><li>PHP </li></ul><ul><li>Cold Fusion </li></ul>
  10. 10. Common Features <ul><li>All server side frameworks share a common set of features: </li></ul><ul><ul><li>Read data submitted by the user </li></ul></ul><ul><ul><li>Generate HTML dynamically based on user input </li></ul></ul><ul><ul><li>Determine information about the client browser </li></ul></ul><ul><ul><li>Access Database systems </li></ul></ul><ul><ul><li>Exploit the HTTP protocol </li></ul></ul>
  11. 11. Decision Points <ul><li>When evaluating which server side framework to use, you need to consider a number of critical factors: </li></ul><ul><ul><li>Ease of development: </li></ul></ul><ul><ul><ul><li>How easily can you build new applications? </li></ul></ul></ul><ul><ul><li>Performance: </li></ul></ul><ul><ul><ul><li>How fast can the framework respond to queries? </li></ul></ul></ul><ul><ul><li>Scalability: </li></ul></ul><ul><ul><ul><li>Can the framework scale to thousands, millions of users? </li></ul></ul></ul><ul><ul><li>Security: </li></ul></ul><ul><ul><ul><li>Are there any inherent security vulnerabilities? </li></ul></ul></ul>
  12. 12. Option 1: CGI <ul><li>Represents one of the earliest, practical methods for generating web content. </li></ul><ul><li>Primarily written in the Perl programming language. </li></ul><ul><li>Unfortunately, traditional CGI programs suffer from scalability and performance problems. </li></ul><ul><li>Let’s examine these two problems… </li></ul>
  13. 13. CGI Architecture <ul><li>Browser initiates request </li></ul><ul><li>Web server receives the request. </li></ul><ul><li>For each request, web server spawns a new operating system process to execute the CGI/Perl Program. </li></ul>Web Browser Web Server Perl/CGI Create New process
  14. 14. CGI Architecture <ul><li>For each browser request, the web server must spawn a new operating system process. </li></ul>Browser 1 Web Server Perl 1 Browser 2 Browser N Perl 2 Perl N
  15. 15. CGI Architecture <ul><li>Spawning a new operating system process for each request takes time and memory. </li></ul><ul><li>Hence, traditional CGI programs have inherent performance and scalability problems. </li></ul><ul><li>Every other server architecture tries to address these problems. </li></ul>
  16. 16. Option 2: Fast CGI <ul><li>Developed by Open Market as an option for developing faster, more scalable CGI programs. </li></ul><ul><li>Fast CGI works by creating a pool of processes for handling CGI requests. </li></ul><ul><li>When a CGI request comes in, Fast CGI picks one of the processes from the pool and assigns it to the task. </li></ul><ul><li>Without the overhead of creating new operating system processes, FastCGI is much faster than traditional CGI. </li></ul><ul><li>For more information, see </li></ul>
  17. 17. Option 3: Mod Perl <ul><li>A module of the Apache Web Server. </li></ul><ul><li>Embeds the Perl interpreter directly within the web server. </li></ul><ul><li>Perl programs are therefore precompiled. </li></ul><ul><li>Because Perl is embedded within the Server, Mod Perl does not need to create a new process for each request. </li></ul><ul><li>Like FastCGI, Mod Perl is much faster than traditional CGI. </li></ul><ul><li>For more information, see: </li></ul>
  18. 18. Option 4: ASP <ul><li>Active Server Pages </li></ul><ul><li>Runs on Microsoft’s Web Server: Internet Information Server (IIS) </li></ul><ul><li>Programmers add ASP code directly into their HTML pages. </li></ul><ul><li>When a client requests a page, the Web Server takes the HTML page, runs the ASP code within the page, and returns a complete HTML page. </li></ul><ul><li>Faster than traditional CGI, but only works on Microsoft IIS. </li></ul>
  19. 19. Option 5: Cold Fusion <ul><li>Developed by Allaire Corporation (now owned by Macromedia.) </li></ul><ul><li>Provides excellent database access and database tools. </li></ul><ul><li>Great platform for rapid prototyping and rapid development. </li></ul><ul><li>For more information: </li></ul>
  20. 20. Option 6: PHP <ul><li>An open source project written entirely by volunteers </li></ul><ul><li>Provides simple, but powerful database access. </li></ul><ul><li>Also great for rapid development. </li></ul><ul><li>For additional information: </li></ul>
  21. 21. Advantages of Servlets <ul><li>Servlets have six main advantages: </li></ul><ul><ul><li>Efficient </li></ul></ul><ul><ul><li>Convenient </li></ul></ul><ul><ul><li>Powerful </li></ul></ul><ul><ul><li>Portable </li></ul></ul><ul><ul><li>Secure </li></ul></ul><ul><ul><li>Inexpensive </li></ul></ul>
  22. 22. Advantage 1: Efficient <ul><li>For each browser request, the servlet spawns a light weight thread. </li></ul><ul><li>This is faster and more efficient that spawning a new operating system process. </li></ul><ul><li>Hence, servlets have better performance and better scalability than traditional CGI. </li></ul>
  23. 23. Advantage 2: Convenient <ul><li>Servlets include built-in functionality for: </li></ul><ul><ul><li>Reading HTML form data </li></ul></ul><ul><ul><li>Handling cookies </li></ul></ul><ul><ul><li>Tracking user sessions </li></ul></ul><ul><ul><li>Setting HTTP headers </li></ul></ul><ul><li>Java is object oriented </li></ul>
  24. 24. Advantage 3: Powerful <ul><li>Servlets can talk directly to the web servers. </li></ul><ul><li>Multiple servlets can share data: </li></ul><ul><ul><li>Particularly important for maintaining database connections. </li></ul></ul><ul><li>Includes powerful techniques for tracking user sessions. </li></ul>
  25. 25. Advantage 4: Portable <ul><li>One of the advantages of Java is its portability across different operating systems. </li></ul><ul><li>Servlets have the same advantages. </li></ul><ul><li>You can therefore write your servlets on Windows, then deploy them on UNIX. </li></ul><ul><li>You can also run any of your servlets on any Java-enabled web server, with no code changes. </li></ul>
  26. 26. Advantage 5: Secure <ul><li>Traditional CGI programs have a number of known security vulnerabilities. </li></ul><ul><li>Hence, you usually need to include a separate Perl/CGI module to supply the necessary security protection. </li></ul><ul><li>Java has a number of built-in security layers. </li></ul><ul><li>Hence, servlets are considered more secure than traditional CGI programs. </li></ul>
  27. 27. Advantage 6: Inexpensive <ul><li>You can download free servlet kits for development use. </li></ul><ul><li>You can therefore get started for free! </li></ul><ul><li>Nonetheless, production strength servlet web servers can get quite expensive. </li></ul>
  28. 28. Java Server Pages <ul><li>Related to Java Servlets </li></ul><ul><li>Can be used alone or in conjunction with servlets </li></ul><ul><li>Represent (yet) another method for creating server side applications </li></ul>
  29. 29. Servlets v. JSP <ul><li>Servlets </li></ul><ul><ul><li>code looks like a regular Java program. </li></ul></ul><ul><li>JSP </li></ul><ul><ul><li>embed Java commands directly within HTML </li></ul></ul><ul><li>Let’s examine a Servlet program next to a JSP program… </li></ul><ul><li>Each of these prints, “Hello, World!” </li></ul>
  30. 30. Servlet Engine <ul><li>There are three kinds of Servlet engine </li></ul><ul><ul><li>Stand Alone Servlet Engine </li></ul></ul><ul><ul><li>Add-on Servlet Engine </li></ul></ul><ul><ul><li>Embedded Servlet Engine </li></ul></ul>
  31. 31. Stand Alone Servlet Engine <ul><li>A standalone servlet engine is a server that includes built-in support for servlets. </li></ul><ul><li>Such an engine has the advantage that everything works right out of the box. O </li></ul><ul><li>ne disadvantage, however, is that you have to wait for a new release of the web server to get the latest servlet support. </li></ul>
  32. 32. Add-On Servlet Engine <ul><li>An add-on servlet engine functions as a plug-in to an existing server--it adds servlet support to a server that was not originally designed with servlets in mind. </li></ul><ul><li>Add-on servlet engines have been written for many servers including Apache, Netscape's FastTrack Server and Enterprise Server, Microsoft's Internet Information Server and Personal Web Server, O'Reilly's WebSite, Lotus Domino's Go Webserver, StarNine's WebSTAR, and Apple's AppleShareIP </li></ul>
  33. 33. Embedded Servlet Engine <ul><li>An embeddable engine is generally a lightweight servlet deployment platform that can be embedded in another application. The application becomes the true server. </li></ul>
  34. 34. import*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(&quot;text/html&quot;); PrintWriter out = res.getWriter(); out.println(&quot;<HTML>&quot;); out.println(&quot;<HEAD><TITLE>Hello World</TITLE></HEAD>&quot;); out.println(&quot;<BODY>&quot;); out.println(&quot;<BIG>Hello World</BIG>&quot;); out.println(&quot;</BODY></HTML>&quot;); } } A Java Servlet : Looks like a regular Java program
  35. 35. <html> <head> <title>Hello, World JSP Example</title> </head> <body> <h2> Hello, World! The current time in milliseconds is <%= System.currentTimeMillis() %> </h2> </body> </html> A JSP Page : Looks like a regular HTML page. Embedded Java command to print current time.
  36. 36. Servlet Lift Cycle <ul><li>Overview of the Life Cycle </li></ul><ul><li>Birth of a Servlet </li></ul><ul><li>Life of a Servlet </li></ul><ul><li>Threading Issues </li></ul><ul><li>Death of a Servlet </li></ul><ul><li>Tips for Debugging Servlets </li></ul>
  37. 37. Life of a Servlet <ul><li>Birth: Create and initialize the servlet </li></ul><ul><ul><li>Important method: init() </li></ul></ul><ul><li>Life: Handle 0 or more client requests </li></ul><ul><ul><li>Important methods: service(), doGet(), and doPost(). </li></ul></ul><ul><li>Death: Destroy the servlet </li></ul><ul><ul><li>Important method: destroy() </li></ul></ul>
  38. 38. Birth of Servlet The init() method <ul><li>The init() method is called when the servlet is first requested by a browser request. </li></ul><ul><li>It is not called again for each request. </li></ul><ul><li>Used for one-time initialization . </li></ul>
  39. 39. Simple Example <ul><li>The init() method is a good place to put any initialization variables. </li></ul><ul><li>For example, the following servlet records its Birth Date/time… </li></ul>
  40. 40. <ul><li>import*; </li></ul><ul><li>import java.util.*; </li></ul><ul><li>import javax.servlet.*; </li></ul><ul><li>import javax.servlet.http.*; </li></ul><ul><li>public class Birth extends HttpServlet { </li></ul><ul><li>Date birthDate; </li></ul><ul><li>// Init() is called first </li></ul><ul><li>public void init() throws ServletException { </li></ul><ul><li>birthDate = new Date(); </li></ul><ul><li>} </li></ul>
  41. 41. // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I was born on: &quot;+birthDate); out.close(); } }
  42. 42. Life of a Servlet <ul><li>The first time a servlet is called, the Servlet is instantiated, and its init() method is called. </li></ul><ul><li>Only one instance of the servlet is instantiated. </li></ul><ul><li>This one instance handles all browser requests. </li></ul>
  43. 43. Service() Method <ul><li>Each time the server receives a request for a servlet, the server spawns a new thread and calls the servlet’s service () method. </li></ul>Browser Browser Browser Web Server Single Instance of Servlet service() service() service()
  44. 44. Let’s Prove it… <ul><li>To prove that only one instance of a servlet is created, let’s create a simple example. </li></ul><ul><li>The Counter Servlet keeps track of the number of times it has been accessed. </li></ul><ul><li>This example maintains a single instance variable, called count. </li></ul><ul><li>Each time the servlet is called, the count variable is incremented. </li></ul><ul><li>If the Server created a new instance of the Servlet for each request, count would always be 0! </li></ul>
  45. 45. import*; import javax.servlet.*; import javax.servlet.http.*; public class Counter extends HttpServlet { // Create an instance variable int count = 0; // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; + &quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } } Only one instance of the counter Servlet is created. Each browser request is therefore incrementing the same count variable.
  46. 46. The Service Method <ul><li>By default the service() method checks the HTTP Header. </li></ul><ul><li>Based on the header, service calls either doPost() or doGet(). </li></ul><ul><li>doPost and doGet is where you put the majority of your code. </li></ul><ul><li>If your servlets needs to handle both get and post identically, have your doPost() method call doGet() or vice versa. </li></ul>
  47. 47. Thread Synchronization <ul><li>By default, multiple threads are accessing the same servlet object at the same time. </li></ul><ul><li>You therefore need to be careful to synchronize access to shared data. </li></ul><ul><li>For example, the code on the next slide has a problem… </li></ul>
  48. 48. package coreservlets; import*; import javax.servlet.*; import javax.servlet.http.*; public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); String title = &quot;Your ID&quot;; String docType = … String id = &quot;User-ID-&quot; + nextID; out.println(&quot;<H2>&quot; + id + &quot;</H2>&quot;); nextID = nextID + 1; out.println(&quot;</BODY></HTML>&quot;); } } This code is problematic. Can result in a race condition, where two users can actually get the same User-ID! For example: User 1 makes request: String id = &quot;User-ID-&quot; + nextID; Gets nextId of 45. Now User 2 makes request, and pre-empts user 1: String id = &quot;User-ID-&quot; + nextID; Gets nextId of 45 (same one!) Admittedly, this case is rare, but it’s especially problematic. Imagine if user Id was tied to credit card number!
  49. 49. How to Solve Synchronization Problems <ul><li>You have a few options for solving servlet synchronization issues: </li></ul><ul><ul><li>Never use instance variables in your servlets. If you don’t have shared instance variables, you don’t have shared synchronization problems. </li></ul></ul><ul><ul><li>Synchronize code explicitly with Java synchronization blocks. </li></ul></ul><ul><ul><li>Use the SingleThreadInterface (not recommended) </li></ul></ul>
  50. 50. Java Synchronization <ul><li>Use a synchronization block whenever accessing/modifying a shared variable. </li></ul><ul><li>For example: </li></ul><ul><li>synchronized (this) { </li></ul><ul><li>String id = &quot;User-ID-&quot; + nextID; </li></ul><ul><li>out.println(&quot;<H2>&quot; + id + &quot;</H2>&quot;); </li></ul><ul><li>nextID = nextID + 1; </li></ul><ul><li>} </li></ul>
  51. 51. SingleThreadModel Interface <ul><li>To prevent multi-threaded access, you can have your servlet implement the SingleThreadModel: </li></ul><ul><ul><li>public class YourServlet extends HttpServlet implements </li></ul></ul><ul><ul><li>SingleThreadModel { </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>This will guarantee that your servlet will only process one browser request at a time. </li></ul><ul><li>It therefore addresses most synchronization issues. </li></ul><ul><li>Unfortunately, however, it can result in severe slowing of performance, and most people strongly recommend against using it. </li></ul><ul><li>In fact, the SingleThreadModel interface is now deprecated in the Servlet 2.4 API. </li></ul>
  52. 52. Death of a Servlet <ul><li>Before a server shuts down, it will call the servlet’s destroy() method. </li></ul><ul><li>You can handle any servlet clean up here. For example: </li></ul><ul><ul><li>Updating log files. </li></ul></ul><ul><ul><li>Closing database connections. </li></ul></ul><ul><ul><li>Closing any socket connections. </li></ul></ul>
  53. 53. Example: <ul><li>This next example illustrates the use of the destroy() method. </li></ul><ul><li>While alive, the servlet will say “I am alive!”. </li></ul><ul><li>When the server is stopped, the destroy() method is called, and the servlet records its time of death in a “rip.txt” text file. </li></ul>
  54. 54. import*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Death extends HttpServlet { // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); out.println (&quot;I am alive!&quot;); out.close(); } Continued….
  55. 55. // This method is called when one stops // the Java Web Server public void destroy() { try { FileWriter fileWriter = new FileWriter (&quot;rip.txt&quot;); Date now = new Date(); String rip = &quot;I was destroyed at: &quot;+now.toString(); fileWriter.write (rip); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
  56. 56. A Persistent Counter <ul><li>Now that we know all about the birth, life and death of a servlet, let’s put this knowledge together to create a persistent counter. </li></ul><ul><li>The example we covered earlier has a big problem: </li></ul><ul><ul><li>When you restart the web server, counting starts all over at 0. </li></ul></ul><ul><ul><li>It does not retain any persistent memory. </li></ul></ul>
  57. 57. Persistent Counter <ul><li>To create a persistent record, we can store the count value within a “counter.txt” file. </li></ul><ul><ul><li>init(): Upon start-up, read in the current counter value from counter.txt. </li></ul></ul><ul><ul><li>destroy(): Upon destruction, write out the new counter value to counter.txt </li></ul></ul>
  58. 58. import*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterPersist extends HttpServlet { String fileName = &quot;counter.txt&quot;; int count; public void init () { try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial); } catch (FileNotFoundException e) { count = 0; } catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; } } At Start-up, load the counter from file. In the event of any exception, initialize count to 0. Continued….
  59. 59. // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/plain&quot;); PrintWriter out = response.getWriter(); count++; out.println (&quot;Since loading, this servlet has &quot; +&quot;been accessed &quot;+ count + &quot; times.&quot;); out.close(); } Each time the doGet() method is called, increment the count variable. Continued….
  60. 60. // At Shutdown, store counter back to file public void destroy() { try { FileWriter fileWriter = new FileWriter (fileName); String countStr = Integer.toString (count); fileWriter.write (countStr); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } When destroy() is called, store new counter variable back to counter.txt. Any problems with this code?
  61. 61. Tips for Debugging Servlets <ul><li>Section 3.8 of our Text has a few tips for Servlet Debugging. Pay close attention! </li></ul><ul><li>At this stage, the best debugging option is to use print statements. </li></ul><ul><li>print statements will be output to the Tomcat console (very useful!) </li></ul><ul><li>Let’s try it out… </li></ul><ul><li>For production systems, a real logging library, such as Log4J, is a much better option. </li></ul>
  62. 62. Servlet Cookie API <ul><li>Creating Cookies </li></ul><ul><li>Cookie Attributes </li></ul><ul><li>Reading Cookies </li></ul><ul><li>Example 1: Basic Counter </li></ul><ul><li>Example 2: Tracking Multiple Cookies </li></ul>
  63. 63. Creating Cookies <ul><li>Three steps to creating a new cookie: </li></ul><ul><ul><li>Create a new Cookie Object </li></ul></ul><ul><ul><ul><li>Cookie cookie = new Cookie (name, value); </li></ul></ul></ul><ul><ul><li>Set any cookie attributes </li></ul></ul><ul><ul><ul><li>Cookie.setMaxAge (60); </li></ul></ul></ul><ul><ul><li>Add your cookie to the response object: </li></ul></ul><ul><ul><ul><li>Response.addCookie (cookie) </li></ul></ul></ul><ul><li>We will examine each of these steps in detail. </li></ul>
  64. 64. 1. Cookie Constructor <ul><li>You create a new cookie by calling the Cookie constructor and specifying: </li></ul><ul><ul><li>Name </li></ul></ul><ul><ul><li>Value </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>Cookie cookie = new Cookie (“school”, “NYU”); </li></ul></ul><ul><li>Neither the name nor the value should contain whitespace or any of the following characters: </li></ul><ul><ul><li>[ ] ( ) = , “ / ? @ ; </li></ul></ul>
  65. 65. 2. Set Cookie Attributes <ul><li>Before adding your cookie to the Response object, you can set any of its attributes. </li></ul><ul><li>Attributes include: </li></ul><ul><ul><li>Name/Value </li></ul></ul><ul><ul><li>Domain </li></ul></ul><ul><ul><li>Maximum Age </li></ul></ul><ul><ul><li>Path </li></ul></ul><ul><ul><li>Version </li></ul></ul>
  66. 66. Cookie Name <ul><li>You rarely call setName() directly, as you specify the name in the cookie constructor. </li></ul><ul><li>getName() is useful for reading in cookies. </li></ul>public String getName(); public void setName (String name);
  67. 67. Cookie Value <ul><li>You rarely call setValue() directly, as you specify the name in the cookie constructor. </li></ul><ul><li>getValue() is useful for reading in cookies. </li></ul>public String getValue(); public void setValue (String value);
  68. 68. Domain Attributes public String getDomain (); public void setDomain(String domain); <ul><li>Normally, the browser only returns cookies to the exact same host that sent them. </li></ul><ul><li>You can use setDomain() to instruct the browser to send cookies to other hosts within the same domain. </li></ul>
  69. 69. Domain Example <ul><li>Example: Cookies sent from a servlet at would not be forwarded to </li></ul><ul><li>If you do want to the cookie to be accessible to both hosts, set the domain to the highest level: </li></ul><ul><ul><li>cookie.setDomain (“”); </li></ul></ul><ul><li>Note that you are always required to include at least two dots. Hence, you must specify, not just </li></ul>
  70. 70. Cookie Age <ul><li>In general there are two types of cookies: </li></ul><ul><ul><li>Session Cookies : Temporary cookies that expire when the user exits the browser. </li></ul></ul><ul><ul><li>Persistent Cookies : Cookies that do not expire when the user exits the browser. These cookies stay around until their expiration date, or the user explicitly deletes them. </li></ul></ul>public int getMaxAge (); public void setMaxAge (int lifetime);
  71. 71. Cookie Expiration <ul><li>The setMaxAge () method tells the browser how long (in seconds) until the cookie expires. </li></ul><ul><li>Possible values: </li></ul><ul><ul><li>Negative Value (default): creates a session cookie that is deleted when the user exits the browser. </li></ul></ul><ul><ul><li>0: instructs the browser to delete the cookie. </li></ul></ul><ul><ul><li>Positive value: any number of seconds. For example, to create a cookie that lasts for one hour, setMaxAge (3600); </li></ul></ul>
  72. 72. Path <ul><li>By default, the browser will only return a cookie to URLs in or below the directory that created the cookie. </li></ul>public String getPath(); public void setPath (String path);
  73. 73. Path Example <ul><li>Example: If you create a cookie at then: </li></ul><ul><ul><li>The browser will send the cookie back to . </li></ul></ul><ul><ul><li>The browser will not send the cookie back to </li></ul></ul><ul><li>If you want the cookie to be sent to all pages, set the path to / </li></ul><ul><ul><li>Cookie.setPath (“/”); </li></ul></ul><ul><ul><li>Very common, widely used practice. </li></ul></ul>
  74. 74. Cookie Version <ul><li>By default, the Servlet API will create Version 0 cookies. </li></ul><ul><li>Via the setVersion() method you can specify version 1. But, since this is not widely implemented, stick with the default. </li></ul>public int getVersion (); public void setVersion (int version);
  75. 75. Security <ul><li>If you set Secure to true, the browser will only return the cookie when connecting over an encrypted connection. (More on SSL later in the semester.) </li></ul><ul><li>By default, cookies are set to non-secure. </li></ul>public int getSecure (); public void setSecure (boolean);
  76. 76. Comments <ul><li>Comments: you can specify a cookie comment via the setComment() method. But, comments are only supported in Version 1 cookies. </li></ul><ul><li>Hence, no one really uses these methods… </li></ul>public int getComment (); public void Comment (String)
  77. 77. 3. Add Cookies to Response <ul><li>Once you have created your cookie, and set any attributes, you add it to the response object. </li></ul><ul><li>By adding it to the response object, your cookie is transmitted back to the browser. </li></ul><ul><li>Example: </li></ul><ul><ul><li>Cookie school = new Cookie (“school”, “NYU”); </li></ul></ul><ul><ul><li>school.setMaxAge (3600); </li></ul></ul><ul><ul><li>response.addCookie (school); </li></ul></ul>
  78. 78. Reading Cookies <ul><li>To create cookies, add them to the response object. </li></ul><ul><li>To read incoming cookies, get them from the request object. </li></ul><ul><li>HttpServletRequest has a getCookies() method. </li></ul><ul><ul><li>Returns an array of cookie objects. This includes all cookies sent by the browser. </li></ul></ul><ul><ul><li>Returns a zero-length array if there are no cookies. </li></ul></ul>
  79. 79. Reading Cookies <ul><li>Once you have an array of cookies, you can iterate through the array and extract the one(s) you want. </li></ul><ul><li>Our next few examples illustrate how this is done. </li></ul>
  80. 80. Example I: Cookie Counter <ul><li>A few weeks back, we created a simple Counter servlet that keeps track of the number of “hits”. </li></ul><ul><li>Now, we want to display the number of hits for each user. </li></ul><ul><li>This is relatively simple to do. We just create a counter cookie, and increment the counter cookie at each visit. </li></ul>
  81. 81. The Code <ul><li>Get the array of cookie objects from the request object. </li></ul><ul><li>Iterate through the array, looking for a “counter” cookie. </li></ul><ul><li>If the “counter” cookie exists, extract its value. Otherwise, set the counter to 0. </li></ul><ul><li>Increment the counter by 1. </li></ul><ul><li>Create a new “counter” cookie, and add it to the response object. </li></ul>
  82. 82. import*; import javax.servlet.*; import javax.servlet.http.*; public class CookieCounter extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name, value = null; Cookie cookie; int counter; res.setContentType(&quot;text/html&quot;); // Try to extract the counter cookie (if one exists) Cookie[] cookies = req.getCookies(); for (int i=0; i<cookies.length; i++) { cookie = cookies[i]; name = cookie.getName(); if (name.equals(&quot;counter&quot;)) value = cookie.getValue(); }
  83. 83. // If possible, parse the counter value // Otherwise, start over at 0. if (value != null) counter = Integer.parseInt (value); else counter = 0; // Increment the counter counter++; // Create a new counter cookie // Cookie will exist for one year cookie = new Cookie (&quot;counter&quot;, Integer.toString(counter)); cookie.setMaxAge (60*60*24*365); res.addCookie (cookie); // Output number of visits PrintWriter out = res.getWriter(); out.println (&quot;<HTML><BODY>&quot;); out.println (&quot;<H1>Number of visits: &quot;+counter); out.println (&quot;</H1>&quot;); out.println (&quot;</BODY></HTML>&quot;); out.close(); } }
  84. 84. HTTP Tracer <ul><li>Before we move on to the next example, let’s see our code in action via the HTTP Tracer…. </li></ul>
  85. 85. Example II: Creating/Reading Multiple Cookies <ul><li>Example 2 consists of two servlets: </li></ul><ul><ul><li> Creates six independent cookies. </li></ul></ul><ul><ul><li> Reads in and displays any and all cookies. </li></ul></ul><ul><li>Let’s examine first. </li></ul>
  86. 86. <ul><li> creates six unique cookies: </li></ul><ul><ul><li>Three Session Cookies </li></ul></ul><ul><ul><ul><li>Session-Cookie 1, 2, 3 </li></ul></ul></ul><ul><ul><ul><li>These last until the user exits the browser. </li></ul></ul></ul><ul><ul><li>Three Persistent Cookies </li></ul></ul><ul><ul><ul><li>Persistent-Cookie 1, 2, 3 </li></ul></ul></ul><ul><ul><ul><li>These last for one year. (slightly different than the example in the book, which sets it to one hour.) </li></ul></ul></ul>
  87. 87. for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie(&quot;Session-Cookie-&quot; + i, &quot;Cookie-Value-S&quot; + i); response.addCookie(cookie); cookie = new Cookie(&quot;Persistent-Cookie-&quot; + i, &quot;Cookie-Value-P&quot; + i); // Cookie is valid for a year, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge (60*60*24*365); response.addCookie(cookie); } Code Fragment
  88. 88. <ul><li>This servlet displays any and all cookies that sent to it. </li></ul><ul><li>It does this by first requesting the cookie array via request.getCookies(); </li></ul><ul><li>The code then iterates through the array to display each unique cookie. </li></ul>
  89. 89. Code Fragment <ul><li>Cookie[ ] cookies = request.getCookies(); </li></ul><ul><li>if (cookies != null) { </li></ul><ul><li>Cookie cookie; </li></ul><ul><li>for(int i=0; i<cookies.length; i++) { </li></ul><ul><li>cookie = cookies[i]; </li></ul><ul><li>out.println(&quot;<TR> &quot; + </li></ul><ul><li>&quot; <TD>&quot; + cookie.getName() + &quot; &quot; + </li></ul><ul><li>&quot; <TD>&quot; + cookie.getValue()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  90. 90. Thank You!