Java Stream 1 11.1 Introduction 11.2 Servlet Overview and Architecture 11.2.1 Interface Servlet and the Servlet Life Cycle 11.2.2 HttpServlet Class 11.2.3 HttpServletRequest Interface 11.2.4 HttpServletResponse Interface 11.3 Handling HTTP get Requests 11.3.1 Setting Up the Apache Tomcat Server 11.3.2 Deploying a Web Application 11.4 Handling HTTP get Requests Containing Data 11.5 Handling HTTP post Requests 11.6 Redirecting Requests to Other Resources 11.7 Session Tracking 11.7.1 Cookies 11.7.2 Session Tracking with HttpSession 11.8 Multi-Tier Applications: Using JDBC from a Servlet 11.9 Servlet Context 11.10 Servlet filter 11.11 Web application listener Unit 09 - Servlet Programming
Unit 09 - Servlet Programming. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Java Stream
1
11.1 Introduction11.2 Servlet Overview and Architecture11.2.1 Interface Servlet and the Servlet Life Cycle11.2.2 HttpServlet Class11.2.3 HttpServletRequest Interface11.2.4 HttpServletResponse Interface11.3 Handling HTTP get Requests11.3.1 Setting Up the Apache Tomcat Server11.3.2 Deploying a Web Application11.4 Handling HTTP get Requests Containing Data11.5 Handling HTTP post Requests11.6 Redirecting Requests to Other Resources11.7 Session Tracking11.7.1 Cookies11.7.2 Session Tracking with HttpSession11.8 Multi-Tier Applications: Using JDBC from a Servlet11.9 Servlet Context11.10 Servlet filter11.11 Web application listener
Unit 09 - Servlet Programming
Java Stream
2
Introduction• Java networking capabilities
– Socket-based and packet-based communications• Package java.net
• Servlets are modules of Java code that run in a server application to answer client requests.
Java Stream
3
Servlet Overview and Architecture
• Typical uses for Servlets include:– Processing and/or storing data submitted by an HTML form.
– Providing dynamic content, e.g. returning the results of a database query to the client.
– Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer
• Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that answer HTTP requests).
• Servlet container (servlet engine)– Server that executes a servlet
Java Stream
4
Interface Servlet and the Servlet Life Cycle
• Interface Servlet– All servlets must implement this interface
– All methods of interface Servlet are invoked automatically
• Servlet life cycle– Servlet container invokes the servlet’s init method
– Servlet’s service method handles requests
– Servlet’s destroy method releases servlet resources when the servlet container terminates the servlet
Java Stream
5
Interface Servlet and the Servlet Life Cycle (Cont.)
This method is automatically called once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).
String getServletInfo()
This method is defined by a servlet programmer to return a String containing servlet information such as the servlet’s author and version.
The servlet container calls this method to respond to a client request to the servlet.
void destroy() This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
Methods of interface Servlet (package javax.servlet).
Java Stream
6
HttpServlet Class
• Overrides method service• Two most common HTTP request types
– get requests– post requests
• Method doGet responds to get requests• Method doPost responds to post requests• HttpServletRequest and HttpServletResponse objects
Java Stream
7
• Web server – creates an HttpServletRequest object
– passes it to the servlet’s service method
• HttpServletRequest object contains the request from the client
HttpServletRequest Interface
Java Stream
8
HttpServletRequest Interface (Cont.)
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name.
Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues( String name )
For a parameter with multiple values, this method returns an array of Strings containing the values for a specified servlet parameter.
Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server. Cookies can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )
Returns an HttpSession object associated with the client’s current browsing session. An HttpSession object can be created by this method (true argument) if an HttpSession object does not already exist for the client. HttpSession objects can be used in similar ways to Cookies for uniquely identifying clients.
Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client.
ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client.
void setContentType( String type )
Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page.
Some methods of interface HttpServletResponse.
HttpServletResponse object contains the request from the client
Java Stream
10
Handling HTTP GET Requests
• GET request– Retrieve the content of a URL
• Example: WelcomeServlet – a servlet handles HTTP GET requests
Outline
Java Stream
11
WelcomeServlet that responds to a simple HTTP get request.
Lines 5-6
Line 9
Lines 12-44
Line 16
Line 17
Lines 22-42
1 // WelcomeServlet.java
2 // A simple servlet to process get requests.
3 package com.alliant.test.servlets;
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class WelcomeServlet extends HttpServlet {
• Start the Tomcat server– CATALINA_HOME\bin\startup.bat
• Launch the Tomcat server– http://localhost:8080/
• Shutdown the Tomcat server– CATALINA_HOME\bin\shutdown.bat
Java Stream
15
Setting Up the Apache Tomcat Server (Cont.).
Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
Java Stream
16
Deploying a Web Application
• Web applications– JSPs, servlets and their supporting files
• Deploying a Web application– Directory structure
• Context root
– Web application archive file (WAR file) OR Web application folder
– Deployment descriptor• web.xml
Java Stream
17
Deploying a Web Application (Cont.)
Directory Description context root This is the root directory for the Web application. The name of
this directory is chosen by the Web application developer. All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory.
WEB-INF This directory contains the Web application deployment descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application.
Web application standard directories.
Outline
Java Stream
18
Deployment descriptor (web.xml) for the advjhtp1 Web application.
Lines 5-37
Lines 8-11
Lines 13-16
Lines 19-29
Line 20
Lines 22-24
Lines 26-28
1 <!DOCTYPE web-app PUBLIC
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
7 <!-- General description of your Web application -->
8 <display-name>
9 Sample
10 Servlet Examples
11 </display-name>
12
13 <description>
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
16 </description>
17
18 <!-- Servlet definitions -->
19 <servlet>
20 <servlet-name>welcome1</servlet-name>
21
22 <description>
23 A simple servlet that handles an HTTP get request.
24 </description>
25
26 <servlet-class>
27 com.alliant.test.servlets.WelcomeServlet
28 </servlet-class>
29 </servlet>
30
Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet.
Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed.
Element description specifies a description of the Web application that might be displayed to the administrator of the server.
Element servlet describes a servlet.Element servlet-name is the name for the servlet.
Element description specifies a description for this particular servlet.
Element servlet-class specifies compiled servlet’s fully qualified class name.
Outline
Java Stream
19
Deployment descriptor (web.xml) for the advjhtp1 Web application.
Lines 32-35
31 <!-- Servlet mappings -->
32 <servlet-mapping>
33 <servlet-name>welcome1</servlet-name>
34 <url-pattern>/welcome1</url-pattern>
35 </servlet-mapping>
36
37 </web-app>
Element servlet-mapping specifies servlet-name and url-pattern elements.
Java Stream
20
Deploying a Web Application (Cont.)
• Invoke WelcomeServlet example– /test/welcome1
• /test specifies the context root• /welcome1 specifies the URL pattern
• URL pattern formats– Exact match
• /test/welcome1
– Path mappings• /test/example/*
– Extension mappings• *.jsp
– Default servlet• /test/example/
Java Stream
21
Deploying a Web Application (Cont.)
WelcomeServlet Web application directory and file structure test servlets WelcomeServlet.html WEB-INF web.xml classes com alliant test servlets WelcomeServlet.class Web application directory and file structure for WelcomeServlet.
Java Stream
22
Handling HTTP GET Requests Containing Data
• Servlet WelcomeServlet2– Responds to a get request that contains data
Outline
Java Stream
23
WelcomeServlet2 responds to a get request that contains data.
Line 16
1 // WelcomeServlet2.java
2 // Processing HTTP get requests containing data.
3 package com.alliant.test.servlets;
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class WelcomeServlet2 extends HttpServlet {
16 Type your first name and press the Submit button
17 <br /><input type = "text" name = "firstname" />
18 <input type = "submit" value = "Submit" />
19 </label></p>
20
21 </form>
22 </body>
23 </html>
Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3.
Outline
Java Stream
32
HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml.
Program output
Java Stream
33
Handling HTTP post Requests (Cont.)
Descriptor element Value servlet element
servlet-name welcome3 description Handling HTTP post requests with data. servlet-class com.deitel.test.servlets.WelcomeServlet3 servlet-mapping element
servlet-name welcome3 url-pattern /welcome3 Deployment descriptor information for servlet WelcomeServlet3.
Java Stream
34
Redirecting Requests to Other Resources
• Servlet RedirectServlet– Redirects the request to a different resource
Outline
Java Stream
35
Redirecting requests to other resources.
Line 16
Lines 20-24
Line 21
Line 24
Lines 29-56
1 // RedirectServlet.java
2 // Redirecting a user to a different Web page.
3 package com.deitel.advjhtp1.servlets;
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class RedirectServlet extends HttpServlet {
– Session tracking– hidden type input– URL rewriting
Java Stream
40
Cookies
• Stored on the user’s computer for retrieval later• Text-based data sent by servlets• Maximum age of a cookie• Deleted automatically when they expire• Servlet CookieServlet
– Handles both get and post requests
Outline
Java Stream
41
Storing user data on the client computer with cookies.
Lines 14-20
Line 28
Line 29
Line 30
Line 32
1 // CookieServlet.java
2 // Using cookies to store data on the client computer.
3 package com.alliant.test.servlets;
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9
10 public class CookieServlet extends HttpServlet {
11 private final Map books = new HashMap();
12
13 // initialize Map books
14 public void init()
15 {
16 books.put( "C", "0130895725" );
17 books.put( "C++", "0130895717" );
18 books.put( "Java", "0130125075" );
19 books.put( "VB6", "0134569555" );
20 }
21
22 // receive language selection and send cookie containing
25 value = "Java" checked = "checked" />Java<br />
26
27 <input type = "radio" name = "language"
28 value = "VB6" />VB 6
29 </p>
30
31 <p><input type = "submit" value = "Submit" /></p>
32
33 </form>
34 </body>
35 </html>
Outline
Java Stream
46
CookieSelectLanguage.html document for selecting a programming language and posting the data to the CookieServlet. Program output
Outline
Java Stream
47
CookieSelectLanguage.html document for selecting a programming language and posting the data to the CookieServlet.
Program output
Java Stream
48
Cookies (Cont.)
Descriptor element Value servlet element
servlet-name cookies description Using cookies to maintain state information. servlet-class com.deitel.advjhtp1.servlets.CookieServlet servlet-mapping element
servlet-name cookies url-pattern /cookies Deployment descriptor information for servlet CookieServlet.
Java Stream
49
Cookies (Cont.)
Method Description getComment() Returns a String describing the purpose of the cookie
(null if no comment has been set with setComment). getDomain() Returns a String containing the cookie’s domain. This
determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client.
getMaxAge() Returns an int representing the maximum age of the cookie in seconds.
getName() Returns a String containing the name of the cookie as set by the constructor.
getPath() Returns a String containing the URL prefix for the cookie. Cookies can be “targeted” to specific URLs that include directories on the Web server. By default, a cookie is returned to services operating in the same directory as the service that sent the cookie or a subdirectory of that directory.
getSecure() Returns a boolean value indicating if the cookie should be transmitted using a secure protocol (true).
getValue() Returns a String containing the value of the cookie as set with setValue or the constructor.
getVersion() Returns an int containing the version of the cookie protocol used to create the cookie. A value of 0 (the default) indicates the original cookie protocol as defined by Netscape. A value of 1 indicates the current version, which is based on Request for Comments (RFC) 2109.
(Part 1 of 2) Important methods of class Cookie.
Java Stream
50
Cookies (Cont.)
setComment( String )
The comment describing the purpose of the cookie that is presented by the browser to the user. (Some browsers allow the user to accept cookies on a per-cookie basis.)
setDomain( String ) This determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client. The domain is specified in the form ".alliant.com", indicating that all servers ending with .alliant.com can receive this cookie.
setMaxAge( int ) Sets the maximum age of the cookie in seconds. setPath( String ) Sets the “target” URL prefix indicating the directories on
the server that lead to the services that can receive this cookie.
setSecure( boolean )
A true value indicates that the cookie should only be sent using a secure protocol.
setValue( String ) Sets the value of a cookie. setVersion( int ) Sets the cookie protocol for this cookie. (Part 2 of 2) Important methods of class Cookie.
Java Stream
51
Session How Do We Need HTTP State?
• Web applications need to track the users across a series of requests:– Online shopping (e.g. Order books)
– Financial portfolio manager
– Movie listings
• HTTP does not support directly• Need a mechanism to maintain state about a series
of requests from the same user ( or originating from the same browser) over some period of time
Java Stream
52
Session Tracking Overview
• The servlet API has a built-in support for session tracking
• Session objects live on the server– Each user has associated an HttpSession object—one user/session
– HttpSession object operates like a hashtable
Java Stream
53
Session Tracking with HttpSession
• To get a user's existing or new session object:– HttpSession session = request.getSession(true);
– "true" means the server should create a new session object if necessary
• To store or retrieve an object in the session:– Stores values: setAttribute("cartItem", cart);
– Retrieves values: getAttribute("cartItem");
Outline
Java Stream
54
Maintaining state information with HttpSession objects.
Line 28
Line 32
Line 35
1 // SessionServlet.java
2 // Using HttpSession to maintain client state information.
3 package com.deitel.test.servlets;
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9
10 public class SessionServlet extends HttpServlet {
11 private final Map books = new HashMap();
12
13 // initialize Map books
14 public void init()
15 {
16 books.put( "C", "0130895725" );
17 books.put( "C++", "0130895717" );
18 books.put( "Java", "0130125075" );
19 books.put( "VB6", "0134569555" );
20 }
21
22 // receive language selection and create HttpSession object
Obtains the time at which the session was created with method getCreationTime.
Obtains the time at which the session was last accessed with method getLastAccessedTime.
Uses method getMaxInactiveInterval to obtain the maximum amount of time that an HttpSession object can be inactive before the servlet container discards it.
Obtains the HttpSession object for the client with method getSession.
Outline
Java Stream
57
Maintaining state information with HttpSession objects.
Line 106
105 if ( session != null )
106 valueNames = session.getAttributeNames();
107 else
108 valueNames = null;
109
110 PrintWriter out = response.getWriter();
111 response.setContentType( "text/html" );
112
113 // start XHTML document
114 out.println( "<?xml version = \"1.0\"?>" );
115
116 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
25 value = "Java" checked = "checked" />Java<br />
26
27 <input type = "radio" name = "language"
28 value = "VB6" />VB 6
29 </p>
30
31 <p><input type = "submit" value = "Submit" /></p>
32
33 </form>
34 </body>
35 </html>
Outline
Java Stream
60
SessionSelectLanguage.html document for selecting a programming language and posting the data to the SessionServlet.
Program output
Outline
Java Stream
61
SessionSelectLanguage.html document for selecting a programming language and posting the data to the SessionServlet.
Program output
Outline
Java Stream
62
SessionSelectLanguage.html document for selecting a programming language and posting the data to the SessionServlet.
Program output
Outline
Java Stream
63
SessionSelectLanguage.html document for selecting a programming language and posting the data to the SessionServlet.
Program output
Java Stream
64
Session Tracking with HttpSession (Cont.)
Descriptor element Value servlet element
servlet-name sessions description Using sessions to maintain state information. servlet-class com.alliant.test.servlets.SessionServlet servlet-mapping element
servlet-name sessions url-pattern /sessions Deployment descriptor information for servlet WelcomeServlet2.
Java Stream
65
Multi-Tier Applications: Using JDBC from a Servlet
• Three-tier distributed applications– User interface
– Business logic
– Database access
• Web servers often represent the middle tier• Three-tier distributed application example
– SurveyServlet
– Survey.html
– MySQL database
Outline
Java Stream
66
Multi-tier Web-based survey using XHTML, servlets and JDBC.
Lines 16-54
Line 21
Lines 22-23
Lines 27-31
1 // SurveyServlet.java
2 // A Web-based survey that uses JDBC from a servlet.
3 package com.alliant.test.servlets;
4
5 import java.io.*;
6 import java.text.*;
7 import java.sql.*;
8 import javax.servlet.*;
9 import javax.servlet.http.*;
10
11 public class SurveyServlet extends HttpServlet {
30 <p><input type = "submit" value = "Submit" /></p>
31
32 </form>
33 </body>
34 </html>
Outline
Java Stream
72
Survey.html document that allows users to submit survey responses to SurveyServlet.
Java Stream
73
Multi-Tier Applications: Using JDBC from a Servlet (Cont.)
Descriptor element Value servlet element
servlet-name animalsurvey description Connecting to a database from a servlet. servlet-class com.alliant.test.servlets.SurveyServlet servlet-mapping element
servlet-name animalsurvey url-pattern /animalsurvey Deployment descriptor information for servlet SurveyServlet.
Java Stream
74
Servlet Context
• Defined by an object of ServletContext type.• Defines a servlet’s view of the web application
within which the servlet is running. • Allows a servlet to access resources available to it.• Using such an object, a servlet can log events,
obtain URL references to resources, and set and store attributes that other servlets in the context can use.
Java Stream
75
Servlet Context - Sample
• We can change the init() method of the SurveyServlet as below:
• Then we need to amend the web.xml file to specify the initial context parameters:
Java Stream
76
Sending Multimedia Content
• People want to return different MIME types • The most common use of a different MIME type
is for returning an image graphic generated by a servlet
• The example next slide is an example of a servlet that generates and returns a GIF image. The graphic says “Hello World!”
Outline
Java Stream
77
HelloWorldGraphics that responds to with a gif graphic
1 // HelloWorldGraphics .java2 // A simple servlet to generate an on the fly image.3 package com.alliant.test.servlets;4 5 import javax.servlet.*;6 import javax.servlet.http.*;7 import java.io.*;8 import Acme.JPM.Encoders.GifEncoder;9 public class HelloWorldGraphics extends HttpServlet { 10 11 public void doGet(HttpServletRequest req, HttpServletResponse res)12 throws ServletException, IOException {13 ServletOutputStream out = res.getOutputStream(); // binary output!14 15 Frame frame = null;12 Graphics g = null;13 try {14 // Create an unshown frame15 frame = new Frame();16 frame.addNotify();17 // Get a graphics region, using the Frame18 Image image = frame.createImage(400, 60);19 g = image.getGraphics();20 // Draw "Hello World!" to the off-screen graphics context21 g.setFont(new Font("Serif", Font.ITALIC, 48));22 g.drawString("Hello World!", 10, 50);23 // Encode the off-screen image into a GIF and send it to the client24 res.setContentType("image/gif");25 GifEncoder encoder = new GifEncoder(image, out);26 encoder.encode();27 }28 finally {29 // Clean up resources30 if (g != null) g.dispose();31 if (frame != null) frame.removeNotify();• }• }• }
Java Stream
78
Servlet Filter
• New component framework• Dynamically intercepting and modifying requests
and responses• Apply filters to web components or pages• Allows range of activities:
– Marking access, blocking access
– Content transformations
• Works on Tomcat4.0 and above• Examples of servlet filters can be found on: