Servlets - PowerPoint PPT Presentation

1 / 79
About This Presentation
Title:

Servlets

Description:

... the service method can be invoked at one time to respond ... Does not support persistent information. Track clients individually. Cookies. Session tracking ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 80
Provided by: nic1153
Category:

less

Transcript and Presenter's Notes

Title: Servlets


1
Servlets
  • N.L. Hsueh
  • 2003/9

2
Outline
3
Introduction
  • Java networking capabilities
  • Socket-based and packet-based communications
  • Package java.net
  • Remote Method Invocation (RMI)
  • Package java.rmi
  • Servlets and Java Server Pages (JSP)
  • Request-response model
  • Packages javax.servlet, javax.servlet.http,
    javax.servlet.jsp, javax.servlet.tagext
  • Form the Web tier of J2EE

4
Conti.
  • Servlets
  • A Java program running in the context of a web
    server that can respond to many clients and
    communicate with other servers
  • Server-side (as opposed to Java applet)
  • Request/response mechanism
  • Alternative for CGI, NSAPI, ISAPI, etc
  • Support thin clients
  • Session-tracking capabilities

5
Servlets in Multi-Tier Systems
  • Servlet is in middle of three-tier system
  • Web page client, communicates using HTTP with
  • Web server, which can run Java servlet, which in
    turn communicates through JDBC with
  • Database Server (e.g. Oracle)
  • Servlet provide all the services of standard CGI
  • Servlet API is a standard extension to the JDK
    under javax
  • Package javax.servlet, Package javax.servlet.http

6
Servlets vs. CGI
Gateway Programs
HTTP request
Run CGI Script or CGI Program (Process)
CGI
HTTP response
Output
Web Server
7
Conti.
8
Conti.
  • Tomcat
  • Jakarta project
  • Official reference implementation of the JSP and
    servlet standards

9
Architecture
Model 1
10
Conti.
Model 2
11
Conti.
  • Benefits of Model 2
  • Using MVC architecture
  • Servlets do not deal with presentation logic at
    all but rather just process HTTP requests and
    control the flow of the application.
  • The model implementing the business logic sends
    objects or JavaBeans to the view, therefore
    encouraging a much cleaner separation of business
    and presentation logic and making application
    development and maintenance much easier

12
Servlet Container
  • Servlet container (servlet engine)
  • Server that executes a servlet
  • Web servers and application servers
  • Netscape iPlanet Application Server
  • Microsofts Internet Information Server (IIS)
  • Apache HTTP Server
  • BEAs WebLogic Application Server
  • IBMs WebSphere Application Server
  • World Wide Web Consortiums Jigsaw Web Server

13
Working Process
  • A client sends an HTTP request to the server or
    servlet container
  • The server or servlet container receives the
    request and directs it the be processed by the
    appropriate servlet
  • The servlet does its processing, which may
    include interacting with a database or other
    server-side components such as other servlets,
    JSP or enterprise java bean
  • The servlet returns its result to the client in
    the form of html, xhtml or xml document

14
UML Presentation
15
Servlet Life Cycle
  • void init (ServletConfig config) called once at
    start
  • ServletConfig getServletConfig() access to
    servlet information
  • String getServletInfo() useful for allowing use
    to get servlet information
  • void service (ServletRequest req, ServletResponse
    resp) called as often as needed to respond to
    requests
  • void destroy() called once for cleanup when
    stopped

16
Interface Servlet
  • Interface Servlet
  • All servlets must implement this interface
  • All methods of interface Servlet are invoked
    automatically
  • Default implementation of Servlet
  • Abstract class GenericServlet
  • Abstract class HttpServlet

17
Servlet.init()
  • public void init (ServletConfig config)
  • Be invoked when the servlet is first started.
  • Be called only once
  • ServletConfig object passed as the parameter has
    a method getServletContext ( )
  • returns a ServletContext with information about
    the servlet environment

18
Servlet Initialization Information
  • This information is passed to the servlet via the
    ServletConfig object parameter of the init
    method.
  • Each web server has its own information tags
    defined.
  • The getInitParameterNames ( ) returns an
    Enumeration of all the parameters available to
    the servlet on that server.
  • A particular parameter is obtained by
  • config.getInitParameter ( timezone)

19
Servlet Context Information
  • This information is available through the
    ServerConfig object.
  • save the ServerConfig parameter from the init
    method.
  • ServletContext c config.getServletContext ( )
  • The ServletContext object has methods
  • getAttribute
  • getMimeType
  • getRealPath
  • getServerInfo
  • getServlet (String name )
  • getServletNames
  • log (String message )

20
  • public void init(ServletConfig c) throws
    ServletException
  • dbUser c.getServletConfig().getInitParameter(
    "dbUser" )
  • driver c.getServletConfig().getInitParameter(
    "driver" )
  • dbUrl c.getServletConfig().getInitParameter(
    "dbUrl" )
  • Msg c.getServletConfig().getInitParameter(
    "exampleMsg" )

An example of ServletContext
21
Servlet.service()
  • public void service (ServletRequest req,
    ServletResponse res)
  • Each request message from the client results in
    invoking the service method.
  • Two ways the client can send information
  • parameter name/value pairs
  • streams - the servlet can invoke
    getInputStream(), which returns a
    ServletInputStream.
  • Servlet can invoke getOutputStream() to generate
    the response.
  • More than one instance of the service method can
    be invoked at one time to respond to multiple
    requests.

22
Servlet.destroy()
  • Called when the servlet in unloaded to clean up
    any open resources.
  • Server normally waits until all service calls are
    terminated to invoke destroy
  • The destroy method should make sure that
    resources are not being used.

23
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

24
  • HttpServletRequest interface
  • Web server creates an HttpServletRequest object
    and passes it to the servlets service method
  • HttpServletRequest object contains the request
    from the client
  • HttpServletResponse interface
  • Web server creates an HttpServletResponse object
    and passes it to the servlets service method
  • HttpServletResponse object contains the response
    to the client

25
UML Presentation
26
Handling HTTP get Requests
  • get request
  • Retrieve the content of a URL
  • Example WelcomeServlet
  • a servlet handles HTTP get requests

27
// WelcomeServlet.java // A simple servlet to
process get requests. import javax.servlet. imp
ort javax.servlet.http. import
java.io. public class WelcomeServlet extends
HttpServlet // process "get" requests
from clients protected void doGet(
HttpServletRequest request,
HttpServletResponse response ) throws
ServletException, IOException
response.setContentType( "text/html" )
PrintWriter out response.getWriter()
// send XHTML page to client // start
XHTML document out.println( "lt?xml version
\"1.0\"?gt" ) out.println( "lt!DOCTYPE
html PUBLIC \"-//W3C//DTD " "XHTML 1.0
Strict//EN\" \"http//www.w3.org"
"/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt" )
28
out.println( "lthtml xmlns
\"http//www.w3.org/1999/xhtml\"gt" )
// head section of document out.println(
"ltheadgt" ) out.println( "lttitlegtA Simple
Servlet Examplelt/titlegt" ) out.println(
"lt/headgt" ) // body section of
document out.println( "ltbodygt" )
out.println( "lth1gtWelcome to Servlets!lt/h1gt" )
out.println( "lt/bodygt" ) // end
XHTML document out.println( "lt/htmlgt" )
out.close() // close stream to complete the
page
29
(No Transcript)
30
Compiling Servlets
  • Software requirement
  • j2sdk1.4.1, j2sdkee1.3.1
  • JAVA_HOME
  • For example, c\j2sdk1.4.1
  • J2EE_HOME
  • For example, c\j2sdkee1.3.1
  • CLASSPATH
  • JAVA_HOME\lib\.jar J2EE_HOME\lib\.jar

31
Setting Up Tomcat Server
  • Download Tomcat (version 3.2.3)
  • Jakarta.apache.org/builds/jakarta-tomcat/release/v
    3.2.3/bin/
  • Define environment variables
  • JAVA_HOME
  • TOMCAT_HOME
  • Start the Tomcat server
  • tomcat start
  • Launch the Tomcat server
  • http//localhost8080/

32
Conti.
33
Deploying Web Applications
  • Web applications
  • JSPs, servlets and their supporting files
  • Deploying a Web application
  • Directory structure
  • Context root
  • Web application archive file (WAR file)
  • Deployment descriptor
  • web.xml

34
lt!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.2//EN"
"http//java.sun.com/j2ee/dtds/web-app_2_2.dtd"gt
ltweb-appgt lt!-- General description of your Web
application --gt ltdisplay-namegt First
Servlet Example Demo lt/display-namegt
ltdescriptiongt This is the Web application
in which we demonstrate our Servlet example
lt/descriptiongt lt!-- Servlet definitions --gt
ltservletgt ltservlet-namegtwelcomelt/servlet-na
megt ltdescriptiongt A servlet that
returns a "Welcome" screen through an HTTP get
request lt/descriptiongt
ltservlet-classgt neo.WelcomeServlet
lt/servlet-classgt lt/servletgt
web.xml
35
lt!-- Servlet mappings --gt ltservlet-mappinggt
ltservlet-namegtwelcomelt/servlet-namegt
lturl-patterngt/welcomelt/url-patterngt
lt/servlet-mappinggt lt!-- Neo --gt lt/web-appgt
web.xml (conti.)
36
Cont.
37
Handling HTTP get Requests Containing Data
  • Servlet WelcomeServlet2
  • Responds to a get request that contains data

38
WelcomeServlet2.java
39
(No Transcript)
40
9.5 Handling HTTP post Requests
  • HTTP post request
  • Post data from an HTML form to a server-side form
    handler
  • Browsers cache Web pages
  • Servlet WelcomeServlet3
  • Responds to a post request that contains data

41
WelcomeServlet3.java
42
(No Transcript)
43
9.6 Redirecting Requests to Other Resources
  • Servlet RedirectServlet
  • Redirects the request to a different resource

44
RedirectServlet.java
45
(No Transcript)
46
9.7 Session Tracking
  • Personalization
  • Privacy invasion
  • HTTP stateless protocol
  • Does not support persistent information
  • Track clients individually
  • Cookies
  • Session tracking
  • hidden type input
  • URL rewriting

47
9.7.1 Cookies
  • Stored on the users 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

48
Fig. 9.20 Storing user data on the client
computer with cookies.Lines 14-20Line
28Line 29 Line 30Line 32
  • 1 // Fig. 9.20 CookieServlet.java
  • 2 // Using cookies to store data on the client
    computer.
  • 3 package com.deitel.advjhtp1.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" )

49
Fig. 9.20 Storing user data on the client
computer with cookies.
  • 36 // send XHTML page to client
  • 37
  • 38 // start XHTML document
  • 39 out.println( "lt?xml version
    \"1.0\"?gt" )
  • 40
  • 41 out.println( "lt!DOCTYPE html PUBLIC
    \"-//W3C//DTD "
  • 42 "XHTML 1.0 Strict//EN\"
    \"http//www.w3.org"
  • 43 "/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt
    " )
  • 44
  • 45 out.println(
  • 46 "lthtml xmlns \"http//www.w3.org/1
    999/xhtml\"gt" )
  • 47
  • 48 // head section of document
  • 49 out.println( "ltheadgt" )
  • 50 out.println( "lttitlegtWelcome to
    Cookieslt/titlegt" )
  • 51 out.println( "lt/headgt" )
  • 52
  • 53 // body section of document
  • 54 out.println( "ltbodygt" )

50
Fig. 9.20 Storing user data on the client
computer with cookies.Line 77
  • 71 // read cookies from client and create
    XHTML document
  • 72 // containing recommended books
  • 73 protected void doGet( HttpServletRequest
    request,
  • 74 HttpServletResponse response )
  • 75 throws ServletException,
    IOException
  • 76
  • 77 Cookie cookies request.getCookies()
    // get cookies
  • 78
  • 79 response.setContentType( "text/html"
    )
  • 80 PrintWriter out response.getWriter()
  • 81
  • 82 // start XHTML document
  • 83 out.println( "lt?xml version
    \"1.0\"?gt" )
  • 84
  • 85 out.println( "lt!DOCTYPE html PUBLIC
    \"-//W3C//DTD "
  • 86 "XHTML 1.0 Strict//EN\"
    \"http//www.w3.org"
  • 87 "/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt
    " )
  • 88
  • 89 out.println(

51
Fig. 9.20 Storing user data on the client
computer with cookies.
  • 105 // get the name of each cookie
  • 106 for ( int i 0 i lt
    cookies.length i )
  • 107 out.println( cookies i
    .getName()
  • 108 " How to Program. ISBN "
  • 109 cookies i .getValue()
    "ltbr /gt" )
  • 110
  • 111 out.println( "lt/pgt" )
  • 112
  • 113 else // there were no cookies
  • 114 out.println( "lth1gtNo
    Recommendationslt/h1gt" )
  • 115 out.println( "ltpgtYou did not select
    a language.lt/pgt" )
  • 116
  • 117
  • 118 out.println( "lt/bodygt" )
  • 119
  • 120 // end XHTML document
  • 121 out.println( "lt/htmlgt" )
  • 122 out.close() // close stream
  • 123

52
Fig. 9.21 CookieSelectLanguage.html document for
selecting a programming language and posting the
data to the CookieServlet.
  • 1 lt?xml version "1.0"?gt
  • 2 lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Strict//EN"
  • 3 "http//www.w3.org/TR/xhtml1/DTD/xhtml1-st
    rict.dtd"gt
  • 4
  • 5 lt!-- Fig. 9.21 CookieSelectLanguage.html
    --gt
  • 6
  • 7 lthtml xmlns "http//www.w3.org/1999/xhtml"gt
  • 8 ltheadgt
  • 9 lttitlegtUsing Cookieslt/titlegt
  • 10 lt/headgt
  • 11
  • 12 ltbodygt
  • 13 ltform action "/advjhtp1/cookies" method
    "post"gt
  • 14
  • 15 ltpgtSelect a programming languagelt/pgt
  • 16 ltpgt
  • 17 ltinput type "radio" name
    "language"
  • 18 value "C" /gtC ltbr /gt
  • 19

53
Fig. 9.21 CookieSelectLanguage.html document for
selecting a programming language and posting the
data to the CookieServlet. Program output
54
Fig. 9.21 CookieSelectLanguage.html document for
selecting a programming language and posting the
data to the CookieServlet. Program output
55
9.7.1 Cookies (Cont.)
56
9.7.1 Cookies (Cont.)
Fig. 9.23 (Part 1 of 2) Important methods of
class Cookie.
57
9.7.1 Cookies (Cont.)
58
9.7.2 Session Tracking with HttpSession
  • Interface HttpSession
  • Supports session tracking
  • Servlet SessionServlet
  • Uses HttpSession objects
  • Handles both get and post requests

59
Fig. 9.24 Maintaining state information with
HttpSession objects.Line 28Line 32Line 35
  • 1 // Fig. 9.24 SessionServlet.java
  • 2 // Using HttpSession to maintain client
    state information.
  • 3 package com.deitel.advjhtp1.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" )

60
Fig. 9.24 Maintaining state information with
HttpSession objects.Line 64Line 67
  • 36
  • 37 response.setContentType( "text/html"
    )
  • 38 PrintWriter out response.getWriter()
  • 39
  • 40 // send XHTML page to client
  • 41
  • 42 // start XHTML document
  • 43 out.println( "lt?xml version
    \"1.0\"?gt" )
  • 44
  • 45 out.println( "lt!DOCTYPE html PUBLIC
    \"-//W3C//DTD "
  • 46 "XHTML 1.0 Strict//EN\"
    \"http//www.w3.org"
  • 47 "/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt
    " )
  • 48
  • 49 out.println(
  • 50 "lthtml xmlns \"http//www.w3.org/1
    999/xhtml\"gt" )
  • 51
  • 52 // head section of document
  • 53 out.println( "ltheadgt" )
  • 54 out.println( "lttitlegtWelcome to
    Sessionslt/titlegt" )

61
Fig. 9.24 Maintaining state information with
HttpSession objects.Line 71Line 74Line
77Line 100
  • 70 out.println( "The session was created
    at "
  • 71 new Date( session.getCreationTime()
    ) "ltbr /gt" )
  • 72
  • 73 out.println( "You last accessed the
    session at "
  • 74 new Date( session.getLastAccessedTim
    e() ) "ltbr /gt" )
  • 75
  • 76 out.println( "The maximum inactive
    interval is "
  • 77 session.getMaxInactiveInterval()
    " secondslt/pgt" )
  • 78
  • 79 out.println( "ltpgtlta href "
  • 80 "\"servlets/SessionSelectLanguage.ht
    ml\"gt"
  • 81 "Click here to choose another
    languagelt/agtlt/pgt" )
  • 82
  • 83 out.println( "ltpgtlta href
    \"sessions\"gt"
  • 84 "Click here to get book
    recommendationslt/agtlt/pgt" )
  • 85 out.println( "lt/bodygt" )
  • 86
  • 87 // end XHTML document
  • 88 out.println( "lt/htmlgt" )

62
Fig. 9.24 Maintaining state information with
HttpSession objects.Line 106
  • 105 if ( session ! null )
  • 106 valueNames session.getAttributeNam
    es()
  • 107 else
  • 108 valueNames null
  • 109
  • 110 PrintWriter out response.getWriter()
  • 111 response.setContentType( "text/html"
    )
  • 112
  • 113 // start XHTML document
  • 114 out.println( "lt?xml version
    \"1.0\"?gt" )
  • 115
  • 116 out.println( "lt!DOCTYPE html PUBLIC
    \"-//W3C//DTD "
  • 117 "XHTML 1.0 Strict//EN\"
    \"http//www.w3.org"
  • 118 "/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt
    " )
  • 119
  • 120 out.println(
  • 121 "lthtml xmlns \"http//www.w3.org/1
    999/xhtml\"gt" )
  • 122
  • 123 // head section of document

63
Fig. 9.24 Maintaining state information with
HttpSession objects.Line 141
  • 138 // get value for each name in
    valueNames
  • 139 while ( valueNames.hasMoreElements()
    )
  • 140 name valueNames.nextElement().t
    oString()
  • 141 value session.getAttribute(
    name ).toString()
  • 142
  • 143 out.println( name " How to
    Program. "
  • 144 "ISBN " value "ltbr /gt"
    )
  • 145
  • 146
  • 147 out.println( "lt/pgt" )
  • 148
  • 149 else
  • 150 out.println( "lth1gtNo
    Recommendationslt/h1gt" )
  • 151 out.println( "ltpgtYou did not select
    a language.lt/pgt" )
  • 152
  • 153
  • 154 out.println( "lt/bodygt" )
  • 155
  • 156 // end XHTML document

64
Fig. 9.25 SessionSelectLanguage.html document for
selecting a programming language and posting the
data to the SessionServlet.
  • 1 lt?xml version "1.0"?gt
  • 2 lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Strict//EN"
  • 3 "http//www.w3.org/TR/xhtml1/DTD/xhtml1-st
    rict.dtd"gt
  • 4
  • 5 lt!-- Fig. 9.25 SessionSelectLanguage.html
    --gt
  • 6
  • 7 lthtml xmlns "http//www.w3.org/1999/xhtml"gt
  • 8 ltheadgt
  • 9 lttitlegtUsing Sessionslt/titlegt
  • 10 lt/headgt
  • 11
  • 12 ltbodygt
  • 13 ltform action "/advjhtp1/sessions"
    method "post"gt
  • 14
  • 15 ltpgtSelect a programming languagelt/pgt
  • 16 ltpgt
  • 17 ltinput type "radio" name
    "language"
  • 18 value "C" /gtC ltbr /gt
  • 19

65
Fig. 9.25 SessionSelectLanguage.html document for
selecting a programming language and posting the
data to the SessionServlet.Program output
66
Fig. 9.25 SessionSelectLanguage.html document for
selecting a programming language and posting the
data to the SessionServlet. Program output
67
Fig. 9.25 SessionSelectLanguage.html document for
selecting a programming language and posting the
data to the SessionServlet. Program output
68
Fig. 9.25 SessionSelectLanguage.html document for
selecting a programming language and posting the
data to the SessionServlet. Program output
69
9.7.2 Session Tracking with HttpSession (Cont.)
70
9.8 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
  • Cloudscape database

71
Fig. 9.27 Multi-tier Web-based survey using
XHTML, servlets and JDBC.Lines 16-54Line
21Lines 22-23Lines 27-31
  • 1 // Fig. 9.27 SurveyServlet.java
  • 2 // A Web-based survey that uses JDBC from a
    servlet.
  • 3 package com.deitel.advjhtp1.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
  • 12 private Connection connection
  • 13 private PreparedStatement updateVotes,
    totalVotes, results
  • 14
  • 15 // set up database connection and prepare
    SQL statements
  • 16 public void init( ServletConfig config )
  • 17 throws ServletException
  • 18
  • 19 // attempt database connection and
    create PreparedStatements

72
Fig. 9.27 Multi-tier Web-based survey using
XHTML, servlets and JDBC.Lines 34-44
  • 33 // PreparedStatement to sum the
    votes
  • 34 totalVotes
  • 35 connection.prepareStatement(
  • 36 "SELECT sum( votes ) FROM
    surveyresults"
  • 37 )
  • 38
  • 39 // PreparedStatement to obtain
    surveyoption table's data
  • 40 results
  • 41 connection.prepareStatement(
  • 42 "SELECT surveyoption, votes,
    id "
  • 43 "FROM surveyresults ORDER BY
    id"
  • 44 )
  • 45
  • 46
  • 47 // for any exception throw an
    UnavailableException to
  • 48 // indicate that the servlet is not
    currently available
  • 49 catch ( Exception exception )
  • 50 exception.printStackTrace()
  • 51 throw new UnavailableException(excep
    tion.getMessage())

73
Fig. 9.27 Multi-tier Web-based survey using
XHTML, servlets and JDBC.Lines 80-81Lines
87-88Lines 91-93Lines 96-123
  • 66 // start XHTML document
  • 67 out.println( "lt?xml version
    \"1.0\"?gt" )
  • 68
  • 69 out.println( "lt!DOCTYPE html PUBLIC
    \"-//W3C//DTD "
  • 70 "XHTML 1.0 Strict//EN\"
    \"http//www.w3.org"
  • 71 "/TR/xhtml1/DTD/xhtml1-strict.dtd\"gt
    " )
  • 72
  • 73 out.println(
  • 74 "lthtml xmlns \"http//www.w3.org/1
    999/xhtml\"gt" )
  • 75
  • 76 // head section of document
  • 77 out.println( "ltheadgt" )
  • 78
  • 79 // read current survey response
  • 80 int value
  • 81 Integer.parseInt(
    request.getParameter( "animal" ) )
  • 82
  • 83 // attempt to process a vote and
    display current results
  • 84 try

74
Fig. 9.27 Multi-tier Web-based survey using
XHTML, servlets and JDBC.
  • 100 out.println( "ltbodygt" )
  • 101 out.println( "ltpgtThank you for
    participating." )
  • 102 out.println( "ltbr
    /gtResultslt/pgtltpregt" )
  • 103
  • 104 // process results
  • 105 int votes
  • 106
  • 107 while ( resultsRS.next() )
  • 108 out.print( resultsRS.getString(
    1 ) )
  • 109 out.print( " " )
  • 110 votes resultsRS.getInt( 2 )
  • 111 out.print( twoDigits.format(
  • 112 ( double ) votes / total
    100 ) )
  • 113 out.print( " responses " )
  • 114 out.println( votes )
  • 115
  • 116
  • 117 resultsRS.close()
  • 118

75
Fig. 9.27 Multi-tier Web-based survey using
XHTML, servlets and JDBC.Lines 140-154
  • 135
  • 136
  • 137 // end of doPost method
  • 138
  • 139 // close SQL statements and database when
    servlet terminates
  • 140 public void destroy()
  • 141
  • 142 // attempt to close statements and
    database connection
  • 143 try
  • 144 updateVotes.close()
  • 145 totalVotes.close()
  • 146 results.close()
  • 147 connection.close()
  • 148
  • 149
  • 150 // handle database exceptions by
    returning error to client
  • 151 catch( SQLException sqlException )
  • 152 sqlException.printStackTrace()
  • 153

76
Fig. 9.28 Survey.html document that allows users
to submit survey responses to SurveyServlet.
  • 1 lt?xml version "1.0"?gt
  • 2 lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Strict//EN"
  • 3 "http//www.w3.org/TR/xhtml1/DTD/xhtml1-st
    rict.dtd"gt
  • 4
  • 5 lt!-- Fig. 9.28 Survey.html --gt
  • 6
  • 7 lthtml xmlns "http//www.w3.org/1999/xhtml"gt
  • 8 ltheadgt
  • 9 lttitlegtSurveylt/titlegt
  • 10 lt/headgt
  • 11
  • 12 ltbodygt
  • 13 ltform method "post" action
    "/advjhtp1/animalsurvey"gt
  • 14
  • 15 ltpgtWhat is your favorite pet?lt/pgt
  • 16
  • 17 ltpgt
  • 18 ltinput type "radio" name "animal"
  • 19 value "1" /gtDogltbr /gt

77
Fig. 9.28 Survey.html document that allows users
to submit survey responses to SurveyServlet.
78
9.8 Multi-Tier Applications Using JDBC from a
Servlet (Cont.)
79
9.9 HttpUtils Class
Write a Comment
User Comments (0)
About PowerShow.com