Professional Documents
Culture Documents
Servlets (Autosaved)
Servlets (Autosaved)
Programming
• JavaScript
• Application server
Web applications.
Oracle WebLogic, IBM WebSphere
• Servlet container
servlets life cycle
part of an application server
(Tomcat , Jetty)
Responsibility
• Web servers static content
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. Cookie objects 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.
This method can create an HttpSession object (true argument) if one does not already
exist for the client. HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients.
Fig. 24.3 Some methods of interface HttpServletRequest.
HttpServletResponse
Interface
• Web server
– creates an HttpServletResponse object
– passes it to the servlet’s service method
24.2.4 HttpServletResponse Interface
(Cont.)
Method Description
void addCookie(
Cookie cookie )
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.
Fig. 24.4 Some methods of interface HttpServletResponse.
24.3 Handling HTTP get Requests
• get request
– Retrieve the content of a URL
• Example: WelcomeServlet
– a servlet handles HTTP get requests
1 // Fig. 24.5: WelcomeServlet.java
2 // A simple servlet to process get requests.
3
4 import javax.servlet.*;
5 import javax.servlet.http.*;
6 import java.io.*;
7
8 public class WelcomeServlet extends HttpServlet {
9
10 // process "get" requests from clients
11 protected void doGet( HttpServletRequest request,
12 HttpServletResponse response )
13 throws ServletException, IOException
14 {
15 response.setContentType( "text/html" );
16 PrintWriter out = response.getWriter();
17
18 // send XHTML page to client
19
20 // start XHTML document
21 out.println( "<?xml version = \"1.0\"?>" );
22
23 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
24 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
25 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
26
27 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
28
29 // head section of document
30 out.println( "<head>" );
31 out.println( "<title>A Simple Servlet Example</title>" );
32 out.println( "</head>" );
33
34 // body section of document
35 out.println( "<body>" );
36 out.println( "<h1>Welcome to Servlets!</h1>" );
37 out.println( "</body>" );
38
39 // end XHTML document
40 out.println( "</html>" );
41 out.close(); // close stream to complete the page
42 }
43 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
WelcomeServlet.
5 <!-- Fig. 24.6: WelcomeServlet.html --> html
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Handling an HTTP Get Request</title>
10 </head>
11
12 <body>
13 <form action = "/jhtp5/welcome1" method = "get">
14
15 <p><label>Click the button to invoke the servlet
16 <input type = "submit" value = "Get HTML Document" />
17 </label></p>
18
19 </form>
20 </body>
21 </html>
Program output
24.3.1 Setting Up the Apache Tomcat Server
Fig. 24.7 Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
24.3.2 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)
– Deployment descriptor
• web.xml
24.3.2 Deploying a Web Application (Cont.)
Directory Description
context root This is the root directory for the Web application. 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. The
examples of this chapter use jhtp5 as the context root.
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.
Fig. 24.8 Web application standard directories.
1 <!DOCTYPE web-app PUBLIC \
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
4
5 <web-app>
6
7 <!-- General description of your Web application -->
8 <display-name>
9 Java How to Program JSP
10 and Servlet Chapter 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 WelcomeServlet
28 </servlet-class>
29 </servlet>
30
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>
24.3.2 Deploying a Web Application (Cont.)
Program output
24.4 Handling HTTP get Requests Containing
Data (Cont.)
Descriptor element Value
servlet element
servlet-name welcome2
description Handling HTTP get requests with data.
servlet-class WelcomeServlet2
servlet-
mapping element
servlet-name welcome2
url-pattern /welcome2
Fig. 24.13 Deployment descriptor information for servlet
WelcomeServlet2.
24.5 Handling HTTP post Requests
Program output
24.5 Handling HTTP post Requests (Cont.)
Descriptor Value
element
servlet element
servlet-name welcome3
description Handling HTTP post requests with
data.
servlet-class WelcomeServlet3
servlet-
mapping element
servlet-name welcome3
url-pattern /welcome3
Fig. 24.16 Deployment descriptor information for servlet
WelcomeServlet3.
24.6 Redirecting Requests to Other Resources
• Servlet RedirectServlet
– Redirects the request to a different resource
1 // Fig. 24.17: RedirectServlet.java
2 // Redirecting a user to a different Web page.
3
4 import javax.servlet.*;
RedirectServlet
5 import javax.servlet.http.*;
redirecting
6 import java.io.*;
7
requests to
8 public class RedirectServlet extends HttpServlet { other
9 resources.
10 // process "get" request from client
11 protected void doGet( HttpServletRequest request, Line 15
12 HttpServletResponse response )
13 throws ServletException, IOException
Obtains theLines
page 19-23
14 {
15 String location = request.getParameter( "page" );
parameter from the request.
Line 20
16
17 if ( location != null )
18 Determine if the valueLine
is either
23
19 if ( location.equals( "deitel" ) ) “deitel” or “welcome1”
20 response.sendRedirect( "http://www.deitel.com" ); Lines 29-56
21 else Redirects the request to
22 if ( location.equals( "welcome1" ) ) www.deitel.com.
23 response.sendRedirect( "welcome1" );
24 Redirects the request to the
servlet WelcomeServlet.
25 // code that executes only if this servlet
26 // does not redirect the user to another page
27
Output a Web page indicating that an
28
invalid request wasRedirectServlet
response.setContentType( "text/html" );
29 PrintWriter out = response.getWriter();
made if method
redirecting
sendRedirect is not called.
30
requests to
31 // start XHTML document
other
32 out.println( "<?xml version = \"1.0\"?>" );
33
resources.
34 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
35 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + Lines 28-55
36 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
37
38 out.println(
39 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
40
41 // head section of document
42 out.println( "<head>" );
43 out.println( "<title>Invalid page</title>" );
44 out.println( "</head>" );
45
46 // body section of document
47 out.println( "<body>" );
48 out.println( "<h1>Invalid page requested</h1>" );
49 out.println( "<p><a href = " +
50 "\"servlets/RedirectServlet.html\">" );
51 out.println( "Click here to choose again</a></p>" );
52 out.println( "</body>" ); RedirectServlet
53
redirecting
54 // end XHTML document
requests to
55 out.println( "</html>" );
56 out.close(); // close stream to complete the page
other
57 } resources.
58 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 RedirectServlet
5 <!-- Fig. 24.18: RedirectServlet.html --> .html document
6 to demonstrate
7 <html xmlns = "http://www.w3.org/1999/xhtml"> redirecting
8 <head>
requests to
9 <title>Redirecting a Request to Another Site</title>
other
10 </head>
11
resources.
12 <body>
13 <p>Click a link to be redirected to the appropriate page</p> Lines 15-16
14 <p>
15 <a href = "/jhtp5/redirect?page=deitel"> Provide hyperlinks that allow
Lines 17-18
16 www.deitel.com</a><br /> the user to invoke the servlet
17 <a href = "/jhtp5/redirect?page=welcome1"> RedirectServlet.
18 Welcome servlet</a>
19 </p>
20 </body>
21 </html>n
RedirectServlet
.html document
to demonstrate
redirecting
requests to
other
resources.
Program output
24.6 Redirecting Requests to other Resources
(Cont.)
Descriptor Value
element
servlet
element
servlet- redirect
name
description Redirecting to static Web pages and other
servlets.
servlet- com.deitel.jhtp5.servlets.RedirectServlet
class
servlet-
mapping
element
servlet- redirect
name
url-pattern /redirect
Fig. 24.19 Deployment descriptor information for servlet
RedirectServlet.
State Management using Hidden Form
Here, uname is the hidden field name and Huda Almustafa is the
hidden field value
State Management using Hidden Form
Here, uname is the hidden field name and Huda Almustafa is the
hidden field value
State Management using Hidden Form
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletR
esponse response)
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Events and listeners
• Events are basically occurrence of something.
ServletRequestListener ServletRequestEvent
ServletRequestAttributeListener ServletContextEvent
ServletContextListener ServletRequestAttributeEvent
ServletContextAttributeListener ServletContextAttributeEvent
HttpSessionListener HttpSessionEvent
HttpSessionAttributeListener HttpSessionBindingEvent
HttpSessionBindingListener
HttpSessionActivationListener
ServletContextEvent and
ServletContextListener
•void contextInitialized(ServletContextEvent)
is invoked when application is deployed on the
server.
•void contextDestroyed(ServletContextEvent)
is invoked when application is undeployed from
the server.
1.In this example, we are creating table of the project. So we
don't need to create all the tables manually in the database.
import javax.servlet.*;
import java.sql.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
System.out.println(query);
}
}
Filters
1.import java.io.IOException;
2.import java.io.PrintWriter;
3.
4.import javax.servlet.*;
5.
6.public class MyFilter implements Filter{
7.
8.public void init(FilterConfig arg0) throws ServletException {}
9.
10.public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=resp.getWriter();
14. out.print("filter is invoked before");
15.
16. chain.doFilter(req, resp);//sends request to next resource
17.
18. out.print("filter is invoked after");
19. }
20. public void destroy() {}
21.}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
24.7 Multi-Tier Applications
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"admin");
Statement st=con.createStatement();
}
pw.println("</table>");
pw.close();
}
catch (Exception e){
e.printStackTrace();
} }}
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8.
9. <h1>Add New Employee</h1>
10. <form action="SaveServlet" method="post">
11. <table>
12. <tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
13. <tr><td>Password:</td><td><input type="password" name="password"/></td></tr>
14. <tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
15. <tr><td>Country:</td><td>
16. <select name="country" style="width:150px">
17. <option>India</option>
18. <option>USA</option>
19. <option>UK</option>
20. <option>Other</option>
21. </select>
22. </td></tr>
23. <tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>
24. </table>
25. </form>
26.
27. <br/>
28. <a href="ViewServlet">view employees</a>
29.
30. </body>
31. </html>
1. public class Emp {
2. private int id;
3. private String name,password,email,country;
4. public int getId() {
5. return id;
6. }
7. public void setId(int id) {
8. this.id = id;
9. }
10. public String getName() {
11. return name;
12. }
13. public void setName(String name) {
14. this.name = name;
15. }
16. public String getPassword() {
17. return password;
18. }
19. public void setPassword(String password) {
20. this.password = password;
21. }
22. public String getEmail() {
23. return email;
24. }
25. public void setEmail(String email) {
26. this.email = email;
27. }
28. public String getCountry() {
29. return country;
30. }
31. public void setCountry(String country) {
32. this.country = country;
33. }
34.
35. }
1. import java.util.*;
2. import java.sql.*;
3.
4. public class EmpDao {
5.
6. public static Connection getConnection(){
7. Connection con=null;
8. try{
9. Class.forName("oracle.jdbc.driver.OracleDriver");
10. con=DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","oracle");
11. }catch(Exception e){System.out.println(e);}
12. return con;
13. }
14.
1. public static int save(Emp e){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement(
6. "insert into user905(name,password,email,country) values (?,?,?,?)");
7. ps.setString(1,e.getName());
8. ps.setString(2,e.getPassword());
9. ps.setString(3,e.getEmail());
10. ps.setString(4,e.getCountry());
11.
12. status=ps.executeUpdate();
13.
14. con.close();
15. }catch(Exception ex){ex.printStackTrace();}
16.
17. return status;
18. }
1. public static int update(Emp e){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement(
6. "update user905 set name=?,password=?,email=?,country=? whe
re id=?");
7. ps.setString(1,e.getName());
8. ps.setString(2,e.getPassword());
9. ps.setString(3,e.getEmail());
10. ps.setString(4,e.getCountry());
11. ps.setInt(5,e.getId());
12.
13. status=ps.executeUpdate();
14.
15. con.close();
16. }catch(Exception ex){ex.printStackTrace();}
17.
18. return status;
19. }
1. public static int delete(int id){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement("delete from
user905 where id=?");
6. ps.setInt(1,id);
7. status=ps.executeUpdate();
8.
9. con.close();
10. }catch(Exception e){e.printStackTrace();}
11.
12. return status;
13. }
1. public static Emp getEmployeeById(int id){
2. Emp e=new Emp();
3.
4. try{
5. Connection con=EmpDao.getConnection();
6. PreparedStatement ps=con.prepareStatement("select * from user905 where id=?"
);
7. ps.setInt(1,id);
8. ResultSet rs=ps.executeQuery();
9. if(rs.next()){
10. e.setId(rs.getInt(1));
11. e.setName(rs.getString(2));
12. e.setPassword(rs.getString(3));
13. e.setEmail(rs.getString(4));
14. e.setCountry(rs.getString(5));
15. }
16. con.close();
17. }catch(Exception ex){ex.printStackTrace();}
18.
19. return e;
20. }
1. public static List<Emp> getAllEmployees(){
2. List<Emp> list=new ArrayList<Emp>();
3.
4. try{
5. Connection con=EmpDao.getConnection();
6. PreparedStatement ps=con.prepareStatement("select * from user905");
7. ResultSet rs=ps.executeQuery();
8. while(rs.next()){
9. Emp e=new Emp();
10. e.setId(rs.getInt(1));
11. e.setName(rs.getString(2));
12. e.setPassword(rs.getString(3));
13. e.setEmail(rs.getString(4));
14. e.setCountry(rs.getString(5));
15. list.add(e);
16. }
17. con.close();
18. }catch(Exception e){e.printStackTrace();}
19.
20. return list;
21. }
22. }
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.annotation.WebServlet;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. @WebServlet("/SaveServlet")
10. public class SaveServlet extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse respons
e)
12. throws ServletException, IOException {
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15.
16. String name=request.getParameter("name");
17. String password=request.getParameter("password");
18. String email=request.getParameter("email");
19. String country=request.getParameter("country");
20.
1. Emp e=new Emp();
2. e.setName(name);
3. e.setPassword(password);
4. e.setEmail(email);
5. e.setCountry(country);
6.
7. int status=EmpDao.save(e);
8. if(status>0){
9. out.print("<p>Record saved successfully!</p>");
10. request.getRequestDispatcher("index.html").include(request, response);
11. }else{
12. out.println("Sorry! unable to save record");
13. }
14.
15. out.close();
16. }
17. }
1 // Fig. 24.20: SurveyServlet.java
2 // A Web-based survey that uses JDBC from a servlet.
3 package com.deitel.jhtp5.servlets;
4 SurveyServlet.j
5 import java.io.*; ava
6 import java.text.*;
Multi-tier Web-
7 import java.sql.*;
based survey
8 import javax.servlet.*;
9 import javax.servlet.http.*;
using XHTML,
10 servlets and
11 public class SurveyServlet extends HttpServlet { JDBC.
12 private Connection connection;
Servlets are initialized by
13 private Statement statement; Lines 16-38
14
overriding method init.
15 // set up database connection and create SQL statement Lines 20-21
16 public void init( ServletConfig config ) throws ServletException
17 {
Line 23
18 // attempt database connection and create Statements
19 try {
Specify database
Lineslocation
24-25
20 System.setProperty( "db2j.system.home",
21 config.getInitParameter( "databaseLocation" ) );
22 Loads
Linesthe27-31
23 Class.forName( config.getInitParameter( "databaseDriver" ) ); database driver.
24 connection = DriverManager.getConnection(
25 config.getInitParameter( "databaseName" ) ); Attempt to open a connection to
the animalsurvey database.
26
27 // create Statement to query database Create Statement to
28 statement = connection.createStatement();
query database.
29 } SurveyServlet.j
30 ava
31 // for any exception throw an UnavailableException to Multi-tier Web-
32 // indicate that the servlet is not currently available based survey
33 catch ( Exception exception ) {
using XHTML,
34 exception.printStackTrace();
servlets and
35 throw new UnavailableException(exception.getMessage());
36 }
JDBC.
37
38 } // end of init method Line 28
39
40 // process survey response
41 protected void doPost( HttpServletRequest request,
42 HttpServletResponse response )
43 throws ServletException, IOException
44 {
45 // set up response to client
46 response.setContentType( "text/html" );
47 PrintWriter out = response.getWriter();
48 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
49
50 // start XHTML document
51 out.println( "<?xml version = \"1.0\"?>" );
52
53 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + SurveyServlet.j
54 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
ava
55 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
Multi-tier Web-
56
57 out.println(
based survey
58 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); using XHTML,
59 servlets and
60 // head section of document JDBC.
61 out.println( "<head>" );
62 Lines 64-65
63 // read current survey response
64 int value = Obtain theLines
survey 72-73
65 Integer.parseInt( request.getParameter( "animal" ) ); response
66 String query;
Line 74
67
68 // attempt to process a vote and display current results
69 try {
70
71 // update total for current surevy response
72 query = "UPDATE surveyresults SET votes = votes + 1 " + Create query to update total
73 "WHERE id = " + value; for current survey response
74 statement.executeUpdate( query );
75 Execute query to update total
for current survey response
// get total of all survey responses Create query to get total of all
query = "SELECT sum( votes ) FROM surveyresults"; survey responses
ResultSet totalRS = statement.executeQuery( query );
Execute query to get total of
totalRS.next(); SurveyServlet.j
all survey responses
int total = totalRS.getInt( 1 ); ava
Multi-tier Web-
// get results Create query to
based get
survey
query = "SELECT surveyoption, votes, id FROM surveyresults " + survey results XHTML,
using
"ORDER BY id";
servlets and
ResultSet resultsRS = statement.executeQuery( query ); Execute query to get
JDBC.
out.println( "<title>Thank you!</title>" ); survey results
out.println( "</head>" );
Line 77
out.println( "<body>" );
out.println( "<p>Thank you for participating." ); Line 78
out.println( "<br />Results:</p><pre>" );
Lines 83-84
// process results
int votes;
Line 85
while ( resultsRS.next() ) {
out.print( resultsRS.getString( 1 ) );
out.print( ": " );
votes = resultsRS.getInt( 2 );
out.print( twoDigits.format(
( double ) votes / total * 100 ) );
out.print( "% responses: " );
out.println( votes );
}
105
106 resultsRS.close();
107
108 out.print( "Total responses: " ); SurveyServlet.j
109 out.print( total ); ava
110 Multi-tier Web-
111 // end XHTML document based survey
112 out.println( "</pre></body></html>" ); using XHTML,
113 out.close();
servlets and
114
JDBC.
115 } // end try
116
117 // if database exception occurs, return error page
118 catch ( SQLException sqlException ) {
119 sqlException.printStackTrace();
120 out.println( "<title>Error</title>" );
121 out.println( "</head>" );
122 out.println( "<body><p>Database error occurred. " );
123 out.println( "Try again later.</p></body></html>" );
124 out.close();
125 }
126
127 } // end of doPost method
128
Method destroy closes
129 // close SQL statements and database when servlet terminates
130 public void destroy()
Statement and
131 { database connection.
132 // attempt to close statements and database connection SurveyServlet.j
133 try { ava
134 statement.close(); Multi-tier Web-
135 connection.close(); based survey
136 } using XHTML,
137 servlets and
138 // handle database exceptions by returning error to client
JDBC.
139 catch ( SQLException sqlException ) {
140 sqlException.printStackTrace();
141 }
Lines 130-136
142 }
143
144 } // end class SurveyServlet
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Survey.html
5 <!-- Fig. 24.21: Survey.html --> document that
6
allows users to
7 <html xmlns = "http://www.w3.org/1999/xhtml">
submit survey
8 <head>
9 <title>Survey</title>
responses to
10 </head> SurveyServlet.
11
12 <body>
13 <form method = "post" action = "/jhtp5/animalsurvey">
14
15 <p>What is your favorite pet?</p>
16
17 <p>
18 <input type = "radio" name = "animal"
19 value = "1" />Dog<br />
20 <input type = "radio" name = "animal" Survey.html
21 value = "2" />Cat<br /> document that
22 <input type = "radio" name = "animal"
allows users to
23 value = "3" />Bird<br />
submit survey
24 <input type = "radio" name = "animal"
25 value = "4" />Snake<br />
responses to
26 <input type = "radio" name = "animal" SurveyServlet.
27 value = "5" checked = "checked" />None
28 </p>
29
30 <p><input type = "submit" value = "Submit" /></p>
31
32 </form>
33 </body>
34 </html>
Survey.html
document that
allows users to
submit survey
responses to
SurveyServlet.
24.7 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.deitel.jhtp5.servlets.SurveyServlet
init-param
param-name databaseLocation
param-value C:/CloudScape_5.0
init-param
param-name databaseDriver
param-value com.ibm.db2j.jdbc.DB2jDriver
init-param
param-name databaseName
param-value jdbc:db2j:animalsurvey
servlet-mapping element
servlet-name animalsurvey
url-pattern /animalsurvey
Fig. 24.22 Deployment descriptor information for servlet SurveyServlet.