Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to...

59
Servlets Lifecycle- notes from Hunter Chapter 3
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    223
  • download

    1

Transcript of Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to...

Page 1: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Servlets

Lifecycle- notes from Hunter Chapter 3

Page 2: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

An alternative approach

• Servlets are meant to resolve both security issues of low-level applications and performance issues of CGI.

• Servlets may all be run in a single JVM so efficient sharing of data is possible.

• Between requests, servlets may persist on the server as object instances.

Page 3: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Servlet container requirements

1. Container must: create and initialize servlets

2. Container must: handle zero or more service calls from clients

3. Destroy and garbage collect servletsSo for example a servlet could be allocated

its own JVM and then garbage collected after handling no requests. This would not be efficient!

Page 4: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Tomcat, etc

• Java servers like Tomcat reside in a JVM instance alongside their servlets.

• A multi-process server would not have this option, but it might run a single JVM instance externally for processes to share.

Page 5: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Instance persistence

When a servlet is loaded, the server creates a single instance which handles all client requests of the servlet.

• So the memory footprint is small

• Object creation overhead is minimized

• Persistence is enabled.

Page 6: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Simple counter• maintains instance variables which persist between invocations and

are used for all invocations:public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse

res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); }}

Page 7: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Synchronization

• Clients are threads calling the servlet.• If you only read from thee request, write to the

response and manipulate local variables (defined inside methods), you don’t have to worry about interaction between threads.

• But if you save non-local variables then data corruption and inconsistencies can occur between client threads.

• In simple counter, we assumed increment and writing the count value formed an atomic action.

Page 8: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Synchronization- option 1

• We could build a synchronized get method:

public synchronized void doGet(…){….}

• The servlet would serve as the monitor to guarantee consistency. Such a servlet can handle only 1 GET request at a time.

Page 9: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Synchronization option 2

• We could synchronize just the increment and output lines:

synchronized(this){

count++;

out.println("Since loading, this servlet has been accessed " + count + " times.");

}• This limits the time in the synchronized block.

Page 10: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Synchronization option 3

int local;

synchronized(this){

local=++count;

}

out.println("Since loading, this servlet has been accessed " + local + " times.");

Page 11: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

• In fact, each registered name (by which the servlet was accessed), not each distinct URL, represents one instance of a servlet.

• To track access count across all instances a static variable can be used.

Page 12: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Holistic counter servlet static int classCount = 0; // shared by all instances int count = 0; // separate for each servlet static Hashtable instances = new Hashtable(); // also shared

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter();

count++; out.println("Since loading, this servlet instance has been accessed " + count + " times."); // Keep track of the instance count by putting a reference to this // instance in a Hashtable. Duplicate entries are ignored. // The size() method returns the number of unique instances stored. instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, this servlet class has been " + "accessed " + classCount + " times."); }

Page 13: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Aside on batch files to set classpath for compilation

• To compile to 1.4.1 I have this jdk on my c drive. Here’s a batch file for a text example:

set path=c:\compilers\j2sdk1.4.1_01\bin\set jdkhome=c:\compilers\j2sdk1.4.1_01\bin\set classpath=c:\compilers\j2sdk1.4.1_01\

bin\;p:\;p:\classes;c:\compilers\j2sdk1.4.1_01\lib

p:\classescd p:\classesp:javac HolisticCounter.java

Page 14: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Holistic Counter Servlet (text example)import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;public class HolisticCounter extends HttpServlet { static int classCount = 0; // shared by all instances int count = 0; // separate for each servlet static Hashtable instances = new Hashtable(); // also shared public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet instance has been accessed " + count + " times."); // Keep track of the instance count by putting a reference to this // instance in a Hashtable. Duplicate entries are ignored. // The size() method returns the number of unique instances stored. instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, this servlet class has been " + "accessed " + classCount + " times."); }}

Page 15: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

HolisticCounter servlet running from ServletServer

Page 16: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

reloading• Recompilation will cause servlets to be reloaded.• This speeds up development.• ClassLoaders are designed to load a class once, but servlet

containers use custom class loaders.• Before dispatching a request to a servlet, the server checks to see if

its class file has changed. If it has, the server abandons the class loader it used to load the earlier instance and creates a new class loader.

• This may cause class cast exceptions. • In the Serlvet API 2.2 servlets in the same context must not throw

class cast exceptions. Typically, then, a new loader instance will be used to reload and run all servlets in the same context if one changes.

• The server probably won’t notice support class recompilations. Generally global support classes should be put somewhere where the server is not likely to keep reloading them.

Page 17: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Init and Destroy

• Like applets, servlets may define init() and destroy() methods.

• The server calls a servlets init() method after constructing an instance and before requests are handled. The server calls destroy() when a servlet has been taken out of service and all pending requests have timed out.

Page 18: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

init()

init() may be called:

1. When the server starts

2. When the servlet is first requested

3. At the request of the administrator

init() can be used to load objects the servlet will use. Init parameters are not associated with a particular request. Typically, these might specify initial values. These values appear in the web.xml file.

Page 19: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

web.xml example. an entire (huge) web.xml file is in the notes for this page

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <!-- General description of your Web application --> <display-name> Servlet and JSP Examples </display-name> <description> This is the Web application in which we demonstrate our JSP and Servlet examples. </description> <!-- Servlet definitions --> <servlet> <servlet-name>ShowFile</servlet-name> <description> A simple servlet that looks for a file passed in as request </description> <servlet-class> ShowFile </servlet-class> </servlet> <!-- Servlet mappings --> <servlet-mapping> <servlet-name>welcome1</servlet-name> <url-pattern>/welcome1</url-pattern> </servlet-mapping> </web-app>

Page 20: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Use web.xml to initialize parameters to a servlet on start-up

<servlet> <servlet-name> counter </servlet-name> <servlet-class> InitCounter </servlet-class> <init-param> <param-name> initial </param-name> <param-value> 1000 </param-value> <description> The initial value for the counter <!-- optional --> </description> </init-param> </servlet>

Page 21: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

init

Multiple init parameters may appear within the servlet tag. The

description tag is optional.

Page 22: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

A counter with init

int count;

public void init() throws ServletException { String initial = getInitParameter("initial"); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { count = 0; } }

Page 23: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

destroy()

• This method should free up resources used by the servlet that would not otherwise be garbage collected.

• Cached information, or data to be rewritten for the next call to init can be handled here.

Page 24: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Init/destroy counter servlet

• State info is saved in a file named InitDestroyCounter.initial

• If no path is available, the server process’s current directory is used (startup dir)

• More details on specifying locations appear in a later text chapter.

• If the file can’t be opened, then the servlet looks for an init parameter.

• If no init param exist the servlet starts at 0.

Page 25: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Tomcat running this servlet

Page 26: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

State info

• State can also be saved as a specialized file format, a serialized java object or in a database.

• If the server crashes, destroy() is not called.• A servlet may chose to save state info more

frequently: a chess servlet can save state after each move, a shopping cart might save when a customer adds an item or removes an item from the cart.

Page 27: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

initDestroyCounter

• initDestroyCounter could save every ten accesses with – if(count%10==0)saveState();//at end of

doGet()

• This could cause data inconsistencies if many threads were accessing the servlet. Moving the count check and call to saveState() to the synchronized block resolves these issues.

Page 28: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Init/destroy slide 1public void init() throws ServletException { // Try to load the initial count from our saved persistent state FileReader fileReader = null; BufferedReader bufferedReader = null; try { fileReader = new FileReader("InitDestroyCounter.initial"); bufferedReader = new BufferedReader(fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt(initial); return; } catch (FileNotFoundException ignored) { } // no saved state catch (IOException ignored) { } // problem during read catch (NumberFormatException ignored) { } // corrupt saved state finally { // Make sure to close the file try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ignored) { } } // No luck with the saved state, check for an init parameter String initial = getInitParameter("initial"); try { count = Integer.parseInt(initial); return; } catch (NumberFormatException ignored) { } // null or non-integer value // Default to an initial count of "0" count = 0; } //init

Page 29: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

init/destroy slide 2 public void destroy() { super.destroy(); // entirely optional saveState(); } //destroy public void saveState() { // Try to save the accumulated count FileWriter fileWriter = null; PrintWriter printWriter = null; try { fileWriter = new FileWriter("InitDestroyCounter.initial"); printWriter = new PrintWriter(fileWriter); printWriter.println(count); return; } catch (IOException e) { // problem during write // Log the exception. See Chapter 5. } finally { // Make sure to close the file if (printWriter != null) { printWriter.close(); }//if }//finally }//saveState

Page 30: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Servlet Thread model: SingleThread

• A servlet could elect to have a pool of instances created to handle requests by implementing the javax.servlet.SingleThreadModel interface.

• This interface requires no method definitions, it simply indicates the servlet wants an alternate lifestyle.

• A server loading such a servlet must guarantee (according to servlet API) that no two threads will both execute their service methods concurrently.

Page 31: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Servlet Thread model: SingleThread

• A servlet connecting to a database might select such an option. Each database transaction requires a dedicated connection object so the servlet needs to insure two servlet instances don’t access the same connection at the same time.

Page 32: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Text has a db example

• We’ll explore database connections later on.

• Text indicates that even for this scenario a SingleThreadModel might not be best – a connection pool from which connections can be checked out and in would be better, similar to the thread pool you built in your first project.

Page 33: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Background processing

• Servlets can continue executing even after their response has been sent. Applets with animation work similarly, one method (paint) updates the graphics and another (thread) calculates the next display.

• The prime hunter servlet displays this capacity.

Page 34: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Primesearcher slide#1

public void init() throws ServletException {

searcher = new Thread(this);

searcher.setPriority(Thread.MIN_PRIORITY); // be a good citizen

searcher.start();

}

Page 35: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Primesearcher slide#2public void run() { // QTTTBBBMMMTTTOOO long candidate = 1000000000000001L; // one quadrillion and one

// Begin loop searching for primes while (true) { // search forever if (isPrime(candidate)) { lastprime = candidate; // new prime lastprimeModified = new Date(); // new "prime time" } candidate += 2; // evens aren't prime

// Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try { searcher.sleep(200); } catch (InterruptedException ignored) { } } }

Page 36: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Primesearcher slide#3

private static boolean isPrime(long candidate) { // Try dividing the number by all odd numbers between 3

and its sqrt long sqrt = (long) Math.sqrt(candidate); for (long i = 3; i <= sqrt; i += 2) { if (candidate % i == 0) return false; // found a factor }

// Wasn't evenly divisible, so it's prime return true; }

Page 37: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Primesearcher slide#4public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); if (lastprime == 0) { out.println("Still searching for first prime..."); } else { out.println("The last prime discovered was " + lastprime); out.println(" at " + lastprimeModified); } }

public void destroy() { searcher.stop(); }}

Page 38: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

destroy()

• destroy() terminates the thread – important since otherwise it would continue to run.

Page 39: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Load on startup specified in web.xml

<servlet> <servlet-name> ps </servlet-name> <servlet-class> PrimeSearcher </servlet-class> <load-on-startup/> </servlet>

Page 40: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Load on startup specified in web.xml

• Web.xml load-on-startup tag can also indicate an int – the position relative to other servlets that this one should be loaded.

Page 41: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Load on startup <servlet> <servlet-name> first </servlet-name> <servlet-class> First </servlet-class> <load-on-startup>10</load-on-startup> </servlet> <servlet> <servlet-name> second </servlet-name> <servlet-class> Second </servlet-class> <load-on-startup>20</load-on-startup> </servlet> <servlet> <servlet-name> anytime </servlet-name> <servlet-class> Anytime </servlet-class> <load-on-startup/> </servlet>

Page 42: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Load on startup

• You may want some servlets loaded and running when you start your server.

• a servlet that looks for big primes might as well start right away (see text example)

• You’ll need to modify your web.xml for Tomcat to give this instruction.

Page 43: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Primes servlet

Page 44: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

ServletServer DOS window shows servlet’s initialized

Page 45: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Client-side caching

• A client calling GET on a particular URI doesn’t necessarily want or need to perform another GET operation. Really, the client only wants the page if the content has changed. The client’s browser stores the page content.

• If we can determine whether the page content has changed then we can decide whether a new call to GET is needed.

Page 46: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Last-Modified

• When they request a page most browsers include a If-Modified-Since header. The structure of this header is the same as the Last-Modified header.

• The server can check this and determine if a page has changed. If it has the server must send the new content. Otherwise, it can send a short response that the page hasn’t changed.

Page 47: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Static vs dynamic content

• For static pages the file system itself contains this information.

• Servlets generate dynamic content. If the server must assume every access changes the content then the usefulness of Modified-Since headers is obviated for dynamic content.

• A servlet which implements the getLastModified() method can provide the server the information.

Page 48: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

getLastModified()

• The server calls this method when it generates a response in order to set the response’s Last-Modified header.

• A GET request that includes the If-Modified-Since header also generates a call to this method.

• A servlet may not be able to determine its last-modified time.

Page 49: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

A getLastModified() method for prime servlet

public long getLastModified(HttpServletRequest req) {return lastPrimeModified.getTime()/1000*1000;}

• Dividing then multiplying by 1000 essential rounds the time stamp to seconds and may help prevent unnecessarily invoking the servlet because of a time difference in milliseconds.

• Recall, the threaded prime searcher kept track of when primes were

found with a field of type Date:

Date lastPrimeModified=new Date();

Page 50: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Server-side caching

• Servlet page generation can be enhanced with a little trickery involving the servlet’s getLastModified() method with the help of the server.

• Especially important for servlets whose page content might take a long time to generate but which changes only rarely, or servlets accessing a database.

• The GuestBook servlet uses server-sde caching and the class CacheHttpServlet (a com.oreilly.servlet class), instead of HttpServlet.

Page 51: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook servlet

• User comments are stored as a Vector of GuestBookEntry objects.

• There is a built-in half-second delay per entry to simulate database access in ‘querying’ the Guestbook, but this is only a problem for the first doGet() after a new entry… Subsequent calls (until a new entry) have no delay thanks to server-side caching.

Page 52: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

compiling

• The Guestbook servlet from chapter 3 of the text uses a service class from the book’s site (CacheHttpServlet). To compile you’ll need those classes available.

public class Guestbook extends CacheHttpServlet {• Here’s a javacFile.bat:set path=c:\compilers\j2sdk1.4.1_01\bin\set jdkhome=c:\compilers\j2sdk1.4.1_01\bin\set classpath=c:\compilers\j2sdk1.4.1_01\bin\;p:\;p:\

classes;c:\compilers\j2sdk1.4.1_01\lib;p:\classes

javac %1• On the commandline I type: javacFile Guestbook.java

Page 53: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook servlet in ppt notes (CacheHttpServlet in text)(running in servletrunner on my p drive)

Page 54: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

guestbook running in Tomcat on my home machine

Page 55: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook codeimport java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;import com.oreilly.servlet.CacheHttpServlet;public class Guestbook extends CacheHttpServlet { private Vector entries = new Vector(); // User entry list private long lastModified = 0; // Time last entry was added // Display the current entries, then ask for a new entry public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); printHeader(out); printForm(out); printMessages(out); printFooter(out); } // Add a new entry, then dispatch back to doGet() public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { handleForm(req, res); doGet(req, res); }

Page 56: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook codeprivate void printHeader(PrintWriter out) throws ServletException { out.println("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>"); out.println("<BODY>"); }

private void printForm(PrintWriter out) throws ServletException { out.println("<FORM METHOD=POST>"); // posts to itself out.println("<B>Please submit your feedback:</B><BR>"); out.println("Your name: <INPUT TYPE=TEXT NAME=name><BR>"); out.println("Your email: <INPUT TYPE=TEXT NAME=email><BR>"); out.println("Comment: <INPUT TYPE=TEXT SIZE=50

NAME=comment><BR>"); out.println("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>"); out.println("</FORM>"); out.println("<HR>"); }

Page 57: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook codeprivate void printMessages(PrintWriter out) throws ServletException { String name, email, comment; Enumeration e = entries.elements(); while (e.hasMoreElements()) { GuestbookEntry entry = (GuestbookEntry) e.nextElement(); name = entry.name; if (name == null) name = "Unknown user"; email = entry.email; if (name == null) email = "Unknown email"; comment = entry.comment; if (comment == null) comment = "No comment"; out.println("<DL>"); out.println("<DT><B>" + name + "</B> (" + email + ") says"); out.println("<DD><PRE>" + comment + "</PRE>"); out.println("</DL>"); // Sleep for half a second to simulate a slow data source try { Thread.sleep(500); } catch (InterruptedException ignored) { } } } private void printFooter(PrintWriter out) throws ServletException { out.println("</BODY>"); } private void handleForm(HttpServletRequest req, HttpServletResponse res) { GuestbookEntry entry = new GuestbookEntry();

entry.name = req.getParameter("name"); entry.email = req.getParameter("email"); entry.comment = req.getParameter("comment"); entries.addElement(entry); // Make note we have a new last modified time lastModified = System.currentTimeMillis(); }

Page 58: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Guestbook code last slide

public long getLastModified(HttpServletRequest req) { return lastModified; }}

class GuestbookEntry { public String name; public String email; public String comment;}

Page 59: Servlets Lifecycle- notes from Hunter Chapter 3. An alternative approach Servlets are meant to resolve both security issues of low-level applications.

Remarks on chpt 3 servlets

• In Chapter 3, Jason Hunter’s examples extend HttpServlet, and CacheHttpServlet in different examples in this chapter.

• Guestbook extends his own class, CacheHttpServlet. PrimeSearcher and the other examples, extend HttpServlet.

• I provided no remarks on the SingleThreadConnection servlet (pg 52 of text) because the SQL connection part isn’t filled in until chapter 9.