Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
e-Science e-Business e-Government and their Technologies Introduction to Web Applications Bryan Carpenter, Geoffrey Fox, Marlon Pierce Pervasive Technology Laboratories Indiana University Bloomington IN 47404 January 12 2004 [email protected] [email protected] [email protected] http://www.grid2004.org/spring2004 1 Contents of this Lecture Set Introduction: Web applications and interfaces. The Tomcat Web server. Java Servlets and HTTP. JavaServer Pages Deploying a JSP-based Web application. 2 Web Applications We consider a Web Application to be a set of related programs and resources embedded in, or accessed through, a Web server. • The whole application may be made available as a single archive file, ready for immediate deployment in a Web server. One can identify two broad kinds of Web application: • Presentation oriented, built around dynamic HTML pages. • Service oriented, in which a Web Service is made available to other applications through XML and HTTP protocols. In this section we will be most interested in presentation oriented Web Applications. • Web services will be discussed at length in later sections. Note they commonly make use of some of the same technologies we discuss here (e.g. Servlets). 3 Web Interfaces As a matter of common experience, today’s Web is much more than a collection of static HTML documents. • We are all accustomed to Web sites that react in complex ways to requests and queries submitted through browsers. Many technologies have been introduced to facilitate this interactivity. One basic idea has been around since the earliest days of the Web, and has come through relatively unscathed, is dynamic generation of HTML. 4 Requesting a Static HTML Document Server HTTP Request GET /index.html HTTP/1.0 User-Agent: Mozilla/4.51 [en]... Host: sirah.csit.fsu.edu:8080 Accept: image/gif, ..., */* ... HTTP/1.1 200 OK Content-type: text/html <html> <head>...</head> <body> ... <html> <head>…</head> <body> … </html> Static HTML files </html> Client HTTP Response 5 Dynamic Generation of HTML Server HTTP Request GET /hello.pl?who=bryan HTTP/1.0 User-Agent: Mozilla/4.51 [en]... Host: sirah.csit.fsu.edu:8080 Accept: image/gif, ..., */* ... #!/usr/bin/perl $name = param(“who”) ; print “Content-type: text/html\n\n” ; print “<html><body>Hello $name!</body></html>\n” ; HTTP/1.1 200 OK Content-type: text/html <html> <body> Hello bryan! </body></html> Client Script, or method HTTP Response 6 Server-side Frameworks First briefly describe four general frameworks for dynamic generation of HTML: • • • • 1. CGI 2. Java Servlets 3. Microsoft Active Server Pages (ASP) 4. JavaServer Pages (JSP) All these technologies require some browser-side mechanisms to get responses from the client • Typically HTML forms, and/or Javascript. But use of HTTP and HTML means that the browserside mechanisms are quite well-separated from the server-side issues. 7 1. CGI The earliest technique for responding dynamically to browser input was CGI: Common Gateway Interface. • The FORM element of some HTML document contains input fields. • Inputted data is read by browser, forwarded to server in a GET or POST request. • The URL in the action attribute of the HTML form identifies an executable file somewhere in the Web Server’s document hierarchy. On the server side, the Web server is configured to execute this program when it receives the HTTP request created by submitting the form. 8 Action of a CGI Script The executable file may be written in any language. Here we assume it is written in Perl. • The Web Server program will invoke the CGI script, and pass it the form data, either through environment variables or by piping data to standard input of the script. • In modern Perl you can use the CGI module to hide many of these details—especially extracting form parameters. The CGI script generates a response to the form, on its standard output. This is piped to the Web server, which returns it to the browser. • The response will be the text of a dynamically generated HTML document, preceded by some HTTP headers. 9 CGI example The form element in the initial HTML document is as follows: <form action=“http://server-name/cgi-bin/hello.pl”> Name: <input type=text name=who size=32> <p> <input type=submit> </form> The CGI script hello.pl is: #!/usr/bin/perl use CGI qw( :standard) ; $name = param(“who”) ; print “Content-type: text/html\n\n” ; print “<html><body><h1>Hello $name!</h1></body></html>\n” ; 10 2. Java Servlets In conventional CGI, a Web site developer writes an executable program that processes a form’s input. The program (or script) must be executed every time a form is submitted. Servlets provide a more modern, Java-centric approach. The server incorporates a Java Virtual Machine, which is running continuously. Execution of a CGI script is replaced invocation of a method on a servlet object. • This is typically much cheaper than starting a whole new program. 11 A “Hello” Servlet import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* ; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”) ; PrintWriter out = response.getWriter() ; out.println(“<html><body>”) ; out.println(“Hello ” + request.getParameter(“who”) + “!”) ; out.println(“</html></body>”) ; } } 12 Remarks HttpServlet is the base class for servlets running in HTTP servers. The URL in the action attribute of the form might be something like: http://server-name/examples/servlet/Hello The doGet() method is called in response to an HTTP GET request directed at the servlet. As the names suggest, the request object describes the browser’s request, and the response object describes and the servlet’s response. Servlet code is very flexible, but verbose. 13 3. Microsoft ASP Microsoft independently addressed the performance issues of CGI, through ISAPI (Internet Server Application Programming Interface). Comparable to Java Servlets; an HTTP request for a dynamic page triggers a DLL call within the running server process, rather than execution of a program. One application of ISAPI that has become important is the library ASP.DLL—Active Server Pages. • An ASP page looks basically like an HTML document, but includes inserts of CGI-like code. • Effectively turns CGI “inside out”. • Scripting language for the inserts typically Visual Basic, though other languages are possible. 14 ASP Example <%@ LANGUAGE=“VBSCRIPT” %> <HTML> <HEAD><TITLE>Sample ASP</TITLE></HEAD> <BODY> Welcome. It is now approximately <%= Time() %>.<BR> Some simple text formatting using server-side code: <% For intCounter = 1 to 5 %> <FONT SIZE = <%= intCounter %>> Hello </FONT><BR> <% Next %> </BODY> </HTML> 15 Remarks The basic structure of the document looks like a static HTML documents, with some special inserts. • It includes processing directives (e.g. LANGUAGE) in <%@…%> brackets. • Server-side VB inserts appear in <%…%> brackets. • <%=expression%> is shorthand for: Response.Write expression comparable with out.println(expression) in Servlets. • Response is one of a number of predefined objects available in “scripting” inserts. We will get very familiar with this syntax later, because JavaServer Pages steals it, almost verbatim! 16 4. JavaServer Pages JavaServer Pages (JSP) allow special tags and Java code to be embedded in HTML files. These tags and code are processed by the Web server to dynamically produce standard HTML. • Produce dynamic Web pages on the server side (like Servlets), but separate application logic from the appearance of the page. • The tags allow previously compiled Java components, in the form of JavaBeans, to be used. • One can also define custom tag libraries. • May produce XML documents, instead of HTML. JavaServer Pages were developed as a response to ASP. • Built on top of Java Servlets, and use many of the same utility classes. 17 JSP elements A JSP page looks like standard HTML or XML, with extra elements processed by the JSP container. • Typically, these elements create text that is inserted into the resulting document. JSP elements include: • Scriptlet enclosed in <% and %> markers: a small script in Java to perform arbitrary functions. • Expression: anything between <%= and %> markers is evaluated by the JSP engine as a Java expression. • JSP directive enclosed in <%@ and %> markers—passes information to the JSP engine (guide “compilation”). • JSP actions or tags are a set of customizable, XML-style tags for particular actions, e.g. predefine jsp:useBean instantiates a Java Bean class on the server. 18 3 Tier Architecture URL JSP page request HTTP request JSP container compiles to a servlet HTTP response response HTTP page Browser JavaBean properties, call methods Library DB Web server 19 “Hello” Servlet Revisited import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* ; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”) ; PrintWriter out = response.getWriter() ; out.println(“<html><body>”) ; out.println(“Hello ” + request.getParameter(“who”) + “!”) ; out.println(“</html></body>”) ; } } 20 An Equivalent JSP Page <html> <body> Hello <%= request.getParameter(“who”) %> ! </body> </html> 21 Remarks A suitable form element to front-end this page might be: <form action=“hello.jsp”> Name: <input type=text name=who size=32> <p> <input type=submit> </form> The JSP version is much more compact and easier to understand! We can expect this to be generally the case when the logic behind a dynamic page is relatively simple, and the bulk of the content is static HTML. 22 References Web Development with JavaServer Pages, Duane K. Fields and Mark A. Kolb, Manning Publications, 2000. • Thorough, insightful. Core JSP, Damon Houghland and Aaron Tavistock, Prentice Hall, 2001. • Some imaginative examples. Good section on JSP and XML. JavaServer Pages, 3rd ed, Hans Bergsten, O’Reilly, 2004. Core Servlets and JavaServer Pages, Marty Hall, Prentice Hall, 2000. • Useful reference for Servlets, especially. JavaServer Pages, v2, and other documents, at: http://java.sun.com/products/jsp/ 23 Getting Started with Tomcat 24 Server Software Standard Web servers typically need some additional software to allow them to run Servlets and JSP—a socalled Servlet Container. There are commercial products e.g.: • New Atlanta ServletExec (www.newatlanta.com) • Macromedia Jrun (www.macromedia.jrun/software/jrun) For this course you will be expected to use: • Apache Tomcat (http://jakarta.apache.org/tomcat) The official reference implementation for the Servlet 2.4 and JSP 2 specifications. Can be used as a small, standalone Web server, or as a servlet container for Apache, IIS, iPlanet, etc servers— look under JK in the Tomcat documentation. 25 Tomcat Tomcat is an open source Web Server, implemented entirely in Java. It can be used to serve ordinary static Web content (HTML, etc), but its main claim to fame is as the reference implementation of the Servlet and JSP specifications. For purposes of coursework you should download and install Tomcat on a computer available to you. • Any PC running Windows (for example) should suffice. • For debugging class projects, you can access your server through localhost URLs, so you don’t need a registered domain name (or even an Internet connection). 26 Downloading Tomcat 5 I will give instructions for installing Tomcat 5 under Windows (details for Windows XP). • You can also easily install on Linux, or other UNIX flavor. If you choose to work on a shared UNIX machine, be aware that you may have adjust your port number to avoid clashing with servers run by other users. • I assume Java is already installed on your computer (preferably Sun J2SE 1.4 or later). Go to http://jakarta.apache.org/tomcat/ Follow the “Binaries” link for download, and scroll down to Tomcat 5 archives and installers. Get the installer for Windows: at the time of this writing the file was called “jakarta-tomcat-5.0.18.exe”. • Size of the file was about 10MB. 27 Installation Run the installer. On the installation wizard, click through, accepting the Apache License agreement. In the instructions that follow I assume you accept the default installation options, so the install location will probably be: C:\Program Files\Apache Software Foundation\Tomcat 5.0 • You will need about 40MB of free disk space. I also assume that you accept the default port number for Tomcat, which is 8080. • You may choose 80, if there is no other Web server running on the computer, but I will assume the 8080 default. You may take the opportunity to set a good admin password for the Web server. You will also be prompted for the name of the folder where Java is installed, but the wizard usually makes a good guess. 28 Running the Server By default on Windows the server will start automatically when installation completes. You should see a progress window like: When startup completes this window disappears, and you will probably see an icon like this in your taskbar: If things don’t happen exactly like this, don’t panic! There are several different ways to start and stop the server, discussed shortly. 29 Check Your Server is “Up” If you are running Tomcat on your local PC, point your Web browser at: http://localhost:8080 If you are running your web server on a remote host called hostname, point your browser at: http://hostname:8080 You should see the default Tomcat home page, which contains some useful documentation: 30 Restarting the Server This is a seemingly trivial skill that needs to be properly mastered! • You will find that restarting the server is a vital part of the debugging cycle for Web applications: if you think you restarted the server, but it didn’t really restart, you can go down frustrating blind alleys of debugging. There are at least 3 mechanisms for starting and stopping the server under Windows. 31 Stopping and Starting the Server Three ways: 1. To Start: use the shortcut you find under: start→All Programs→Apache Tomcat 5.0 To Stop: right-mouse-click on Tomcat icon that appears on the taskbar, and select “Shutdown”. 2. Use the Windows “Services” tool that you may find through the Windows Management console or perhaps through start→Control Panel→Administrative Tools→Services This gives a convenient way to start, stop, or restart services, including Tomcat. 3. From a Windows Command Prompt, run the batch files startup.bat, shutdown.bat which you will find in bin\ under the installation folder, typically: C:\Program Files\Apache Software Foundation\Tomcat 5.0\bin\ 32 Tips for Restarting Choose one of the approaches on the previous slide: mixing one approach to starting with another for stopping isn’t likely to work properly! Approach 1 is perhaps the most “natural” under Windows, but for me it seemed error-prone. • Approach 2 seems OK. Approach 3 is robust because it displays a console window while the server is running, so you know for sure whether the server is up or down. Until you are confident you have this mastered, regularly check whether or not the server is running by: 1. 2. 3. clearing your browser cache (Tools→Internet Options→Delete Files under IE 6), then (for added assurance) restarting your browser, then trying to visit the URL http://localhost:8080 33 Using Linux Tomcat runs very well under Linux. Follow the instructions in the Tomcat documentation for installation. To start or stop the server, use the scripts startup.sh, shutdown.sh in the Tomcat installation bin/ directory. 34 A First Web Application As a toy example, we will deploy the trivial “Hello World” of dynamic HTML. We create a Web Application that consists of one static HTML document with a form prompting for the visitor’s name, and a dynamic JSP document that displays a customized greeting for that visitor. 35 Preparing a folder Under Tomcat, each web application should be created in a dedicated folder, normally created under the folder called webapps\ in the server installation directory. First I make a folder: C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\grid04hello\ Within the new folder I must create a nested folder called “WEB-INF\”. • For now the subfolder can be empty. But without a grid04hello\WEB-INF\, Tomcat 5 will not automatically recognize grid04hello\ as a web application folder! 36 A “Hello Web” Application In the grid04hello/ folder I create the two files index.html: <html> <body> <form method=“get” action=“hello.jsp”> Name: <input type=“text” name=“who” size=“32”/> <p/> <input type=“submit”/> </form> </body> </html> and hello.jsp: <html> <body> Hello <%= request.getParameter(“who”) %> ! </body> </html> 37 Files and Folders Tomcat 5.0\ webapps\ grid04hello\ hello.html hello.jsp WEB-INF\ [currently empty] …other Web applications … …Tomcat server code, configuration, logs, etc… 38 Starting the Web Application To “start” the Web application (i.e. to get it loaded into your server) you just need to restart your Tomcat server. • If you are developing a simple Web application like the one here, using only HTML and JSP files, you don’t usually need to restart more than once. A running server will recognize when deployed JSP files are edited, and recompile them automatically. But you do have to restart the server to get the new application recognized initially (later we describe an alternative way to deploy the application). 39 Using the Web Application Visiting http://localhost:8080/grid04hello/hello.html, I should see something like: On entering my name, and hitting submit, I see: 40 The Rest of this Section We discuss Java Servlets in some detail. For presentation-oriented Web Applications JSP is usually more convenient. But JSP and other Java Web technologies are built on top of Servlets, and you will need some knowledge of the Servlet classes to use JSP effectively. We cover writing Web Applications with JSP. We will also say something about managing Tomcat. General organization of Servlet-based Web applications. 41 Java Servlets 42 Servlets At its most abstract, a Java Servlet is a Java class that can be embedded in a some general-purpose server program. A subset of requests arriving at the server—presumably those matching some selection criterion—will be redirected to the servlet for special handling. Although servlets are supposedly deployable in various kinds of servers (HTTP, Databases, FTP, …?), we will only be interested in HTTP servlets, embedded in Web servers. Most commonly a servlet is responsible for handling HTTP GET or POST requests, directed at a particular URL. 43 Contents of this Section Introduction • Review of HTTP features. • Simple servlet. • Servlet deployment issues. Servlet programming. • Form processing with Servlets. • Servlet Life Cycle. • Generating responses. Cookies and session-tracking. 44 References Core Servlets and JavaServer Pages, Marty Hall, Prentice Hall, 2000. • Good coverage, with some discussion of the Tomcat server. • There is a 2001 sequel called “More Servlets and JavaServerPages”. Java Servlet Programming, 2nd Edition, Jason Hunter and William Grawford, O’Reilly, 2001. • Haven’t seen second edition, but 1st ed (1998) was good, with some good examples. Java Servlet Specification, v2.4, and other documents, at: http://java.sun.com/products/servlet/ 45 The HTTP Protocol We begin by reviewing some essential features of Hyper Text Transfer Protocol. HTTP is a textual, client-server protocol, consisting of requests and responses. It is commonly implemented over TCP, though other underlying protocols are possible. • e.g. some handheld devices implement the most important parts of HTTP, but not general IP protocols. Like many W3C documents, the detailed specification is bizarrely complex, but the most important ideas are very simple. 46 A GET Request When one points Internet Explorer 6 (say) at a URL like http://www.grid2004.org/index.html, the HTTP request sent to the server may look something like: GET /index.html HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Host: www.grid2004.org Connection: Keep-Alive • Exercise: adapt the “Simple Server” program, outlined early in the section on Java sockets, to print out the HTTP request it receives. Confirm the format above by pointing a browser at your “server”. 47 Anatomy of an HTTP Request If you are not very familiar with the HTTP protocol, study the format of this request. The individual lines here are called “headers”. Even without prior knowledge you may be able to guess the meaning of many of the headers. • After the headers, there is a blank line—not obvious on the previous slide, but important to a well-formed request. 48 POST Requests Another common HTTP request is the POST request. • In ordinary Web browsing this is commonly used to send some data to the server, submitted using an HTML form. • In this context the data might include values of fields typed directly into the browser window, and uploaded contents of local files, selected through a form. The format is very similar to GET, except that the first word in the method header is “POST”, and the blank line terminating the headers is followed by the posted data. • The following example was generated by submitting a form. Note two extra headers: Content-length and Cachecontrol. The posted data is simply: “who=Bryan”. 49 An Example POST Request POST /handleform HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Host: www.grid2004.org Content-Length: 9 Connection: Keep-Alive Cache-Control: no-cache who=Bryan 50 The HTTP Response A typical HTTP response has a format similar to the HTTP post request: a series of headers, a blank line, then the returned data. • The returned data may for example be an HTML page. The first header now gives an error status for the request: a status code of 200 indicates success. The following response could be generated by the server when the course home page is requested. • Exercise: compile and run the TrivialBrowser class, given early in the section on Java sockets. You should see something similar to the contents of the next slide. 51 Example HTTP Response HTTP/1.1 200 OK Date: Fri, 06 Feb 2004 01:34:56 GMT Server: Apache/1.3.29 (Unix) PHP/4.3.4 Last-Modified: Thu, 29 Jan 2004 22:27:25 GMT ETag: "832b65-2cf-401988cd" Accept-Ranges: bytes Content-Length: 719 Content-Type: text/html <!DOCTYPE HTML PUBLIC …> <HTML> <HEAD> <TITLE>e-Science e-Business e-Government and their Technologies</TITLE> … </HTML> 52 The HttpServlet class Having reviewed some essential features of HTTP, we are ready to start describing servlets. Every HTTP servlet will extend the base class HTTPServlet, which is defined in the package javax.servlet.http. This class defines a series of request-handling methods: doGet() doPost() doPut() doDelete() doOptions() doTrace() Handle HTTP GET request. Handle HTTP POST request. Handle HTTP PUT request. Handle HTTP DELETE request. Handle HTTP OPTIONS request. Handle HTTP TRACE request. When you define a new servlet class, you normally override one or more of these methods. 53 A “Hello World” Servlet import java.io.* ; import javax.servlet.* ; import javax.servlet.http.* ; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”) ; PrintWriter out = response.getWriter() ; out.println(“<html><body>”) ; out.println(“<h1>Hello World!</h1>”) ; out.println(“</html></body>”) ; } } 54 A Request Handling Method All HttpServlet request-handling methods (doGet(), doPost(), etc) have a similar interface. They are passed parameters of type HttpServletRequest, HttpServletResponse • Needless to say, these are Java objects representing the HTTP request and response. The request and response objects have methods for accessing the headers, the data “payload”, and other properties of the HTTP messages. • In the example, the first line of doGet() sets the Content-Type header of the response, and the remaining lines write the data payload—a short HTML document—to the response. • The servlet container can complete most headers in the response, but setting the Content-Type header is mandatory. 55 Deploying Servlets At the end of the section introducing Tomcat, we deployed a trivial Web app using a JSP page. We nested a folder in webapps/ for our applications, and also created an empty subfolder called WEB-INF/. In general the WEB-INF/ folder of an application holds associated classes and XML descriptors. In particular servlet class files and the deployment descriptor (“web.xml” file) go in the WEB-INF/ folder. In the following example we recycle the grid04hello/ folder created earlier. 56 Files and Folders Tomcat 5.0\ webapps\ grid04hello\ …HTML and JSP files … WEB-INF\ web.xml classes\ Hello.class …other Web applications … …Tomcat server code, configuration, logs, etc… 57 Compiling the Servlet The servlet source should be contained in a file Hello.java. • You can conveniently put the source itself in the classes\ subfolder of WEB-INF\, and compile it “in situ”. • Or compile the source wherever you like, and just copy the class file to classes\. 58 Setting the Class Path If you are using javac from a command prompt, you must add the servlet classes to the class path, so the compiler knows where to find them. • e.g. click to start→Control Panel→System→Advanced→Environment Variables and define new system variables: TOMCAT_HOME c:\Program Files\Apache Software Foundation\Tomcat 5.0 CLASSPATH .;%TOMCAT_HOME%\common\lib\servlet-api.jar If you are using an IDE like JBuilder, there will probably be built-in support for developing servlets. You may not have to worry about these details. 59 The Deployment Descriptor Tomcat 5 apparently requires a deployment descriptor mentioning every servlet class in the Web application. Create a file web.xml in the WEB-INF\ folder—a minimal descriptor for our servlet is given on the next slide. Don’t worry if this doesn’t make much sense to you—we will cover XML shortly. You may copy the example web.xml file from: Tomcat 5/servlets-examples/WEB-INF/web.xml and edit it appropriately. • The important parts are the <servlet> and <servlet-mapping> elements, which define the servlet class and the URL it is found at. 60 Minimal web.xml File <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>grid2004 Hello examples</display-name> <description>grid2004 Hello examples.</description> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/servlet/Hello</url-pattern> </servlet-mapping> </web-app> 61 Viewing the Servlet Restart your Tomcat server. Visit the URL: http://localhost:8080/grid04hello/servlet/Hello You should see something like: 62 Servlets vs JSP Compared with our earlier “Hello Web” JSP application, you will notice that writing and deploying a Java servlet is much more work. This isn’t surprising, because JSP is a higher level application layered on servlets. If you are building an application around dynamic HTML, it will nearly always be preferable to use JSP. But it is important to know something about raw servlets, because eventually you will want to implement HTTP applications (e.g. Web services) that do something other than generate dynamic HTML. For these JSP won’t help. 63 Servlet Programming 64 Form processing with Servlets Assume we have a form in an HTML document like <form method=“get” action=“http://hostname:8080/grid04hello/servlet/Hello”> Name: <input type=text name=who size=32> <p> <input type=submit> </form> This supposes Tomcat is running on port 8080 on the host hostname. 65 Getting Form Parameters A suitable goGet() method in the Hello servlet class would be: public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”) ; PrintWriter out = response.getWriter() ; out.println(“<html><body>”) ; out.println(“Hello ” + request.getParameter(“who”) + “!”) ; out.println(“</html></body>”) ; } The method getParameter() of HttpServletRequest will parse the HTTP request and extract the named form parameter (“who” in this example). • If a single form parameter has multiple values (allowed in HTML), can instead use request.getParameterValues(), which returns an array. 66 GET vs POST: Idempotence If the method attribute on the form is GET, the form data is appended to the path component of the action URL, and sent in an HTTP GET request. • Be aware browsers may silently retry GET requests that apparently failed. Use the GET method only for actions that are idempotent— actions where accidental repeats don’t have observable effects: A Google search for a particular topic is effectively idempotent. Transferring $1000 from your bank account is not idempotent. If the method is POST, the URL is not extended: the form data is sent in the data payload of an HTTP POST request. • Browsers are supposed to prompt before retrying a POST request. To handle a POST request with a servlet, define the doPost() method instead of the doGet() method: other details are unchanged. 67 URL Encoding URL encoding is a method of wrapping up form-data in a way that will make a legal URL for a GET request. • The encoded data consists of a sequence of name=value pairs, separated by &. • Spaces in values are replaced by +. • Non-alphanumeric characters are converted to the form %XX, where XX is a two digit hexadecimal code. • In particular, line breaks in multi-line form data (e.g. addresses) become %0D%0A—the hex ASCII codes for a carriage-return, new-line sequence. URL encoding is somewhat redundant for the POST method, but it is the default anyway. If you are using servlets you usually don’t need to worry about any of this, because getParameter() and related methods do the decoding for you. 68 Reading Posted Data Where posted data is not simply URL Encoded form parameters (e.g. if a file is uploaded, producing to posted data in multipart MIME format), the data may be read directly: public void doPost(HttpServletRequest req, HttpServletResponse resp) { … BufferedReader in = new BufferedReader(req.getReader()) ; String line ; while((line = in.readLine()) != null) { … } … } Don’t try to combine reading data using getReader() with the higher-level approach using getParameter()—choose one or the other. 69 Information from Request Headers There is a series of convenience methods that read information from the request headers, including: getMethod(), getRequestURI(), getProtocol() Method header getContentLength() Content-Length header getContentType() Content-Type header getAuthType(), getRemoteUser() Authorization header getCookies() See later getHeader(String name) getHeaders(String name) getHeaderNames() Any HTTP request header Enumeration of headers Enumeration of header names Exercise: Study the servlet RequestHeaderExample, which comes in the “servlet examples” in the Tomcat release, for an example inspecting request headers. 70 Servlet Life Cycle By default, a Web server only creates one instance of a servlet class for each <servlet> element in the web.xml file. • All requests to the same URL are handled by the same servlet class instance. This means that a request may see effects of processing earlier requests through values of instance variables. • Or class variables. By default, though, each request is handled in a different Java thread. • So mutual exclusion is an issue. 71 A Counter Servlet public class Counter extends HttpServlet { int count = 0 ; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”) ; PrintWriter out = response.getWriter() ; out.println(“<html><head></head><body>”) ; out.println(“This servlet instance has been accessed ” + (count++) + “ times”) ; out.println(“ </body></html>”) ; } } 72 Remarks The first time I point my browser at this servlet I get a response page containing the message: This servlet has been accessed 0 times Each time I reload the URL, the count increases. Since count is an instance variable of the class, this illustrates the case that only a single instance of Counter is created. 73 Mutual Exclusion The counter servlet is not completely reliable, because it is possible to have concurrent requests handled in different threads. The instance variable count is shared by threads. This could lead to problems of interference. For example, the increment of count could be done in a synchronized statement: int myCount ; synchronized(this) myCount = count++ ; Subsequently the local variable myCount—which is private to the thread—is printed in the response. 74 The init() Method The init() method: public void init() throws ServletException {. . .} is called once when the servlet is created. You override it to define initialization code for your servlet instance. 75 Initialization Parameters A new counter servlet, defining an init() method: public class InitCounter extends HttpServlet { int count ; public void init() throws ServletException { ServletConfig config = getServletConfig() ; try { count = Integer.parseInt(config.getInitParameter(“initial”)) ; } catch (NumberFormatException e) { count = 0 ; } } … definition of doGet() method … } 76 Defining Initialization Parameters In web.xml, I add the element: <servlet> <servlet-name>Counter2</servlet-name> <servlet-class>InitCounter</servlet-class> <init-param> <param-name>initial</param-name> <param-value>50</param-value> </init-param> </servlet> If I restart the server and point my browser at this servlet I see the (misleading) message: This servlet has been accessed 50 times 77 Generating Responses A minimal server response to a client request might be: HTTP/1.1 200 OK Content-Type: text/plain Hello World! We already saw how to set the content type explicitly using setContentType(). • In general the content type can be any MIME type recognized by the browser. A servlet can explicitly set other values by using the setStatus() method. 78 Explicitly Returning Status Codes Status values are available as predefined constants in the HttpServletResponse class, e.g: final int SC_OK = 200 ; final int SC_FOUND = 302 ; final int SC_NOT_FOUND = 404 ; Use like: response.setStatus(HttpServletResponse.SC_OK) ; 79 Common Cases There are a couple of convenience methods on HttpServletResponse for dealing with common cases: void sendError(int sc, String message) • send specified status, with generated page containing message. void sendRedirect(String location) • send SC_TEMPORARY_REDIRECT status, and include Location header. By sending the SC_FOUND or SC_TEMPORARY_REDIRECT status, together with a dynamically generated URL, a servlet can cause a the browser to go directly to a different page or site (without the user manually clicking another link). 80 Cookies and Session Tracking 81 The Problem HTTP is said to be a stateless protocol. It consists of a series of request/response transactions with no intrinsic association between different transactions. • Stateless protocols have reliability advantages: recovery from failure, robustness and simplicity of protocol implementation. • Modern HTTP isn’t completely stateless; by default it tries to keep TCP connections open between transactions. Very often a Web application needs a server to engage in an extended dialog with a client, involving a series of requests and responses. So the problem is how to define and keep track of a particular “session” between client and Web server. This is called session tracking. 82 Example Classic example of “session information” is the contents of a customer’s shopping cart, at an online store. Typically the shopping carts of all customers actively browsing a site will be stored on the server side (e.g. in data structures managed by a servlet). But every HTTP request coming from a customer must somehow be tagged with information correlating the transaction with a particular session. • When a customer chooses a new item, the server needs a nugget of identifying information, to decide which shopping cart the new item should go in. 83 Basic Approaches Practical approaches to attaching session information to transactions include: • URL-Rewriting (“fat URLs”) Assumes all pages associated with the session are dynamically generated by the server. Session identification is directly appended to any URLs in the generated pages that refer back to the same server. • Cookies An extension to HTTP that lets a Web server ask a browser to store small amount of identifying information. The browser returns this information in subsequent HTTP request headers, when it revisits the same server. We will focus on use of cookies, because they provide the most flexibility, and they are used almost universally today. 84 Cookies If a browser receives an HTTP response including a Set-Cookie header (and is willing to take the cookie) it stores the information in the header. This information can either be stored in the memory of the browser process (“session cookie”) or saved to disk (“persistent cookie”). Whenever a browser constructs an HTTP request for a server, it checks whether it is storing any cookies it previously received from the server. If so, it returns the cookie information in a Cookie header attached to the new request. 85 Uses of Cookies 1. Recognizing a regular customer • 2. Session Tracking • A persistent cookie can save some identification information for a particular customer. The stored information could be actual name or details, but more likely some opaque key into a database on the server. Within a single dialog with a site, session cookies can be used as the underlying mechanism for session tracking. The first application is limited, because many people configure their browsers to reject persistent cookies, regarding them as an intrusion of privacy. But nearly everybody will accept session cookies (you have to work quite hard to make Internet Explorer reject session cookies). 86 The Servlet Cookie API A servlet creates a cookie by using a constructor for the class Cookie. Various attributes can be set for the cookie before sending it to the client. They include: • The name and value of cookie • The domain to which the cookie should be returned. By default the cookie will only be returned to the server that sent it, but this default can be overridden. • The URI path to which the cookie should be returned. By default, the cookie is only returned to pages in the same directory as the page that sent the cookie. • The time when a persistent cookie expires. 87 Example View the “Cookies” example in the Tomcat release. If you are running Tomcat locally, go to http://localhost:8080/servlets-examples/ In the example, the lines that add a set-cookie header to a server response are: Cookie c = new Cookie(name, value); response.addCookie(c); The resulting HTTP response will include a header like: Set-Cookie: name=value 88 Browser Behavior If the browser accepts a cookie, it returns a cookie header like Cookie: name=value in HTTP requests, when revisiting the same server. In servlet code you read the set of cookies returned by the browser by, e.g.: Cookie[] cookies = request.getCookies(); • Exercise: Set one or two cookies using the “Cookies” example in the Tomcat release. After setting the cookies, also visit the “Request Headers” example to see the returned HTTP cookie headers themselves. 89 The Session Tracking API You should be able to see in a general way how the Servlet cookie API can be used for session tracking. Actually you don’t need to explicitly manipulate cookies to achieve this: servlets provide a higher-level API that transparently uses cookies to keep track of sessions. • Using the higher-level API has the added benefit that it also supports URL-rewriting as a tracking mechanism, in the (fairly unlikely) event that a browser doesn’t support session cookies. 90 The HttpSession class A session is defined as an association—lasting for some time—between a particular browser and a particular Web application. It is represented by an instance of the HttpSession class. • A servlet method retrieves the current session object by applying the method getSession() to the HttpRequest. • If no session object exists on a call to getSession(), a new one will be created. Objects of any type can be bound to sessions by storing them as named attributes in the session, using the setAttribute(), getAttribute() methods of HttpSession. 91 Shopping Cart Using a Session public void doGet(HttpServletRequest req, HttpServletResponse resp) throws … { HttpSession session = request.getSession(true) ; ArrayList shoppingCart = (ArrayList) session.getAttribute(“cart”) ; if(shoppingCart == null) { // New session shoppingCart = new ArrayList() ; session.setAttribute(“cart”, shoppingCart) ; } } … Add or remove items from cart … 92 Remarks The true argument of getSession() means that a new session object will be created if one does not already exist—you should probably always use this argument. See the “Sessions” example in the Tomcat release for a complete example using various session tracking methods. • It is instructive to revisit the “Cookies” example after starting a session: you should find a cookie called JSESSIONID has been established. 93 Session Attributes vs. Instance Variables In Java programs, local variables are normally declared inside methods to hold values computed and used within the invocation. Typically, instance variables are used to hold values that need to be shared across multiple invocations. In servlet programming—where several browser sessions may be concurrently operating on a single servlet instance—this role for instance variables is naturally taken over by attributes of the session object. • Think hard before declaring an instance variable in a servlet! In many cases you should probably be using a session attribute instead. 94 The Scope of a Session A servlet context is a group of servlets (and possibly other resources), collected together as a Web application. Several servlets may be involved in the same session, hence share the same HttpSession object. • This sharing is automatic if the servlets are in the same context, and are interacting with the same browser. Servlets from different contexts in the same server, or interacting with different browsers, always have distinct HttpSession objects. 95 Life-Time of a Session In general a session expires after some interval. The method: public void setMaxInactiveInterval(int seconds) on HttpSession can be used to request that the session will be invalidated if there has been no transaction in the specified interval. The method: public void invalidate() on HttpSession can be used to forcibly end a session. 96 JSP: JavaServer Pages 97 What is a JSP Page? According to the JavaServer Pages Specification: • “A JSP page is a text-based document that describes how to process a request to create a response. The description intermixes template data with some dynamic actions.’’ JSP deliberately supports multiple paradigms for authoring dynamic content. • These include Scriptlets, JavaBeans and Tag Libraries. 98 JSP Features Fixed template data—the parts of a JSP page that are used verbatim in the response. In simple cases this data will take the form of plain HTML. It may also be XML, or plain text. Standard directives guiding translation of a JSP page to a servlet. Scripting elements: scriptlets, expressions, and declarations that include Java fragments to embed dynamic content. Standard actions which are predefined XML-like tags. A tag extension mechanism, called tag libraries. 99 Translating and Executing JSP Pages A JSP page is executed in a JSP container, generally installed in a Web server. The underlying semantic model is that of a servlet. • A JSP container will translate the JSP page to a Java servlet. By default, translation and compilation of a JSP page is likely to occur the first time it is accessed. • With Tomcat 5, you can find the generated Java and the class files in a subdirectory under the folder Tomcat 5.0\work\ . 100 Directives vs Request-time Operations Directives provide “global” information about the behavior of a JSP page—independent of any specific request. • In practice, they guide the process of translation from JSP to a Java Servlet. They are “compile-time” instructions. Scripting elements and actions have some effect in the context of a particular request. • e.g. generating some output that depends on form parameters, creating an object in the JSP container, or reading or writing entries in a database. 101 Scripting Elements The two most important kinds of scripting element are: • Scriptlets: arbitrary fragments of Java that are executed in the request handling method. Syntax is e.g.: <% out.println(“Your lucky number is ” + Math.random()) ; %> • Expressions: any Java expression, cast to a String. Evaluated in the context of the request handling method. Syntax is e.g.: <%= Math.sqrt(2) %> Don’t confuse JSP scripting elements with JavaScript! JSP is executed on the server side. JavaScript is usually executed in the browser. You can freely use JSP to generate HTML documents that include JavaScript inserts, which will be executed later in the browser. But these are different from JSP scripting elements, and have different syntax. 102 A JSP Page with a Scriplet <html><head></head><body> <% out.println(“Now is ” + new java.util.Date()) ; %> </body></html> This is the complete JSP page. Just save this text in, e.g., “date.jsp”, and install it in a suitable document directory. Don’t forget the semicolon! • The scriptlet must yield a legal Java program when it is inserted into the automatically generated servlet code. • Since compilation is done on the fly, syntax errors are reported through the browser the first time you visit the page. If you forget the semicolon you will get a cryptic error message referring the generated servlet. 103 Viewing the date.jsp Page If we visit date.jsp we see something like: 104 “Compound” Scriptlets A compound statement doesn’t have to be confined to a single scriptlet element—it can be assembled from several scriptlet elements, surrounding blocks of template text. Here is an example using a conditional around blocks of template data: <html><head></head><body> <% if (Math.random() < 0.5) { %> Dean for President! <% } else { %> Vote Kerry! <% } %> </body></html> Earlier warnings about syntax errors apply—take special care not to lose any braces! 105 Expressions A JSP expression is very similar to a scriplet, except that the enclosed Java code is required to be an expression. The expression is evaluated, then converted to a String. The string is interpolated into the template text— wherever the element appears—and sent to the browser as part of the generated HTML. The syntax of an expression element is: <%= Java expression in here %> • Distinguished from a scriptlet by the = sign. 106 Avoiding out.println() We can use an expression to replace the first scriplet in this lecture, viz: <html><head></head><body> <% out.println(“Now is” + new java.util.Date()) ; %> </body></html> with: <html><head></head><body> Now is <%= new java.util.Date() %> </body></html> In general, expression elements save us writing many scriptlets that just include calls to out.println(). 107 Predefined Variables in JSP Some variables are predefined for use in JSP scriptlets and expressions. In earlier examples we used the variable out, for example. This refers to the PrintWriter associated with the servlet HttpResponse object. 108 Some Predefined Variables request The HttpServletRequest object describing the current request. response The HttpServletResponse object describing the response currently being prepared. out The PrintWriter object associated with response. session The HttpSession object associated with the request. 109 Directives The general syntax is of a directive is: <%@ name attr1=“value1” attr2=“value2” … %> where name is the name of the directive, and attr1, attr2, . . . are the names of various attributes associated with this directive. The currently allowed values for name are page, include and taglib: • The page directive defines various attributes associated with a page. • The include directive allows another file to be textually included. • The taglib directive imports a tag library. 110 The import attribute For now the most important attribute that can be set by the page directive is the import attribute. This simply adds an import directive to the generated Java code. Syntax is, e.g.: <%@ page import=“java.util.*” %> 111 Actions and Beans Scripting elements of JSP are powerful. • Give us essentially all the power of Java and servlets, but with the code embedded directly in an HTML page. Code fragments and HTML are simply separated by <%, %> brackets. This is both an advantage and a disadvantage: • Allows a dynamic page to be developed and deployed quickly. • Equally quickly, the JSP source can become difficult to read. An HTML page containing many Java inserts can be difficult to read and maintain. • The same remarks may presumably be applied to syntactically similar systems (e.g. ASP, PHP). 112 Actions JSP actions are special elements that follow an XMLlike syntax. They sit naturally within an HTML document (and presumably are comfortable for Web designers). It is possible to write JSP pages that use actions exclusively—there need not be any Java source embedded in the HTML page. • One can still invoke Java code through JavaBeans. More practically, one can use actions to instantiate and set properties of beans, but still admit scripting elements for invoking methods on beans, and for adding conditional and looping control to the JSP page. 113 The Standard Actions Predefined action tags include: • jsp:useBean - declares the usage of an instance of a JavaBeans component. • jsp:setProperty - this tag can be used to set properties of a bean. • jsp:getProperty - gets the property of the Bean, converts it to a String, and puts it into document. • jsp:forward - forwards the request to another JSP page or servlet. • jsp:include - include another JSP page 114 Syntax All actions follow an XML-like syntax: an element either has the form: < name attr1=“value1” attr2=“value2” . . . /> or the form: < name attr1=“value1” attr2=“value2” . . . > JSP body of element </ name > Here name is the name of the element, and attr1, attr2, . . . are the names of various attributes associated with this element. 115 JavaBeans JavaBeans is a component architecture. It dictates a set of rules that software developers follow to create reusable components. A Bean is an instance of a class that was coded following these rules. For our purposes, a Bean is simply an instance of a selfcontained Java class used in an JSP page. JSP interacts with Beans through “actions”, or simply by calling methods on the bean, from scripting elements. 116 Elementary Use of Beans in JSP The jsp:useBean action tells a page that a particular Bean is to be used here. Its minimal form names a Bean, and specifies its class. If there is no Bean of the specified name currently “in scope” the jsp:useBean method creates a new Bean instance. • A JavaBean must have a public no-argument constructor. This allows a Bean container to instantiate the class without previous knowledge of the class. 117 The “Use Bean” Element. The basic form of the element is: <jsp:useBean id=“bean-name” class=“class-name” scope=“scope”/> • The name bean-name should be a legal Java variable name. Appearance of this tag causes a variable of this name, and type class-name, to become available in any following scripting elements. • The class called class-name is typically defined in the classes\ folder of the Web application. • The jsp:useBean element may also contain “conditional text” that is only included if the Bean is freshly created. • The scope attribute is discussed in the next slide. 118 Controlling a Bean’s Scope The accessibility and lifetime of a Bean created by a JSP page is controlled by the scope attribute of the jsp:useBean element. The most useful values are session The current session. The bean automatically becomes an attribute of the HttpSession object. The bean is typically created at the start of a client session, and garbage-collected when the session ends. application Available to any request in the same Web application (servlet context). Effectively a global variable that lives as long as the Web server is running, and is shared between client sessions. 119 “Session Beans” By declaring beans with session scope we can avoid having to deal explicitly with the HttpSession object. We may loosely refer to these as “session beans”, but they should not be confused with the EJB concept of a session bean. • Enterprise JavaBeans is a much more specialized architecture than “ordinary” JavaBeans. 120 JSP Tag Libraries We saw that the JSP standard actions are a set of tags for creating and manipulating beans, and a few other purposes. They are useful but fairly limited. JSP allows creating of custom tags through tag libraries. This is a powerful feature, that allows you to build whole new XML-like vocabularies for creating dynamic Web pages. We don’t have time to do full justice to tag libraries here, but you can download many standard tag libraries from: http://jakarta.apache.org/taglibs 121 A Simple Web Application 122 A Complete Web Application We round off this section by giving the full source of a tiny but self-contained Web application, which uses multiple (two) JSP pages and a JavaBean, and does non-trivial session tracking. We mentioned earlier that the classic example of “session information” is the contents of a customer’s shopping cart at an online store. In the interests of fitting code in slides, we scale this down and deal with selections from a virtual snackvending machine. • “. . . Think of clocks and counters and telephones and board games and vending machines.” C.A.R Hoare, Communicating Sequential Processes, 1985. 123 Snack-Vending Machine The first page of our Web application is the selection page, implemented by a JSP called vendingmachine.jsp. The generated page contains a series of small HTML forms, each with a single button for selecting snack items. When we click on a snack, we return to the selection page, but our selection is now appended to a list maintained by the server. In our implementation, this list is abstracted in a session bean of class vending.VendingBean. This bean also maintains the fixed list of all snacks available from the vending machine. 124 vendingmachine.jsp <html><head></head><body> <jsp:useBean id="vendingBean" class="vending.VendingBean" scope="session"/> <% String snack = request.getParameter("selection") ; if(snack != null) vendingBean.addSelection(snack) ; %> <% for (int i = 0 ; i < vendingBean.getNumSnacks() ; i++) { %> <form action="vendingmachine.jsp"> <input type="submit" name="selection" value="<%= vendingBean.getSnacks(i) %>" /> </form> <% } %> <a href="checkout.jsp">Proceed to checkout</a> </body></html> 125 Generated HTML If we view the generated HTML of the initial page, (View→Source in Internet Explorer) it includes a series of forms—one per snack. The submit button for each form sets a value for the parameter called selection, value is name of the snack: <html><head></head><body> <form action="vendingmachine.jsp"> <input type="submit" name="selection" value="Chips"/> </form> <form action="vendingmachine.jsp"> <input type="submit" name="selection" value="Popcorn"/> </form> ... <a href="checkout.jsp">Proceed to checkout</a> </body></html> 126 The Initial Page Visiting the vendingmachine.jsp page, I see something like: 127 Selecting a Snack On the first visit to the vendingmachine.jsp, the form parameter selection will presumably be null, so the first scriptlet in the page does nothing. Clicking on a snack button sets the selection parameter, and returns to the same page. But this time selection is non-null, so the addSelection() method of the bean is called. 128 The VendingBean class package vending ; import java.util.ArrayList; public class VendingBean { final String [] snacks = {"Chips", "Popcorn", "Peanuts", "Snickers bar", "Twix", "Pop Tarts", "Chocolate Donut"} ; public int getNumSnacks() { return snacks.length ; } public String getSnacks(int i) { return snacks [i] ; } ArrayList selections = new ArrayList() ; public int getNumSelections() { return selections.size() ; } public String getSelections(int i) { return (String) selections.get(i) ; } public void addSelection(String selection) { selections.add(selection) ; } } 129 Viewing the Selections After selecting a few snacks, click on the “Proceed to checkout” link. This takes us to the second JSP, checkout.jsp. This accesses the same Bean, and prints out the current selections it contains. Finally it terminates the current session, so the next visit to vendingmachine.jsp will start with a fresh session bean. 130 checkout.jsp <html><head></head><body> <h3>Your selections were:</h3> <jsp:useBean id="vendingBean" class="vending.VendingBean“ scope="session"/> <ul> <% for (int j = 0 ; j < vendingBean.getNumSelections() ; j++) { %> <li> <%= vendingBean.getSelections(j) %> </li> <% } %> </ul> <p>Enjoy!</p> <% session.invalidate() ; %> <p> <a href="vendingmachine.jsp">Back</a> </p> </body></html> 131 The Checkout Page If I click a few selections on the main page, then follow the link to the checkout, I may see something like: 132 A JSP Programming Style JSP deliberately supports multiple programming styles, but the style we have illustrated here is a reasonable one: • Capture non-trivial logic of the application (“business logic”) in one or more JavaBean classes. The interface of the bean class should be natural for the application logic—decoupled from presentation. Avoiding generating HTML fragments and minimize use of servlet support classes inside the bean classes. • Simple logic associated with presentation—e.g. loops or conditionals associated with generating HTML elements—is better handled in scriptlets. Or specialized tag libraries, but we haven’t had time to discuss tag libraries in detail. • It is possible to use <jsp:setProperty>, etc actions to manipulate the Java beans using tags alone, but it is often more natural to call Java methods on the beans directly, from scriptlets. 133 Web Application Directory Hierarchy Tomcat 5.0\ webapps\ grid04vending\ vendingmachine.jsp checkout.jsp WEB-INF\ web.xml classes\ vending\ VendingBean.class 134 Deployment Issues The folders for the vending machine application are illustrated on the previous slide. The web.xml file is probably optional here, because we have no servlets. • But it is useful, if only to give a “display-name” for the application. Bean classes, like servlet classes, normally go in the WEB-INF\classes\ folder. • We defined our bean class to belong to the package vending, so there is a folder vending\ nested inside classes\. 135 The Web Archive File It is convenient to bundle all the files associated with an application into a Web Archive, for easy deployment. • This can include ordinary, static Web content, servlet classes, JSP pages, bean classes, … Assuming the components of your application are organized in folders as shown above, cd to the grid04vending\ folder (the top-level folder of your app) and execute the command: jar cvf grid04vending.war * • This assumes you are using a command prompt, and you have J2SE or equivalent Java software installed. This should create an archive file called grid04vending.war. 136 Deploying Archive Files Once you have a Web archive, deployment in a new Tomcat server (or other servlet container) is very easy. You can manually deploy the application simply by copying the .war file to the Tomcat 5.0\webapps\ folder. When you restart the Web server, it notices the archive file, automatically expands it, and loads the application. Alternatively you can use the Tomcat Application Manager interface. 137 Tomcat Management Interface Starting from the home page of your Web server (e.g. http://localhost:8080) follow the link “Tomcat Management”. • You may have to modify account information in Tomcat 5.0\conf\tomcat-users.xml, first. You use this page to start/stop/reload running applications. To deploy a .war file in a running server, copy it to the webapps\ folder, then use this form (right): Alternatively you can upload a .war file through your browser using this form (below): 138