Developing Java EE Web Applications Using RAD v7 - Training Etc

indexadjustmentInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

69 εμφανίσεις

D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-1
Chapter 3:
Servlets
1) A Simple Servlet.......................................................................................................3-2
2) Web Applications.....................................................................................................3-3
3) WebSphere Deployment Descriptors.....................................................................3-4
4) Running Servlets in RAD........................................................................................3-5
5) Configuring Servlets................................................................................................3-7
6) Configuring Servlets in RAD..................................................................................3-9
7) Servlet Initialization Parameters..........................................................................3-11
8) Generating and Validating Forms........................................................................3-16
9) Servlets and Threads.............................................................................................3-20
10) Other Settings in web.xml...................................................................................3-24



Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-2
A Simple Servlet

This servlet generates an HTML page with a welcome
message and the current date and time.
WelcomeServlet.java
1. package examples.servlets;
2.
3. import java.io.*;
4. import java.util.*;
5. import javax.servlet.*;
6. import javax.servlet.http.*;
7.
8. public class WelcomeServlet extends
9. HttpServlet {
10.
11. public void doGet
12. (HttpServletRequest request,
13. HttpServletResponse response)
14. throws ServletException, IOException {
15.
16. String title = "Welcome Servlet";
17. response.setContentType ("text/html");
18. PrintWriter out = response.getWriter();
19.
20. out.println("<HTML>");
21. out.println("<HEAD><TITLE>" + title +
22. "</TITLE></HEAD>");
23. out.println("<BODY><H1>" + "Welcome!" +
24. "</H1>");
25. out.println("<H3>" + new Date() +
26. "</H3>");
27. out.println("</BODY></HTML>");
28. }
29. }


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-3
Web Applications

A Web Application contains an application's resources,
such as servlets, JSPs, HTML pages and images. Web
Applications deployed on WebSphere use a standard
Java EE deployment descriptor (web.xml) and two
WebSphere-specific deployment descriptors (ibm-web-
bnd.xmi and ibm-web-ext.xmi).

Web Applications use a standard directory structure
defined in the Java EE specification and can be deployed
as a collection of files that use this directory structure
(called exploded directory format) or as an archive file
(.war file).

The root directory of the Web Application directory
structure is referred to as the document root of the
application. This directory contains files such as HTML
and JSPs. All files under this root directory can be served
directly to the client, except for files under a special
subdirectory named WEB-INF.

The WEB-INF directory contains web.xml, ibm-web-
bnd.xmi, ibm-web-ext.xmi, and the following
subdirectories:
 classes contains server classes such as servlets
 lib contains .jar files


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-4
WebSphere Deployment Descriptors

In the Project Explorer, examine the
mywebapp/WebContent/WEB-INF folder. In addition to
the Java EE standard deployment descriptor (web.xml),
you will find the WebSphere (vendor-specific) deployment
descriptors:
 ibm-web-bnd.xmi
 ibm-web-ext.xmi

XML (Extensible Markup Language) is a flexible way to
create common information formats, sharing both data
and the way the data is formatted. XML is similar to
HTML; both contain special markup symbols (or tags).

XMI (XML Metadata Interchange) is a proposed use of
XML that is intended to provide a standard way for
programmers to exchange information about metadata -
i.e., information about what a set of data consists of and
how it is organized. Specifically, XMI is intended to help
programmers using the Unified Modeling Language (UML)
exchange their data models with other programmers who
may be using different languages and development tools.

Ideally, XMI will allow cooperating companies to use each
other's data repositories. XMI is described as similar to,
but competing with, Microsoft's Open Information Model.



Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-5
Running Servlets in RAD

In the Project Explorer, right-click on “Java Resources:
src” (under “mywebapp”). Select “New / Package” from
the pop-up menu. The “New Java Package” dialog box
appears.

Enter examples.servlets in the “Name” box. Click
“Finish.”

In the Project Explorer, right-click on “examples.servlets”
and select “Import” from the pop-up menu. The “Import”
dialog box appears.

Expand the “General” node in the tree diagram, select
“File system” as the import source, and click “Next.”

On the next screen (“File system”), use the “Browse”
button next to the “From directory” box to select the
following directory:
c:\rad7-web\examples\servlets

A listing of all of the files in that directory should now
appear in the right-hand pane below the “From directory”
box.
 If the right-hand pane is empty, double click on “servlets” in the
left-hand pane.

Select all of the .java files in the right-hand pane, and
then click “Finish.”


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-6
Running Servlets in RAD

In the Project Explorer, expand “examples.servlets,” and
right-click on “WelcomeServlet.java.” Select “Run As” /
“Run on Server” from the pop-up menu.

The internal Web browser window opens, and the servlet's
output appears:





The servlet can also be tested with an external Web
Browser. Use the following URL:
http://localhost:9080/mywebapp/servlet/
examples.servlets.WelcomeServlet




Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-7
Configuring Servlets

Servlets are registered and configured as part of a Web
Application. You register a servlet in the web.xml file
using two elements:
 The <servlet> element defines a name for the servlet and
specifies the compiled class that contains the servlet.
Optionally, you can include <init-param> elements to define
initialization parameters.
 The <servlet-mapping> element defines the URL pattern
that calls the servlet.

Example:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>
mywork.servlets.ServletClass
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/urlname</url-pattern>
</servlet-mapping>


The servlet would be invoked as:
http://host:port/contextRoot/urlname


The context root is specified in the deployment descriptor
of the Enterprise Application (application.xml). Its
default value is the name of the Dynamic Web project.


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-8
Configuring Servlets

Note that each servlet has its own <servlet> and
<servlet-mapping> elements. Here is an example of
the entries in web.xml for three servlets:
1. <servlet>
2. <servlet-name>servlet1</servlet-name>
3. <servlet-class>
4. examples.servlets.WelcomeServlet
5. </servlet-class>
6. </servlet>
7.
8. <servlet>
9. <servlet-name>servlet2</servlet-name>
10. <servlet-class>
11. examples.servlets.Cart
12. </servlet-class>
13. </servlet>
14.
15. <servlet>
16. <servlet-name>servlet3</servlet-name>
17. <servlet-class>
18. mywork.servlets.MyDateServlet
19. </servlet-class>
20. </servlet>
21.
22. <servlet-mapping>
23. <servlet-name>servlet1</servlet-name>
24. <url-pattern>/Welcome</url-pattern>
25. </servlet-mapping>
26.
27. <servlet-mapping>
28. <servlet-name>servlet2</servlet-name>
29. <url-pattern>/shop</url-pattern>
30. </servlet-mapping>
31.
32. <servlet-mapping>
33. <servlet-name>servlet3</servlet-name>
34. <url-pattern>/mydate</url-pattern>
35. </servlet-mapping>


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-9
Configuring Servlets in RAD

To change the URL of the Welcome servlet, the servlet
can be registered in the Web Deployment Descriptor
(web.xml).

In the Project Explorer, expand “Web Content” and then
“WEB-INF.” Double-click on “web.xml.” This will open the
Web Deployment Descriptor editor. Click on the
“Servlets” tab.

Click on the “Add” button under the “Servlets and JSPs”
box. The “Create Servlet” dialog box appears.

Check the box labeled “Use existing Servlet class,” then
click the “Browse” button next to the “Class name” box.
The “New Servlet” dialog box appears.

Make sure the “Servlet” radio button is selected. Select
“WelcomeServlet” in the “Matching servlets” box. Then
click “OK.”

At this point, you should be back on the “Create Servlet”
dialog box. Click “Next.”

Accept the default setting in the “Name” box or enter a
name of your choosing.

Enter a short description for the servlet (optional).


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-10
Configuring Servlets in RAD

In the “URL Mappings” box, change the default setting
(/WelcomeServlet) to: /hello (Do not forget the leading
forward slash.)
 To change the URL Mapping, first select “/WelcomeServlet,”
then click the “Edit” button. Enter /hello in the “Pattern” box,
and click “OK.”

Click “Finish.”

“WelcomeServlet” should now appear in the “Servlets and
JSPs” box in the Web Deployment Descriptor editor.

Save the Web Deployment Descriptor using the File menu
or the Save icon (diskette) on the toolbar.

You can now access the servlet with a simpler (and more
flexible) URL:
http://localhost:9080/mywebapp/hello







Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-11
Servlet Initialization Parameters

Each servlet can receive a set of initialization parameters.
These parameters are name-value pairs that are used to
set default values or to customize the servlet.

Two methods are available to facilitate retrieval of the
initialization parameters:
Enumeration getInitParameterNames()
String getInitParameter (String parameterName)

Initialization parameters are specified in the <servlet>
element in the web.xml file. The general format is:
<init-param>
<param-name>aName</param-name>
<param-value>aValue</param-value>
</init-param>


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-12
Servlet Initialization Parameters

Here is an example demonstrating the retrieval of
initialization parameters.
InitParamsDemo.java
1. package examples.servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. public class InitParamsDemo extends HttpServlet {
8.
9. String backgroundColor = "white";
10. String foregroundColor = "black";
11.
12. public void init() throws ServletException {
13. String temp;
14.
15. temp = getInitParameter ("background");
16. if (temp != null) {
17. backgroundColor = temp;
18. }
19.
20. temp = getInitParameter ("foreground");
21. if (temp != null) {
22. foregroundColor = temp;
23. }
24. }
25.
26. public void doGet (HttpServletRequest request,
27. HttpServletResponse response) throws
28. ServletException, IOException {
29.
30. response.setContentType ("text/html");
31. PrintWriter out = response.getWriter();
32.
33. out.println ("<HTML><HEAD><TITLE>" +
34. "InitParamsDemo</TITLE></HEAD>");


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-13
Servlet Initialization Parameters
InitParamsDemo.java - continued
35. out.println ("<BODY BGCOLOR=" +
36. backgroundColor +
37. " TEXT=" + foregroundColor + ">");
38.
39. out.println ("<H3>Hello</H3>");
40.
41. out.println ("</BODY></HTML>");
42. }
43. }

Here are some settings that could be used to test the
InitParamsDemo servlet:
<servlet>
<servlet-name>initdemo</servlet-name>
<servlet-class>
examples.servlets.InitParamsDemo
</servlet-class>
<init-param>
<param-name>background</param-name>
<param-value>yellow</param-value>
</init-param>
<init-param>
<param-name>foreground</param-name>
<param-value>red</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>initdemo</servlet-name>
<url-pattern>/InitDemo</url-pattern>
</servlet-mapping>


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-14
Servlet Initialization Parameters

To use servlet initialization parameters, the servlet must

be registered in web.xml. In the Web Deployment
Descriptor editor (“Servlets” tab), click on the “Add” button
under the “Servlets and JSPs” box. The “Create Servlet”
dialog box appears.

On the next screen (“Create Servlet”), check the box
labeled “Use existing Servlet class,” then click the
“Browse” button next to the “Class name” box. The “New
Servlet” dialog box appears.

Be sure that the “Servlet” radio button is selected. Scroll
through the list of “Matching servlets” and select
“InitParamsDemo.” Click “OK.”

You should be back on the “Create Servlet” screen. Click
“Next.”

Accept the default setting in the “Name” box or enter a
name of your choosing.

Enter a short description for the servlet (optional).

Click the “Add” button next to the “Initialization
Parameters” box. The “Initialization Parameters” dialog
box appears.


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-15
Servlet Initialization Parameters

Enter background in the “Name” box and yellow in the
“Value” box. Click “OK.”

Use the “Add” button again to add the other parameter.
Name Value
foreground red


In the “URL Mappings” box, change the default setting
(/InitParamsDemo) to: /initdemo (Do not forget the
leading forward slash.)

Click “Finish.”

The servlet has now been registered in web.xml along
with the appropriate elements for the initialization
parameters. You can see the XML tags by clicking the
“Source” tab in the Web Deployment Descriptor editor.

In the Project Explorer, expand “examples.servlets,” and
right-click on “InitParamsDemo.java.” Select “Run As” /
“Run on Server” from the pop-up menu.

The servlet can also be tested with an external Web
Browser. Use the following URL:
http://localhost:9080/mywebapp/initdemo



Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-16
Generating and Validating Forms

The next example demonstrates a servlet that generates a
form and validates the user's entries. If any field is left
blank, an error message is displayed. If all fields are filled
in, the request is forwarded to a second servlet that
echoes the form data and provides a button to return to
the form.

When a servlet generates a form, special processing is
required so that there is no attempt to validate the form
data the first time the servlet is invoked.

To run this example, the FormServlet should be
registered under the URL “/showForm,” and the
FormSuccessServlet should be registered under the
URL “/showSuccess.”


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-17
Generating and Validating Forms
FormServlet.java
1. package examples.servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. public class FormServlet extends HttpServlet {
8.
9. public void doGet(HttpServletRequest req,
10. HttpServletResponse res)
11. throws ServletException, IOException {
12.
13. boolean formSubmitted = false;
14. boolean nameFilledIn = false;
15. boolean zipFilledIn = false;
16.
17. String name = req.getParameter("fname");
18. String zip = req.getParameter("zipcode");
19.
20. // Make sure that all fields have been
21. // filled in, but don't do this if it is
22. // the first time the form is displayed
23.
24. if (name != null && zip != null) {
25. formSubmitted = true;
26.
27. if (name.length() > 0) {
28. nameFilledIn = true;
29. }
30. if (zip.length() > 0) {
31. zipFilledIn = true;
32. }
33. }
34.
35. // If everything is OK, forward to
36. // another servlet
37.
38. if (nameFilledIn && zipFilledIn) {
39. RequestDispatcher rd =
40. req.getRequestDispatcher("/showSuccess");
41. rd.forward (req, res);
42. }


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-18
Generating and Validating Forms
FormServlet.java - continued
43. res.setContentType("text/html");
44. PrintWriter out = res.getWriter();
45.
46. out.println("<HTML><HEAD>");
47. out.println("<TITLE>Form Servlet</TITLE>");
48. out.println("</HEAD><BODY>");
49.
50. out.println("<FORM>");
51. out.println("First Name: " +
52. <INPUT TYPE=TEXT NAME=fname");
53.
54. // If this is not the first time form
55. // is displayed, show the name entered
56. // or an error message if blank
57.
58. if (formSubmitted) {
59. if (nameFilledIn) {
60. out.println
61. (" VALUE=" + name + ">");
62. } else {
63. out.println ("> <FONT COLOR=red>" +
64. "Name cannot be blank</FONT>");
65. }
66. }
67.
68. out.println("<BR>Zipcode: " +
69. <INPUT TYPE=TEXT NAME=zipcode");
70.
71. // If this is not the first time form
72. // is displayed, show the zipcode entered
73. // or an error message if blank
74.
75. if (formSubmitted) {
76. if (zipFilledIn) {
77. out.println (" VALUE=" + zip + ">");
78. } else {
79. out.println ("> <FONT COLOR=red>" +
80. "Zipcode cannot be blank</FONT>");
81. }
82. }


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-19
Generating and Validating Forms
FormServlet.java - continued
83. out.println
84. ("<P><INPUT TYPE=SUBMIT VALUE=Submit>");
85. out.println("</FORM></BODY></HTML>");
86. }
87. }

FormSuccessServlet.java
1. package examples.servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. public class FormSuccessServlet extends HttpServlet {
8.
9. public void doGet(HttpServletRequest req,
10. HttpServletResponse res)
11. throws ServletException, IOException {
12.
13. String name = req.getParameter("fname");
14. String zip = req.getParameter("zipcode");
15.
16. res.setContentType("text/html");
17. PrintWriter out = res.getWriter();
18.
19. out.println("<HTML><HEAD>");
20. out.println("<TITLE>Form Success</TITLE>");
21. out.println("</HEAD><BODY>");
22.
23. out.println("<H2>Success!!!</H2>");
24. out.println("You have completed the form.");
25. out.println("<UL><LI>Name = " + name);
26. out.println
27. ("<LI>Zipcode = " + zip + "</UL>");
28. out.println("<FORM ACTION=showForm>");
29. out.println("<P><INPUT TYPE=SUBMIT " +
30. "VALUE=\"Return to Form\">");
31. out.println("</FORM></BODY></HTML>");
32. }
33. }


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-20
Servlets and Threads

With servlets, your code need not explicitly create threads
to have synchronization problems. The server creates
threads to handle multiple simultaneous requests.

If a request for your servlet arrives while another request
has not yet been completed, both requests will execute
simultaneously in the same servlet object.

For example, suppose a bank deposit servlet is running
on a server (see the example on the next page).
 At or near the same time, two different clients could make
requests to deposit $500 to the same account. If the servlet is
not thread-safe, we have a race condition in which the account
could be left in an inconsistent state.

In the example on the next page, the private instance
variable balance is a race condition variable, because it
could be updated by two or more threads executing in the
doGet() method of the same servlet instance.

Typically, a servlet engine will not create multiple
instances of a servlet, but note that some servers do
create separate servlet instances for each request. In this
case, you must first solve the problem of how to share the
data (e.g., make it static), and then you still must deal
with the thread problem.


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-21
Servlets and Threads
BankServlet.java
1. package examples.servlets;
2.
3. import java.io.*;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6.
7. public class BankServlet extends HttpServlet {
8.
9. private static double balance = 0.0;
10.
11. public void doGet(HttpServletRequest req,
12. HttpServletResponse res)
13. throws ServletException, IOException {
14.
15. double d;
16. res.setContentType("text/html");
17. res.setStatus(HttpServletResponse.SC_OK);
18. PrintWriter out = res.getWriter();
19.
20. out.println("<HTML><HEAD>");
21. out.println("<TITLE>Bank Servlet</TITLE>");
22. out.println("</HEAD>");
23. out.println("<BODY>");
24.
25. String amount = req.getParameter("amount");
26.
27. if (amount != null && ! amount.equals("")) {
28. d = getBalance();
29. out.println("<P>Old Balance is " + d);
30. d += Double.parseDouble(amount);
31.
32. // This sleep makes it possible for the
33. // user to consistently observe the
34. // the problem. Start two browsers and
35. // have them both do the update at the
36. // same time (within two seconds).
37.
38. try { Thread.sleep(2000); }
39. catch (InterruptedException e) {}
40.
41. setBalance(d);
42. }


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-22
Servlets and Threads
BankServlet.java – continued
43. out.println("<P>New Balance is " + balance);
44. out.println
45. ("<FORM METHOD=GET ACTION=\"Bank\">");
46. out.println("<P>Enter an amount to deposit");
47. out.println("<INPUT TYPE=TEXT NAME=amount>");
48. out.println("<P><INPUT TYPE=SUBMIT
49. VALUE=\"Submit Deposit\">");
50. out.println("<INPUT TYPE=RESET
51. VALUE=\"Clear Amount\">");
52. out.println("</FORM></BODY></HTML>");
53. }
54.
55. public void init() throws ServletException {
56. System.out.println ("BankServlet initialized");
57. }
58.
59. public double getBalance() {
60. return balance;
61. }
62.
63. public void setBalance(double d) {
64. balance = d;
65. }
66. }

Note that this servlet must
be registered under the URL of
"/Bank".


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-23
Servlets and Threads

The “critical section” of code is this block:
if (amount != null)
{
d = getBalance();
d += Double.parseDouble(amount);
setBalance(d);
}

Two requests could get the balance before either one sets
the balance unless the code block is synchronized.
synchronized (BankServlet.class)
{
if (amount != null)
{
d = getBalance();
d += Double.parseDouble(amount);
setBalance(d);
}
}

One could synchronize the entire service() method, but
this would incur an unnecessary performance hit.

Although the balance variable above was the source of
the problem, this does not mean that all data should be
synchronized, only variables that might be updated by
multiple threads.


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-24
Other Settings in web.xml

Define context parameters
 The <context-param> element declares servlet context
initialization parameters.
 Each <context-param> element has two sub-elements,
<param-name> and <param-value>.
 These parameters are available throughout the Web
application, and can be accessed using the
getInitParameter() and getInitParameterNames()
methods (from javax.servlet.ServletContext). A
servlet obtains its ServletContext by calling the
getServletContext() method.

Define welcome pages
 The <welcome-file-list> element can be used to specify
a list of pages to look for when the URL specified is a directory.
One or more <welcome-file> sub-elements specify page
names, which are looked for in the order specified.
 If you do not define a welcome page, WebSphere looks for the
following files (in the order shown):
• index.html
• index.htm
• index.jsp
• default.html
• default.htm
• default.jsp


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-25
Other Settings in web.xml

Define error pages
 The <error-page> element can be used to define a
customized page to respond to HTTP errors or Java
exceptions. The sub-elements are <error-code> (or
<exception-type>) and <location>.
• <error-code> contains an HTTP error code (e.g., 404).
• <exception-type> contains the name of a Java exception
class.
• <location> contains the URL of the error page.

Example settings in web.xml
1. <web-app id="WebApp_ID" version="2.4"
2. xmlns="http://java.sun.com/xml/ns/j2ee"
3. xmlns:xsi=
4. "http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation=
6. "http://java.sun.com/xml/ns/j2ee
7. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
8.
9. <context-param>
10. <param-name>myparameter</param-name>
11. <param-value>orange</param-value>
12. </context-param>
13.
14. <!-- servlet and servlet-mapping -->
15. <!-- elements go here -->
16.
17. <welcome-file-list>
18. <welcome-file>hello.html</welcome-file>
19. </welcome-file-list>
20.
21. <error-page>
22. <error-code>404</error-code>
23. <location>/error404.jsp</location>
24. </error-page>
25. </web-app>


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-26
Creating a New Servlet

In the Project Explorer, right-click on “examples.servlets,”
and select “New / “Other” from the pop-up menu. The
“New” dialog box appears.

In the tree diagram, expand the node labeled “Web,” and
select “Servlet.” Click “Next.”

On the next screen (“Create Servlet”), type a name in the
“Class name” box. Click “Next.”

On the next screen, accept the default settings or enter
your own values in the “Name” and “URL Mappings”
boxes. Click “Next.”

The next screen allows you to select which method stubs
should be generated. In particular, you can select a
doGet(), a doPost(), or both. You can also get an
init() method if needed. Make your selections and
click “Finish.”

An editor pane opens to allow you to complete the coding
for the new servlet class.


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-27
Exercises
1. Modify the WelcomeServlet so that the welcome
message is passed into the servlet as an initialization
parameter.
 Solution: solutions\servlets\WelcomeServlet2.java
2. Test the BankServlet. (It should be registered in
web.xml and mapped to the URL /Bank.) Open two
browser windows and click the two submit buttons in
rapid succession. You should lose some money! Then
activate the commented line to solve the problem.
3. Write a servlet that produces a “hit” count.
 Each time the servlet is requested, it prints a number reflecting
the number of times that this servlet has been requested.
 It should also display the number of seconds since the last
request.
 Prove that the servlet is not thread-safe.
 Solution: solutions\servlets\NonSafeCounter.java
4. Make the servlet from the previous exercise thread-safe.
 Solution: solutions\servlets\SafeCounter.java
5. Write a servlet that displays the data entered by the user
on the “My Profile” form (from exercise in previous
chapter).
 Solution:
solutions\project3\myprofile.html
solutions\project3\EchoServlet.java


Copy
Copy
Evaluation
Evaluation


D
EVELOPING
J
AVA
EE

W
EB
A
PPLICATIONS USING
RAD
V
7 C
HAPTER
3:

S
ERVLETS

©2009 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
3-28
This Page Intentionally Left Blank


Copy
Copy
Evaluation
Evaluation