LTW Session2. Servlets
LTW Session2. Servlets
LTW Session2. Servlets
Slide 1
Objectives
Applied
• Code and test servlets that require any of the features presented in
this chapter.
• Use the web.xml file for an application to map a servlet to a URL
pattern.
• Write debugging data for a servlet to either the console or a log
file.
Slide 2
Objectives (cont.)
Knowledge
• In general terms, describe servlets and their use of request and
response objects.
• Describe servlet mapping.
• Describe the use of the init, doGet, doPost, and destroy methods in
a servlet.
• Describe the use of debugging data that’s written to the console or
a log file.
Slide 3
The HTML page for an Email List application
Slide 4
The servlet page for an Email List application
Slide 5
The code for the HTML page
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Murach's Java Servlets and JSP</title>
</head>
<body>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below. <br>
Then, click on the Submit button.</p>
Slide 6
The code for the HTML page (continued)
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr>
<td></td>
<td><br>
<input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Slide 7
The code for the HTML page that calls the Servlet
• The Action and Method attributes for the Form tag set up a
request for a Servlet that will be executed when the user clicks on
the Submit button.
• The three text boxes represent parameters that will be passed to
the Servlet when the user clicks the Submit button.
Slide 8
The code for the AddToEmailListServlet class
package email;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Slide 9
Code for the AddToEmailListServlet class (cont.)
// send response to browser
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(
"<!doctype html public \"-//W3C//DTD HTML 4.0 "
+ " Transitional//EN\">\n"
+ "<html>\n"
+ "<head>\n"
+ " <title>Murach's Java Servlets and JSP</title>\n"
+ "</head>\n"
+ "<body>\n"
+ "<h1>Thanks for joining our email list</h1>\n"
+ "<p>Here is the information that you entered:</p>\n"
+ " <table cellspacing=\"5\" cellpadding=\"5\" "
+ " border=\"1\">\n"
+ " <tr><td align=\"right\">First name:</td>\n"
+ " <td>" + firstName + "</td>\n"
+ " </tr>\n"
Slide 10
Code for the AddToEmailListServlet class (cont.)
+ " <tr><td align=\"right\">Last name:</td>\n"
+ " <td>" + lastName + "</td>\n"
+ " </tr>\n"
+ " <tr><td align=\"right\">Email address:</td>\n"
+ " <td>" + emailAddress + "</td>\n"
+ " </tr>\n"
+ " </table>\n"
+ "<p>To enter another email address, click on the "
+ "Back <br>\n"
+ "button in your browser or the Return button shown <br>\n"
+ "below.</p>\n"
+ "<form action=\"join_email_list.html\" "
+ " method=\"post\">\n"
+ " <input type=\"submit\" value=\"Return\">\n"
+ "</form>\n"
+ "</body>\n"
+ "</html>\n");
out.close();
}
Slide 11
Code for the AddToEmailListServlet class (cont.)
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
}
Slide 12
The web.xml file with the mapping for the servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
Slide 13
The web.xml file with the mapping for the servlet
(cont.)
<!-- other configuration settings for the application -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>join_email_list.html</welcome-file>
</welcome-file-list>
</web-app>
Slide 14
The structure for a simple servlet that returns
HTML
package murach;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>HTML from servlet</h1>");
out.close();
}
Slide 15
The structure for a simple servlet that returns
HTML (cont.)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doPost(request, response);
}
}
Slide 16
How to code a servlet
• In practice, all servlets extend the HttpServlet class. To extend this
class, the servlet must import the java.io, javax.servlet, and
javax.servlet.http packages.
• The doGet method overrides the doGet method of the HttpServlet
class and processes all HTTP requests that use the Get method.
• The doPost method overrides the doPost method of the HttpServlet
class and processes all HTTP requests that use the Post method.
• The doGet and doPost methods use two objects that are passed to it
by the web server: (1) the HttpServletRequest object, or the request
object, and (2) the HttpServletResponse object, or the response
object.
Slide 17
How to code a servlet (cont.)
• The setContentType method of the response object sets the content
type of the response that’s returned to the browser. Then, the
getWriter method of the response object returns a PrintWriter
object that can be used to send HTML to the browser.
• Before you can create a PrintWriter object, you must set the
content type. This allows the getWriter method to return a
PrintWriter object that uses the proper content type.
Slide 18
XML tags that add servlet mapping to the web.xml
file
<!-- the definitions for the servlets -->
<servlet>
<servlet-name>AddToEmailListServlet</servlet-name>
<servlet-class>
email.AddToEmailListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>email.TestServlet</servlet-class>
</servlet>
Slide 19
XML tags that add servlet mapping to the web.xml
file (cont.)
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
Slide 20
XML elements for working with servlet mapping
Element Description
<servlet-class> Specifies the class for the servlet.
<servlet-name> Specifies a unique name for the servlet that’s used
to identify the servlet within the web.xml file. This
element is required for both the servlet element and
the servlet-mapping element and maps each servlet-
mapping element to a servlet element.
<url-pattern> Specifies the URL or URLs that are mapped to the
specified servlet. This pattern must begin with a
front slash, but the URL pattern can specify a virtual
directory or file that doesn’t actually exist.
Slide 21
Some URL pattern examples
URL pattern Description
/addToEmailList Specifies the addToEmailList URL in the root
directory of the application.
/email/* Specifies any URL in the email directory.
/email/add Specifies the add URL in the email directory.
/email/add.jsp Specifies the add.jsp URL in the email directory.
Slide 22
How to request the mapped servlet
Slide 23
A Form tag that requests the servlet
<form action="addToEmailList" method="post">
The URL displayed in the browser
http://localhost:8080/ch06email/addToEmailList
Slide 24
Five common methods of a servlet
public void init() throws ServletException{}
Slide 25
How the server handles a request for a servlet
Client
Request
Server
Slide 26
The life cycle of a servlet
• A server loads and initializes the servlet by calling the init method.
• The servlet handles each browser request by calling the service
method. This method then calls another method to handle the
specific HTTP request type.
• The server removes the servlet by calling the destroy method. This
occurs either when the servlet has been idle for some time or when
the server is shut down.
Slide 27
A method of the GenericServlet class
Method Description
getServletContext() Returns a ServletContext object that
contains information about the application’s
context.
Slide 28
Code that gets the real path for a file
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
Slide 29
The code for the User class
package business;
public User()
{
firstName = "";
lastName = "";
emailAddress = "";
}
Slide 30
The code for the User class (continued)
public User(String firstName, String lastName,
String emailAddress)
{
this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
}
Slide 31
The code for the User class (continued)
public void setLastName(String lastName)
{
this.lastName = lastName;
}
Slide 32
The code for the UserIO class
package data;
import java.io.*;
import business.User;
Slide 33
The code for the AddToEmailListServlet class
using User and UserIO classes
package email;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserIO;
Slide 34
Code for the AddToEmailListServlet class (cont.)
// use regular Java objects to write the data to a file
User user = new User(firstName, lastName, emailAddress);
UserIO.add(user, path);
Slide 35
Code for the AddToEmailListServlet class (cont.)
+ " <tr><td align=\"right\">Last name:</td>\n"
+ " <td>" + lastName + "</td>\n"
+ " </tr>\n"
+ " <tr><td align=\"right\">Email address:</td>\n"
+ " <td>" + emailAddress + "</td>\n"
+ " </tr>\n"
+ " </table>\n"
+ "<p>To enter another email address, click on the "
+ "Back <br>\n"
+ "button in your browser or the Return button shown <br>\n"
+ "below.</p>\n"
+ "<form action=\"join_email_list.html\" "
+ " method=\"post\">\n"
+ " <input type=\"submit\" value=\"Return\">\n"
+ "</form>\n"
+ "</body>\n"
+ "</html>\n");
out.close();
}
Slide 36
Code for the AddToEmailListServlet class (cont.)
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
}
Slide 37
Code that adds an instance variable to the
EmailServlet class
package email;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Slide 38
Code that adds an instance variable to the
EmailServlet class (cont.)
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// update global count variable
globalCount++; // this is not thread-safe
Slide 39
Code that adds an instance variable to the
EmailServlet class (cont.)
+ "<h1>Thanks for joining our email list</h1>\n"
+ "<p>This page has been accessed "
+ globalCount + " times.</p>"
+ "</body>\n"
+ "</html>\n");
out.close();
}
}
Slide 40
How to code instance variables
• An instance variable of a servlet belongs to the one instance of the
servlet and is shared by any threads that request the servlet.
• Instance variables are not thread-safe. In other words, two threads
may conflict when they try to read, modify, and update the same
instance variable at the same time, which can result in lost updates
or other problems.
Slide 41
Common servlet problems
Problem Possible solutions
The servlet won’t Make sure the compiler has access to the JAR
compile files for all necessary APIs.
Make sure the Java classes that you code are
stored in the correct directories with the correct
package statements.
The servlet won’t run Make sure the web server is running.
Make sure you’re using the correct URL.
Changes to the servlet Make sure servlet reloading is on.
aren’t showing up Redeploy the application.
Restart the server so it reloads all applications.
The page doesn’t Select the Source or Page Source command
display correctly from your browser’s View menu to view the
HTML code and identify the problem. Then,
you can fix the problem in the servlet.
Slide 42
Code that prints debugging data to the console
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
//
// code
//
String emailAddress =
request.getParameter("emailAddress");
System.out.println("AddToEmailListServlet emailAddress: "
+ emailAddress);
//
// code
//
}
Slide 43
How to print debugging data to the console
• When you’re testing an application on your local system, you can
use the println method of the System.out or System.err objects to
display debugging messages on the console for the servlet engine.
• When you use debugging messages to display variable values, it’s
a good practice to include the servlet name and the variable name
so the messages are easy to interpret.
• When you use an IDE like NetBeans, debugging data that is
written to a server console is also available in an output window.
Slide 44
Two methods of the HttpServlet class used to log
errors
Method Description
log(String message) Writes the specified message
to the server’s log file.
log(String message, Throwable t) Writes the specified message
to the server’s log file,
followed by the stack trace for
the exception.
Slide 45
Servlet code that prints the value of a variable to a
log file
log("emailAddress=" + emailAddress);
Slide 46
Servlet code that prints a stack trace to a log file
try
{
UserIO.add(user, path);
}
catch(IOException e)
{
log("An IOException occurred.", e);
}
Slide 47
The location of a typical Tomcat log file
C:\tomcat\logs\localhost.2007-06-29.log
Slide 48