Sei sulla pagina 1di 76

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

n
Web Component Development
a
s
With Servlet and
haJSP
)

m
Technologies
co uide

o tG
o
h
Activity
e- nSolaris
ya Guide
d
@
u
j
a SL-314-EE6
St
w
s
i
d
r
th
a
h
e
tb o us
n
a
k se t
a
(um licen

A
AK

UM

D65271GC11
Edition 1.1
July 2010
D68406

SOInfotech Pvt Ltd


Copyright 2010, Oracle and/or its affiliates. All rights reserved.

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Disclaimer
This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
Sun microsystems Disclaimer
This training manual may include references to materials, offerings, or products that were previously offered by Sun
microsystems . Certain materials, offerings, services, or products may no longer be offered or provided. Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
Restricted Rights Notice
If this documentation is delivered to the U.S. Government or anyone using the documentation on behalf of the U.S.
Government, the following notice is applicable:

Trademark Notice

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.

UM

A
AK

an
r
t
n

U.S. GOVERNMENT RIGHTS


The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

bl
a
r
fe

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

no
This page intentionally left blank.
a
s

UM

A
AK

ha
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

no
This page intentionally left blank.
a
s

UM

A
AK

ha
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

Table of Contents
About This Workbook ............................................................Preface-i
Course Goal ............................................................................. Preface-i
Conventions ............................................................................. Preface-ii
Icons ................................................................................. Preface-ii
Typographical Conventions ......................................... Preface-ii
Additional Conventions.............................................. Preface-iv

an
r
t
n

UM

no
a
has
Introduction to Java Servlets ..........................................................1-1
)
Objectives ...........................................................................................
1-1
om uide
c

o
Exercise 1 .............................................................................................
1-2
G
t
n
ahoProject....................................................
Task Create ayNew
1-2
de
@
u
j
Task Create
a
servlet..............................................................
1-2
t
a
S
w
Task
isthe Servlet...................................................... 1-3
rd Examine
h
t
a
h
Task

Create
the
New Servlet Code...................................... 1-3
e
b
s

t
u
o Run the New Servlet .................................................... 1-3
t
kan seTask
a
Task Provide an Index Page ................................................. 1-4
m enExercise
u
(
Summary.............................................................................. 1-6
lic
T

A
AK

Introduction to Java Server Pages .................................................2-1


Objectives ........................................................................................... 2-1
Exercise 1 ............................................................................................. 2-2
Task Create an HTMLForm.................................................. 2-2
Task Create a JSP.................................................................... 2-2
Task Run the Application ..................................................... 2-3
Exercise Summary.............................................................................. 2-4
Implementing an MVC Design .........................................................3-1
Objectives ........................................................................................... 3-1
Exercise 1 ............................................................................................. 3-2
Task Design a JavaBeans Compliant Model. ..................... 3-2
Task Implement the Model................................................... 3-3
Task Create an HTML Form to Submit the Request......... 3-3
Task Create a View Component Using a JSP..................... 3-4
Task Create the Controller.................................................... 3-4

v
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd

Task Run the Application ..................................................... 3-5


Exercise Summary.............................................................................. 3-6

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The Servlets Environment.............................................................. 4-1


Objectives ........................................................................................... 4-1
Exercise 1 ............................................................................................. 4-2
Task Create index.jsp and a View JSP............................. 4-2
Task Create the Controller Servlet....................................... 4-2
Exercise Summary.............................................................................. 4-4
Container Facilities For Servlets & JSPs....................................... 5-1
Objective............................................................................................. 5-1
Exercise 1 ............................................................................................. 5-2
Task Investigate Projects Using web.xml........................... 5-2
Task Code the Servlet to Use the Configuration Information
5-3
Task Prepare the Index Page and Run the Application .... 5-5
Exercise Summary.............................................................................. 5-6

an
r
t
n

no
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r Pages ....................................................................
h
t
a
Developing
JSP
7-1
h
e
b
s

t
u
Objectives
...........................................................................................
7-1
n
o
a
t
k
e 1 ............................................................................................. 7-2
a Exercise
sTask
m
n
u
e
Investigate JSP Translation.......................................... 7-2
(
licExercise 2 .............................................................................................
T
7-3
More View Facilities......................................................................... 6-1
Objectives ........................................................................................... 6-1
Exercise 1 ............................................................................................. 6-2
Task List HTTP Headers ....................................................... 6-2
Exercise 2 ............................................................................................. 6-3
Task ............................................................................................. 6-3
Exercise Summary.............................................................................. 6-4

A
AK

UM

Task Investigate the jsp:useBean Tag .............................. 7-3


Task Retrieve Session Information Using JSP Tags .......... 7-4
Exercise Summary.............................................................................. 7-5
Developing JSP Pages Using Custom Tags ................................. 8-1
Objective............................................................................................. 8-1
Exercise 1 ............................................................................................. 8-2
Task Investigate the c:out Core Tag. ................................. 8-2
Task Investigate the c:remove Core Tag. .......................... 8-2
Exercise Summary.............................................................................. 8-4
More Controller Facilities................................................................ 9-1
Objectives ........................................................................................... 9-1
Exercise 1 ............................................................................................. 9-2
Task Witness the Failure ....................................................... 9-2
Task Examine the Cause of the Failure............................... 9-3
Exercise 2 ............................................................................................. 9-4

vi

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Examine the Starting Point.......................................... 9-4


Task Install a Login Mechanism in the Application ......... 9-4
Task Install a Security Filter in the Application ................ 9-5
Exercise Summary.............................................................................. 9-7
More Options for the Model...........................................................10-1
Objective........................................................................................... 10-1
Exercise 1 ........................................................................................... 10-2
Task Create a New Project and an Entity. ........................ 10-2
Task Create a controller ...................................................... 10-2
Task Create JSPs ................................................................... 10-3
Task Test the Application ................................................... 10-3
Task Optional: Add Edit, Delete, and Find Operations . 10-3
Exercise Summary............................................................................ 10-4

an
r
t
n

UM

no
a
has
)
om uide
c

o tG
o
Implementing Security ...................................................................12-1
h
ya uden
Objectives .........................................................................................
12-1
@
j
t
Exercise 1 ...........................................................................................
12-2
a sS
w
i
d
r Verify
Task
ththe Project Prior to Adding Security............ 12-2
a
h
e
Users in the GlassFish Server................. 12-2
tb Task
u sConfigure
n
o
Task
Assign
Users
Roles................................................. 12-2
a
t
k seTask MandateLogintoBefore
a
Access.................................... 12-3
m en
u
(
Task Run the Application and Verify Login Requirement ....
lic
T

A
AK

12-3
Task Pick Up the Username from the Environment....... 12-4
Task Modify the Application to Use Form-based login . 12-4
Task Provide a Logout Mechanism................................... 12-4
Exercise Summary............................................................................ 12-5

vii
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

Asynchronous Servlets and Clients .............................................11-1


Objectives ......................................................................................... 11-1
Exercise 1 ........................................................................................... 11-2
Task Create a New Project and Asynchronous Servlet .. 11-2
Task Create an Asynchronous Client................................ 11-3
Task Test the Application. .................................................. 11-4
Exercise Summary............................................................................ 11-5

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

viii

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab Preface

About This Workbook


Course Goal

bl
a
r
fe

Upon completion of this lab workbook, you should be able to:

an
r
t
n

Write servlets using the Java programming language (Java


servlets)

no
a
has
)
Write pages created with the JavaServer
om Pages
ide technology (JSP
c

u
o
pages)
o nt G
h
a
yJSP pages
de using the Expression Language,
Create easy-to-maintain
@
u
j
t
S
JSP Standard Tag
(JSTL), and the Struts Tiles framework
waLibrary
s
i
d
r
h
t
a
h web
Create
robust
b
se applications that integrate Struts and JSP pages

t
u
n
a e to
kworkbook
a
This
m ens presents the lab exercises for each module of the Student
u
(
lic
T Guide.

Create robust web applications using Struts, session management,


filters, and database integration

A
AK

UM

Lab Preface-i
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Conventions

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Conventions
The following conventions are used in this course to represent various
training elements and alternative learning resources.

Icons
Note Indicates additional information that can help you, but is not
crucial to your understanding of the concepts being described.

Typographical Conventions

bl
a
r
fe

an
r
t
n

no
a
has
)
om uide
Use ls -al to list all files.
c

G
system% You have mail.hoo
t
n
a
y ude
@
j
t
a indicate
Sprogramming
Courier is also used
to
constructs, such as class
w
s
i
d
r
h
names, methods,
for example:
t
a and ekeywords;
h
b
s

u
ntgetServletInfo
The
method is used to get author information.
o
a
t
k
e
a
java.awt.Dialog
class contains Dialog constructor.
s
m The
n
u
e
(
lic
T
Courier is used for the names of commands, files, directories,
programming code, and on-screen computer output; for example:

A
AK

UM

Courier bold is used for characters and numbers that you type; for
example:
To list the files in this directory, type:
# ls

Courier bold is also used for each line of programming code that is
referenced in a textual description; for example:
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
Notice the javax.servlet interface is imported to allow access to its
life cycle methods (Line 2).

Lab Preface-ii

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Conventions

Courier italics is used for variables and command-line placeholders


that are replaced with a real name or value; for example:

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

To delete a file, use the rm filename command.

Courier italic bold is used to represent variables whose values are to


be entered by the student as part of an activity; for example:
Type chmod a+rwx filename to grant read, write, and execute
rights for filename to world, group, and users.
Palatino italics is used for book titles, new words or terms, or words that
you want to emphasize; for example:
Read Chapter 6 in the Users Guide.
These are called class options.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

About This Workbook


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

Lab Preface-iii

SOInfotech Pvt Ltd


Conventions

Additional Conventions

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Java programming language examples use the following additional


conventions:

Method names are not followed with parentheses unless a formal or


actual parameter list is shown; for example:
The doIt method... refers to any method called doIt.
The doIt() method... refers to a method called doIt that takes
no arguments.

Line breaks occur only where there are separations (commas),


conjunctions (operators), or white space in the code. Broken code is
indented four spaces under the starting code.

If a command used in the Solaris Operating System (Solaris OS) is


different from a command used in the Microsoft Windows platform,
both commands are shown; for example:

an
r
t
n

n
a
If working in the Solaris OS:
as
h
)
$cd SERVER_ROOT/BIN
om uide
c

o tG
o
h
a den
If working in MicrosoftyWindows:
@
j
C:\>CD SERVER_ROOT\BIN
a s Stu
w
rd thi
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Lab Preface-iv

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 1

Introduction to Java Servlets


Objectives
Upon completion of this lab, you should be able to:

Explore the NetBeans IDE (Integrated Development Environment)

Create and run a simple servlet

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

1-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will create a simple servlet. In the process, you will
begin to become familar with NetBeans, the IDE used throughout this
class.

Preparation
No preparation is needed for this exercise.

Task Create a New Project.


1.

Select the New Project icon (or select File->new project)

underneat it. Underneath Web Pages you will see WEB-INF and
index.jsp. Right click on the index.jsp and select Delete. Answer
the prompt to delete the file. Notice that the file disappears from the
editor pane on the right.

UM

1-2

an
r
t
n

Start NetBeans by launching the icon on your desktop. The icon


looks like a blue cube.

no
a
has labeled Next >
3. Select a Java Web project, then click the) button
om uithen
de click Next > again
c

4. Give the project the name SL314m01lab1,


o
o nt G
h
a
5. Click Next > again, then
click
e
y udFinish
@
j
t
wa his S
d
r
t
aa servlet
h
e
Task Create
b
s

nt to u
a
k
e the left side of the NetBeans UI, notice the project explorer
a nson
m
1. High
u
e
(
lictree. This should show your new project, with Web Pages as a folder
T
2.

A
AK

bl
a
r
fe

2.

Below the Web Pages entry, you will see a folder labeled Source
Packages. Right click on that, and select new and then Servlet.

3.

At the Class Name: prompt, enter the name Lab1Servlet

4.

At the Package: prompt, enter the package name SL314.m1

5.

Click Next >, notice that the Servlet Name is Lab1Servlet and the
URL Pattern is /Lab1Servlet.

6.

Click Finish.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Examine the Servlet


1.

On the right side of the NetBeans UI, you will now see the template
servlet code created for you by the wizard. Notice that the editor is a
folding editor. That is, it hides chunks of code that might be
considered less important, and allows you the opportunity to do the
same. The idea is that you can make code more readable by
removing clutter from your editor. Notice that very near the bottom
of the source file, there is a line that starts with a plus-sign in a box,
and this text: HttpServlet methods. Click on the + sign on the left to
edit the code.

2.

Click the plus sign, and observe that the formerly hidden text is now
visible. Notice that there are two methods, doGet and doPost, which
both delegate directly to the processRequest method. (This was
described in the module.)

bl
a
r
fe

ns
a
r
t
3. Notice that both doGet and doPost are labeled @Override.
n- Recall
o
n
that this is a Java 5 language feature that will cause
a the compiler to
s
object if the designated method is an overload,
a or unique method,
hconfidence
)
rather than a genuine override. This gives
m ide that doGet and
o
c
doPost are actually the correctly
formed
umethods.
o
G
o
t
ah den
y
tu Code
aj@Servlet
S
Task Create the
New
w
rd this
a
h
se
tbprocessRequest
u
1. a
Innthe
method, uncomment the skeleton code. This
to a minimal HTML
k code screates
e
a
page, and will save you some typing.
m en
u
(
2. licAdd a little of your own code to the servlet to personalize it. This
T

A
AK

could be as simple as adding your name, or something a little more


complex, such as a calculation. Remeber, however, that the point of
this exercise is familiarity with the tools, and the basic
understanding of where code is placed in the servlet, so do not risk
wasting time by being unduly ambitious. Theres time in the course
for that later.

UM

3.

After you have entered your code, if is not properly indented, rightclick in the editor pane and select Format. Notice that the indentation
is corrected to conform with the rest of the code.

Task Run the New Servlet


1.

Type Control-S (or select File->Save) to save the file.

Introduction to Java Servlets


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

1-3

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
2.

Right click on the project and select Run from the popup menu.
NetBeans will start the GlassFish server and Derby database,
compile your servlet, and build the web application. It then attempts
to run the application.

3.

Because this is a web appplication, to run it requires that a browser


be started. In this case, NetBeans automatically starts the browser.
However, it points the browser at the base of the application, not at
the servlet you just created, so you will get an error from the
browser, and must modify the URL to find your servlet successfully.

4.

Look at the top of the servlet class. You will see a line like this:
@WebServlet(name = Lab1Servlet, urlPatterns =
{/Lab1Servlet}}

5.

no
a
has
)
om uide
c

o tG
o
h
Task Provide an Indexya
Pageden
@
j
a s Stu
w
i in the project browser. Be sure youre
rd WebthPages
1. Find the a
entry
h
e for this project. Right click on that and select
b at theusentry
looking
t
n
to ....
kaNews->e HTML
a
enthe prompt HTML File Name: enter index and click Finish
(um2.licAt

A
AK

an
r
t
n

6.

The browser should now display the page created by your servlet,
and you should recognize the additional behavior you placed into
the template.

3.

In the resulting template, enter an HTML link (anchor) element that


will jump to the URL currently in your browsers URL bar. If you
have done everything as specified in these notes, that should be
something like:

UM

http://localhost:11331/SL314m1lab1/Lab1Servlet

Note The port number might vary depending on the version of


NetBeans, GlassFish, or installation conditions.
4.

The full text of the link HTML might look like this:
Click <a
href="http://localhost:8080/SL314m1lab1/Lab1Servlet">
here</a> to go to the servlet

5.

1-4

Save the file, and run the project again.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

Append the urlPatterns element (/Lab1Servlet in this example) to


the URL in the browser, and set the browser to loading that
composite URL.

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6.

This time, you should find that the browser immediately displays
your index page, and when you click the link, you are taken to your
servlet.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Introduction to Java Servlets


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

1-5

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

UM

A
AK

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 2

Introduction to Java Server Pages


Objectives
Upon completion of this lab, you should be able to:

Create a simple Java Server Page (JSP) page

Send input to a JSP and process that input

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

2-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will create an HTML form and a simple JSP that
handles input from that form.

Preparation
No preparation is needed for this exercise.

Task Create an HTMLForm

bl
a
r
Note From this point on, you will not be given detailed instructions
fein
s
n
the use of NetBeans unless you have to do something that hastrnot
a been
- consult
n
previously described. If you have difficulty with the IDE,ofirst
the
n
lab instructions for lab 1 to see if they contain a description
of what you
a
s
a
are trying to do. If you still cannot make the IDE
what you want it to,
) h do

m
ask your instructor for assistance.
co uide

o
GSL314m02lab1.
t
ho named
1. Create a new Java Webya
project
n
de
@
u
j
t
2. Delete the index.jsp
wa hisfile.S
d
r
t file called index.html
3. Create h
aa
new HTML
e
b
s

u
nt thetotemplate
4. kaWhere
states TODO write content enter the following
e
a
s
HTML
code:
en action="simple.jsp">
(um lic<form

A
AK

Please enter your favorite animal:&nbsp;


<input type="text" name="favoriteAnimal" value="Gnu"

UM

/>
<input type="submit" />
</form>
5.

Save the file

Task Create a JSP

2-2

1.

Right click on Web Pages for this project, then select New->JSP... to
create a new JSP file called simple (the file will be named
simple.jsp automatically.

2.

In the JSP, change the title to Animal Lovers Page

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
3.

In the JSP, change the level-one heading to Hello Animal Lover

4.

In the JSP, below the level-one heading, enter the following text:
<p>Your favorite animal is a
<%= request.getParameter("favoriteAnimal") %>
Wow, mine is too!
</p>

5.

Save the file.

Task Run the Application


1.

Run the application, you should see a form that prompts you to
enter your favorite animal

bl
a
r
2. Type the name of an animal into the text box and click the submit
fe
s
n
button
tra
n
3. You should see the output of your JSP, which should
nostate your
a
favorite animal, and express surprise that the
favorite is
hascomputers
the same.
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Introduction to Java Server Pages


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

2-3

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

2-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 3

Implementing an MVC Design


Objectives
Upon completion of this lab, you should be able to:

Create a model component adhering to JavaBeans naming


conventions

bl
a
r
fe

ns
a
r
t
Use a servlet to create a controller component, use thatncontroller
to
o
n
invoke a model, and forward that model to a JSP
a view for display
s
User a JSP to create a view component ha
) e
m
o
Use the Expression Language toread
id from a JavaBeans
c attributes
u
o
G
o
compliant model
ah dent
y
aj@ s Stu
w
rd thi
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

3-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will create an MVC-based web application. The
application will allow the user to determine the material traditionally
associated with a given wedding anniversary.

Preparation
No preparation is needed for this exercise.

Task Design a JavaBeans Compliant Model.


1.

UM

an
r
t
n

Consider the attributes needed to model the wedding anniversary


problem. One writable attribute will be needed to represent the year
number of the anniversary. Another, read-only, attribute will be
needed to allow the view to present the name of the associated
material.

no
a
has
)
m ide
o
c

uand write them in the first


2. Decide what you will call these
o attributes,
G
o
t
h
colum of Table 3-1 below.
ya uden
@
j
t
3. Decide what theanecessary
methods will be to
Scorresponding
w
s
i
d
r attributes
support those
th in the JavaBeans naming conventions. Write
a
h
e
those
in Table 3-1 below. Note that because one attribute is
tbmethods
uswill
n
o
a
read-only,
you
require a total of three methods, so one table cell
t
k se
a
en remain blank.
(um licwill

A
AK

Table 3-1 JavaBeans Attribute and Method Names


Attribute
Name

4.

AccessorMethod

Mutator Method

Decide what key name you will use to store the model in the request
when it is forwarded. Write that down here:

Table 3-2 Model Name When Stored in Request Scope


Model name in request scope

3-2

bl
a
r
fe

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1
5.

Decide on the name of your model class, package name, and what, if
any, base class it should extend. Write those down here:

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Table 3-3 Bean Class and Ancestry


Bean class name
Bean package
Bean class extends

Task Implement the Model

2.

Create a new class for the model as you specified in Table 3-3 above
and provide get and set methods as you specified in Table 3-1 above.

no
a
3. In the file anniversaries.txt, you will findslists of anniversary
haapply.
material names with the year to which )they
These data are

m
e
o
provided in a form intended to simplify
incorporating
a Java
c
uidextract the into
o
G
class. Use this form if it suits
you
or
simply
raw
data if
o
t
h
n
a
y creating
you prefer to use that in
deyour model. The file can be found
@
u
j
t
under the Files tab
(just
to
the
a s S right of the Projects tab in NetBeans)
w
d
r
at the root
directory
ofi the solution for this lab.
h
t
a
h
sea trivial main method in your model to test the
b Create
t
u
4. (Optional)
n
to
kabasicsfunctioning
of the methods.
e
a
m
n
u
e
(
lic
T

N Task Create an HTML Form to Submit the Request

A
AK

UM

In NetBeans, create a new web application project called


SL314m03lab1. This will also be the context root for the application.

an
r
t
n

1.

You will need a regular HTML form to allow the user of your
application to enter the anniversary year they are interested in.
When you created the project, NetBeans created an index.jsp file.
Delete this file and create a new HTML page called index.html
instead.

2.

In the index.html file, you will create a form that prompts for a
number of years. Decide what you will call the parameter when it is
submitted to the web application. Write this parameter name in the
Table 3-4 below.

Implementing an MVC Design


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

1.

3-3

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

3.

The form will invoke an action, which will be the controller servlet
that you will create shortly. Decide what the context root of this
application will be, and the URL that will invoke the controller. Write
these too in the Table 3-4 below.

Table 3-4 Information Required for Assembling the Form


Parameter name
Context root
Servlet URL
4.

Create the form in the index.html file.

Task Create a View Component Using a JSP rans


-t

on
n
1. Decide what you will call your view JSP. Writea
this down here:
s
a
) h e
Table 3-5 JSP View Name
m
co uid

o
o nt G
JSP name
h
a
y ude
@
j
a s St
w
iview. It must present the year and anniversary
d
2. Create the rJSP for the
h
t
a
h
e
material
by the model. Recall the name of the model
sreturned
b name
t
u
n
in Table
to3-2 above. This will be needed along with the attribute
kaas
e
a
s
names
from
Table 3-1 above to construct the EL expressions.
m en
u
(
lic
T

A
AK

UM

3-4

Task Create the Controller


1.

The final step in constructing this application is to create a controller


to tie it all together. Create an HttpServlet, and ensure that it
responds to the URL that you selected in Table 3-4 above.

2.

Modify the processRequest method so that it:


a.

Extracts the year parameter named in Table 3-4 above.

b.

Creates an instance of the model.

c.

Sets the year value in the model (consider the data typeis this
a String or an int? If you convert, do not try to help the user but
simply swallow any exceptions and produce a clean output.
Error handling is a topic of later modules.)

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
d.

Stores the model in the request scope using the name in


Table 3-2 above.

e.

Forwards to the view, named in Table 3-5 above.

Task Run the Application


1.

Right-click the project and run it.

2.

Your browser should be launched automatically, and should show


the input form. Enter a number of years, and press the submit
button.

3.

You should see appropriate output in the subsequent browser page.

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Implementing an MVC Design


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

3-5

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

3-6

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 4

The Servlets Environment


Objectives
Upon completion of this lab, you should be able to:

Extract and examine HTTP request headers

Create an HTML form

an
r
t
n

Create and use an HttpSession to create a simple shopping cart

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

bl
a
r
fe

A
AK

UM

4-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will list the HTTP headers that are sent by your
browser.

Preparation
No preparation is needed for this exercise.

Task Create index.jsp and a View JSP

bl
a
r
In this project, the MVC model will be simplified a little. The intentioneis
sf
that you will create a servlet to act as controller and a JSP to act asnview,
a
but will use a String object to carry the result data directly from
-trthe servlet
n
o
to the JSP.
n
a
s
1. Create a new project called SL314m4l1. ha
)
eso that it carries a
om uifile
2. Edit the automatically created index.jsp
d
c

G /ListHeaders. You may


o
single link that will lead to
ao
relativet URL,
h
n
a
use an HTML anchor y
to do this,
deor if youre feeling ambitious, a
@
u
j
t
a an otherwise
submit buttonwon
S empty form.
s
i
d
r
h
t project, call this file HeadersView.jsp
a JSP toe the
3. Add a h
new
b
s

u
nt to the
o
4. kaAdd
view introductory text such as These are the headers
t
a ofnyour
se browser.
m
u
e
(
ic
5. l Add an EL expression that will output the value of a text element in
T

A
AK

the request scope called headerList.

UM

Task Create the Controller Servlet


1.

Add a servlet to the project. Make the fully qualified name of the
servlet sl314.m4.HeaderServlet.

2.

Set the URL pattern for the servlet to ListHeaders.

3.

In the servlet, declare a StringBuilder called result. Set the value


of the result to <UL>\n.

4.

Obtain the enumeration of header names from the request object.

5.

For each entry in the enumeration:


a.

4-2

Append <LI> to result.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
b.

Append the header name to result.

c.

Append = to result.

d.

Extract the value of the header from the request and append
that value to result.

e.

Append </LI>\n to the result.

6.

Append </UL>\n to result.

7.

Add an attribute to the request called headerList and set the value
to result.

8.

Forward to HeadersView.jsp.

9.

Finally, run the example and verify that you see headers such as
host, user-agent, accept and others.

bl
a
r
fe

an
r
t
n

Note As you create the HTML in your servlet, consider the implications
this has for maintainability. Previous discussions have already identified
this as a bad practice. Can you determine why this is being done in this
example? How do you think this could be avoided?

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

The Servlets Environment


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

4-3

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

4-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 5

Container Facilities For Servlets & JSPs


Objective
Upon completion of this lab, you should be able to:

Identify critical elements of the deployment descriptor, web.xml

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

5-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will investigate the deployment descriptor and the
containers servlet support.

Preparation
No preparation is needed for this exercise.

Task Investigate Projects Using web.xml

1.

Create a new Java Web project named SL314m05lab1

2.

Create a servlet. Accept the default name NewServlet, and place it


in the package sl314m5.lab. Click Next >

UM

an
r
t
n

no
a
3. Select the checkbox Add information to deployment
descriptor
has
(web.xml)
)
m ide
othat
c

4. Modify the URL Pattern(s) field


so
itureads /PathToServlet/*
o
G
o
t
atohthedright
5. Click on the New button
en of the table labeled Initialization
y
@
u
j
t created row of the table the values
Parameters. Type
a into stheSnewly
w
i
d
KeyName and
r DatathValue under the headings Name and Value
a
h
respectively.
se
b
t
u
n
to
kaClicksFinish
6.
e
a
en that under the project folders Web Pages->WEB-INF there is a
(um7.licNotice

A
AK

bl
a
r
fe

new node named web.xml. Double click on that element.

8.

From the editor pane, select the General tab, then open the Context
Parameters region. (Click on the plus sign).

9.

Select Add... in the Context Parameters region, enter a parameter


name and a value.

10. Select XML at the top of the editor window, toward the right hand
end. You should see an XML file somewhat like this:
1
2
3
4
5
6
7
8

5-2

<?xml version="1.0" encoding="UTF-8"?>


<web-app [...]>
<context-param>
<param-name>MyParameter</param-name>
<param-value>My Parameter Value</param-value>
</context-param>
<servlet>
<servlet-name>NewServlet</servlet-name>

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<servlet-class>sl314m5.lab.NewServlet</servlet-class>
<init-param>
<param-name>KeyName</param-name>
<param-value>Data value</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/PathToServlet/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

bl
a
r
fe

an
r
t
n

11. Examine the XML file and determine how a triggering URL is
matched to the servlet class that must run in response to that URL.

A
AK

UM

no
a
12. Examine the XML file and determine howhthe
askey-value pairs you
)
specified are represented. Note also m
how one e
couple
is associated
o
d
i
c
specifically with the servlet, while
the other
u is at almost the top level
o
G
o
t
of the XML structure and
is
outside
the
servlet
definition.
ah den
y
aj@ s Stu
w
i to Use the Configuration
rdServlet
h
t
a
Task Code the
h
se
b
t
u
n
Information
ka se to
a
enthe servlet source file, writing your code in the
(um1. licEdit

T
processRequest() method that has been added by NetBeans.

2.

Extract a reference to the ServletContext object.

Note If you want to know what methods are available directly on the
HttpServlet object, you can check the documentation, or simply type
this. in the editor and wait for NetBeans to prompt you with a list. You
should find the method needed to get the servlet init parameter very
easily.
3.

Store the servlet context in a variable.

Container Facilities For Servlets & JSPs


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

5-3

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1

Note To declare the variable of type ServletContext, you will need to


add an import. NetBeans will prompt you to do this using a little
lightbulb and red-ball icons in the left margin of the browser. Click that
icon and select the entry Add import for
javax.servlet.ServletContext.
4.

Using the servlet context reference, locate a method that you think
might provide access to a logging facility. Using this method, write a
message to the web-containers logging stream that indicates that the
servlet has been invoked and outputs the time of that invocation.

Note You can use message + new java.util.Date() to create a


message that includes the current date and time.

an
r
t
n

no
a
Note You will also find log methods defined a
servlet itself,
h onsthe
through the this reference.
)
om uide
c

o reference,
G determine how you can
o
5. Using the same servlet context
t
h
n
a
y uthat
obtain the context parameter
de you stored in the web.xml file.
@
j
t
Recall from the
that
S this is referred to in the APIs as an
walecture
s
i
d
r
initParameter.
As
before
NetBeans typing completion can be used
h
t
a
h
e
to help.
tb o us
n
a
t
k Output
6.
the key and value pair in a meaningful message to the log
e
a
s
en
(um licstream.

A
AK

UM

7.

Extract the value of the servlet initialization parameter. Notice that


this value is extracted directly from the HttpServlet object (this).

8.

Write the name and value of the parameter to the log stream.

9.

Create a minimal HTML page so that the servlet will generate some
visible output on the browser. Consider including the current date
and time here too.

Note If no output were created, the test of logging and parameter


handling would still work, however, it would be rather disturbing to have
zero output on the browser. This further demonstrates the usefulness of
the logging facility, as it allows you to see progress in a servlet or JSP even
when the application is malfunctioning

5-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Prepare the Index Page and Run the Application


1.

Edit the index.jsp file of the project. Create a link in it. That link
should jump to PathToServlet/blah.

2.

Run the program.

3.

Look at the GlassFish v3 Domain tabs. One shows the building and
deployment of the application. The other shows the output from the
logging requests.

4.

Determine that the key/value pairs in the logging output are correct.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Container Facilities For Servlets & JSPs


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

5-5

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

5-6

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 6

More View Facilities


Objectives
Upon completion of this lab, you should be able to:

Understand and use the four scopes

Understand and use the expression language, EL


Recognize and use the EL implicit objects

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

bl
a
r
fe

A
AK

UM

6-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will investigate EL implicit objects and the JSTL
forEach tag.

Preparation
No preparation is needed for this exercise.

Task List HTTP Headers

1.

Create a new Java Web project named SL314m06lab1.

2.

In the resulting index.jsp page, change the title and heading to


HTTP Headers

UM

6-2

an
r
t
n

no
a
3. Create a taglib directive to make the core JSTL
tag library available
hainsModule
with a prefix of c. Consult Tag Example
6, More View
)

m
e
o
Facilities, in the student guideif
cyou need
uida reminder of the syntax
o
G
for this.
o
ah dent
y
4. Prepare an unnumbered
uin the body of the document.
j@ list
t
a
S
dw thislist tags, place a c:forEach tag that will
5. Inside the runnumbered
a
h theselements
e
enumerate
of the HTTP headers array. Consult EL
b

t
u
n
Objects
in Module 6, More View Facilities, in the
to
kaImplicit
e
a
s
student
guide
if
you
need help in finding the header array.
m en
u
(
c
6. li Test the program (note that there is no servlet in this exercise).
T

A
AK

bl
a
r
fe

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 2

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 2
In this exercise, you will investigate using EL to access complex data
structures.

Preparation
No preparation is needed for this exercise.

Task

1.

Open the project named SL314m06lab2 and look at the classes


domain.Customer and domain.Address

bl
a
r
fe

ns
a
r
t
n2. Examine the launch page index.jsp, and the servetoclass
n
web.Controller, to determine the basic structure
a of the application.
s
a
Note that the application is missing the view
to
) h eCustomerView.jsp

m
which the controller servlet forwards.
co uid

o
3. Create the view class CustomerInfo.jsp.
o nt G Arrange that it displays
h
a
y uofdethe customer
the name and three addresses
@
j
a fors the
Stcustomer with the ID 1 (only one exists).
4. Test your application
w
i
d
r
th ways (syntactically) that you can access the
a
h
e
5. There
are
two
distinct
tbcustomer
usaddressesusing arrays or using the three distinct
n
o
three
a
t
ak fields.
seWhichever you used in step 3, modify your view to use the
m
n
u
e
(
licother approach, and retest your application.
T

A
AK

UM

More View Facilities


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

6-3

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

6-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 7

Developing JSP Pages


Objectives
Upon completion of this lab, you should be able to:

bl
a
r
fe

Describe the translation of a JSP to a Servlet

Understand the use of JavaBeans with jsp:useBean, setProperty,


and getProperty tags

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

7-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Exercise 1
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

In this exercise, you will investigate the compilation of JSPs to servlets.

Preparation
No preparation is needed for this exercise.

Task Investigate JSP Translation.


Create a new Java Web project, called SL314m07lab1.

2.

Add a little body text to the JSP.

3.

Run the project.

4.

Right click the JSP and select View Servlet from the pop-up menu.

an
r
t
n

no
a
has how
5. Examine the contents of the servlet, and) notice
it corresponds to

m
e
your original JSP.
o
c Guid
o
o
6. Make the following changes
t JSP, and with each change, reh to your
n
a
e
y
d servlet source again.
run the project, then
uthe
j@examine
t
a
S
w hisdeclaration for a private int variable.
a.
Add an
dinitialize
r
t
a
h
e
s
b. tb
Add a page
directive
to import java.util.*.
u
n
o
a
t
e an expression to output the result of doubling the private
ak c. nsAdd
m
u
e
(
lic int variable you added in step a above.
T

A
AK

bl
a
r
fe

1.

d.

Add code to iterate over the numbers 1 to 10, printing a


message as part of an unnumbered list each time round. Be sure
to use explicit curly braces for the loop boundaries.

e.

Edit the code from step d. above by removing the curly braces.
What happens now? Examine the generated servlet and
determine what went wrong.

UM

Note In step e above, NetBeans will complain of an error in the servlet


itself. Ignore this, and attempt to run the file regardless.

7-2

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 2

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 2
In this exercise, you will use the jsp:useBean, setProperty and
getProperty tags.

Preparation
No preparation is needed for this exercise.

Task Investigate the jsp:useBean Tag

UM

1.

Open the project called SL314m07lab2.

2.

Examine the index.jsp page. This contains a form that triggers the
setAddress.jsp page and submits five parameters to that page.

7.

Add an unnumbered list, and in it, print out each element of the
bean using the <jsp:getProperty tag.

8.

Create a second unnumbered list, and in it, print out each element of
the bean using scriptlet code. Recall from The useBean Tag on
page 7-26 of the student guide that the <jsp:useBean tag creates a
variable in the generated servlet code. That variable has the name
provided in the id element of the <jsp:useBean tag.

9.

Test your application and determine that the data are transferred
from the form into the bean and are then displayed by the
setAddress.jsp page.

an
r
t
n

no
a
3. Examine the class domain.Address. This isaassimple JavaBean that
hfieldnames declared in
holds address information. Notice that )the
m
e are identical.
the form and the attribute names
idBean
cofo the Java

u
o
o nt G
h
4. Create a new JSP, called a
setAddress.jsp.
e
y
j@ Stud to use the <jsp:useBean tag to
5. Add code to the a
setAddress.jsp
dw this
create a JavaBean.
r
a
h
se add code using the <jsp:setProperty tag to
bsetAddress.jsp
6. Innthe
t
u
tallo the fields of the addressBean directly from the input
kapopulate
e
a
s
If you are in doubt, refer to the section under the heading
en
(um licproperties.

The
setProperty
Tag on page 7-27 of the student guide.
T

A
AK

bl
a
r
fe

Developing JSP Pages


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

7-3

SOInfotech Pvt Ltd


Exercise 2

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Retrieve Session Information Using JSP Tags


1.

Create a new page called showAddress.jsp.

2.

Using elements of the showAddress.jsp page for assistance, create a


standalone page that shows the current values of a bean called
addressBean that is in the session scope. Note that this page will be
loaded by typing its URL directly. The goal is to demonstrate that the
bean created in the previous task is still accessible because it is in the
session scope.

3.

Test the page to show the values from the previous form submission.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

7-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Developing JSP Pages


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

7-5

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

UM

A
AK

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 8

Developing JSP Pages Using Custom Tags


Objective
Upon completion of this lab, you should be able to:

Use custom tags in creating a JSP

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

8-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Exercise 1
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

In this exercise, you will investigate the use of core JSTL tags.

Preparation
No preparation is needed for this exercise.

Task Investigate the c:out Core Tag.

A
AK

UM

Create a new Java Web project, called SL314m08lab1

5.

Surround each of these lines with a <c:out tag. Consult JSTL out
Tag on page 8-11 of the student guide for a reminder of the syntax.

6.

Run the application again and observe the behavior. Notice that the
default value of escapeXml is true, and this has created output
characters that present like the input text, even though they are not
achieved directly. You will see in Module 12, Implementing
Security that this can be a valuable tool in protecting against crosssite scripting attacks.

Task Investigate the c:remove Core Tag.


1.

8-2

bl
a
r
2. Into the index.jsp file, add a taglib directive for the core JSTL
fe
s
n
library. Refer to JSTL Functional Areas on page 8-13 in tthe
ra student
n
guide for details of the prefix and URI that are expected
no for this.
a
3. Create a paragraph in your JSP that contains
the following literal
has
text:
)
om uide
<script type=text/javascript>
c

o tG
o
alert(How annoying);
h
ya uden
</script>
@
j
a a sheading
<h1 this iswnot
St
i
d
r is that
X > Y...
th true & is the other true too?
a
h
e
tb theoerrors
us for now and run the application. Notice how the
4. Ignore
n
a
t
ak textnsiseinterpreted. Some of it disappears, and some behaves
m
e
(u licstrangely.

T
1.

Open the project SL314m08lab2. Examine the Address JavaBean


(this is the same one you have seen before).

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
2.

Into the index.jsp file, add a jsp:useBean directive to create an


instance of the Address bean in the session scope.

3.

Add a jsp:setProperty tag to set a literal value of 1234 Acacia


Gardens for the property address1 o f the bean.

4.

Add a jsp:getProperty tag to output the value of the address1


property (to prove that it is present and assigned).

5.

Run the application to demonstrate that the bean has been created
and the value assigned.

6.

Add the taglib directive to allow the use of the core tag library.

7.

After the value of the property has been printed out, add a c:remove
tag to remove the bean, then repeat the code you used to output the
value further up the file.

A
AK

bl
a
r
8. Run the application and demonstrate that the bean was removed,fe
ns
and therefore the attempt to output the value of the address
field
a
r
t
fails.
onn
a
s
a
) h e
m
co uid

o
o nt G
h
a
y ude
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

UM

Developing JSP Pages Using Custom Tags


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

8-3

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

8-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 9

More Controller Facilities


Objectives
Upon completion of this lab, you should be able to:

Understand fundamental concurrency problems

Add a filter to a servlet

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

9-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will demonstrate a problem that can arise in a
concurrency situation. The project simulates a very simple bank account,
modeling only the balance.

Preparation
No preparation is needed for this exercise.

Task Witness the Failure

bl
a
r
fe

an
r
t
n

Note Certain versions of Firefox browser will not operate correctly in


this task. The browser does not send concurrent requests to the same URL
from separate windows or tabs. An alternative browser is required for this
exercise.

no
a
has
)
om uide
c

o andt run
1. Open the project SL314m09lab1
G the project.
o
h
n
a
e deposit 100, then select
yDeposit
dand
2. In your browser, select
@
u
j
t
a s S50 from the account. Satisfy yourself that
Withdraw andwwithdraw
i the essential computation for this simulation.
d
r
h
t
a
the project
is capable
of
h
se
b
t
u
n
ka se to
a
Note e
n
The page will take about five seconds to load after you click
(umSubmit.
c
i

l
This is not because the simulation is particularly complex, but
T

A
AK

UM

9-2

you will examine the reason in Task 2.


3.

Open a second tab in your browser, and load the base page of the
application in that too. It should show the same balance that was left
after step two.

4.

Without clicking Submit yet in either tab, set one tab up to deposit
100 and the other to withdraw 200.

5.

In less than five seconds, click Submit on both tabs. When the pages
return, notice that each shows a balance that would have been
correct if the other operation had not occurred, but is wrong for the
aggregate of both operations.

6.

In either of the tabs, deposit a zero amount. Notice that the balance
shown is definitely wrong.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Examine the Cause of the Failure


1.

Open the domain.Account class in the NetBeans editor window.

2.

Observe that in the deposit and withdraw methods, the


computation consists of:
a.

Read the balance

b.

Modify the balance

c.

Store the new balance

This logic is correct, however, a delay has been deliberately added


after step a. this means that if two threads execute these methods
concurrently, each will start with the unmodified balance, and then
write it back. In effect, the last one to complete wins. This is called a
write-write conflict.

3.

Consider how you might fix this problem. Unfortunately, the


solution of removing the sleep, and of modifying the code to read
this.balance += amount does not solve the problem. It greatly
reduces the chance that you will see it, especially in a lab
environment with one user testing the code, but it is not a correct
solution. The problem remains that the execution of the += operator
still involves reading the value, modifying it, and then storing the
result. Although the time delay between the read and the write is
small, it is not zero.

no
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se variable data are shared between threads, this
b whenever
t
u
Inneffect,
to might arise. A full solution may often be achieved
kakind sofeproblem
a
en synchronization or database transactions, however, details of
(um licusing

N
KA

A
UM

an
r
t
n

these are beyond the scope of the class.

4.

Modify the methods deposit and withdraw by marking them


synchronized. Do not remove or alter any of the existing code.

5.

Run steps 3 and 4 from Task 1 above again. Notice this time that the
simulation takes longer to complete, but the answer is correct.

More Controller Facilities


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

9-3

SOInfotech Pvt Ltd


Exercise 2

Exercise 2
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

In this exercise, you will add a filter to an existing servlet.

Preparation
No preparation is needed for this exercise.

Task Examine the Starting Point.

A
AK

Open the project SL314m09lab2 and run the project.

to login to the ApplicationController. You might need to use the


following HTML tag to achieve this:
<input type=hidden name=operation value=Login/>

UM

9-4

bl
a
r
2. Select different operations and observe the applications behavior.
fe
s
n
tra
n
o
Task Install a Login Mechanism in thes Application
an
ha
)
om uidtoeattempt to read an
1. Add code to the ApplicationController
c

o session.
attribute user from the current
GSet the value found (or null
o
t
h
n
a
if not found) in an attribute
y uuser
dein the request scope.
@
j
t
S advertize.jsp pages to conditionally
2. Modify the quote.jsp
wa hisand
d
r
athe usere ift the user attribute is not null. Use the core JSTL
welcome
h
b
s

tlibraryotouprovide
tag
the conditional behavior for this.
n
a
t
k
a Create
3.
sea new JSP called login.jsp. This should collect a username
m
n
u
e
(
licon a form, and submit this along with the parameter operation set
T
1.

4.

Add a JSP called welcome.jsp. This should welcome the new user
and be the target of the controllers forwarding in the case that the
operation is Login.

5.

Modify the ApplicationController so that if the operation


parameter is login it creates an HttpSession, and embeds the
provided user name in that session.

6.

Test that the application now addresses a logged-in user by name.


You will need to navigate to the login.jsp page manually.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 2

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Install a Security Filter in the Application


1.

Create a ServletFilter, called SecurityFilter. Configure it to


intercept calls to the ApplicationController. As you go through
the wizard, select REQUEST for the Dispatch Conditions.

2.

Edit the template-generated filter:


a.

Delete the methods doBeforeProcessing and


doAfterProcessing.

b.

Delete everything in the doFilter method except for the call to


chain.doFilter.

c.

Delete the methods getFilterConfig and setFilterConfig.

d.

Delete the method toString.

e.

Delete the method sendProcessingError.

an
r
t
n

no
a
g. In the init method, delete everything except
s the line that stores
a
h
the filterConfig parameter in the
variable of the
) instance

m
e
same name.
o
c Guid
o
o
3. In the doFilter method,abefore
h ethentcall to chain.doFilter, add
y
code to do the following:
j@ Stud
a
a.
Determine
is operation to be performed is (use a
dwwhatththe
r
a
h
call).
b
se
request.getParameter(operation)
t
u
n
kab. sIfethetooperation is anything other than Quote, proceed to call
a
(um licen chain.doFilter and end processing in this doFilter method.

T
f.

N
KA

4.

A
UM

5.

Delete the method log.

For Quote operations only, proceed as follows:


a.

Determine if there is a session associated with this request, and


if so, determine if the session contains an attribute called user.

b.

If the user attribute exists and is not empty, processing


proceeds with the call to chain.doFilter.

c.

If the session does not exist, or if the user attribute does not
exist or is empty, processing proceeds by forwarding through a
RequestDispatcher configured to dispatch to the page
login.jsp.

Run the program and verify:


a.

Any user, regardless of whether they are logged in or not, can


log in, and can access the advertisement.

More Controller Facilities


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

9-5

SOInfotech Pvt Ltd


Exercise 2

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

b.

When an attempt is made to get a Quote, this is successful only


if the user has logged in already. Otherwise, the request results
in a redirection to the login page.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

9-6

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

More Controller Facilities


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

9-7

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

UM

A
AK

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 10

More Options for the Model


Objective
Upon completion of this lab, you should be able to:

Create applications that use Java Persistence API for persistent


storage

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

10-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will create a simple database application that
provides a list of songs.

Preparation
No preparation is needed for this exercise.

Task Create a New Project and an Entity.

1.

Create a new project called SL314m10lab1.

2.

Create a new Entity:

UM

10-2

an
r
t
n

no
a
b. In the package entity.
has
)
m ide
c. With a Primary Key Type ofco
Long.

u
ofor thet G
o
d. Create a Persistence
Unit
entity.
Use the default name,
h
n
a
e
y
the default provider,
d source jdbc/__default, the
udata
j@andSthe
t
a
transaction
API,
a
generation
strategy of Create.
w his
d
r
t for String artist, and String songName.
a to theeentity
h
3. Add b
fields
s

u get and set methods for these. Be sure to annotate


nt simple
Provide
o
a
t
k
a thenfields
se using the @Column .
m
u
e
(
lic
T
a.

A
AK

bl
a
r
fe

Called Song.

Task Create a controller


1.

Create a servlet called Controller, in the package web.

2.

In the controller, extract a parameter from the request called


operation. This value should be one of list or add. Based on this
operation the controller should either list all the songs in the
database, or add a new one.

3.

Arrange for the servlet to have use of two injected resources. These
will be provided using the annotated variable declarations
@PersistenceContext EntityManager em;
and
@Resource UserTransaction utx;

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
4.

To implement the list operation, look at the example in Java


Persistence API Example on page 10-27 of the student guide.
Assuming you have an entity manager variable called em, you can
use this call to create a list of the results:
em.createQuery(select s from Song s).getResultList()

5.

To implement the add operation, the controller should expect two


additional parameters to the HTTP request, these will be artist and
song. Use these to create and initialize a new Song object, then begin
a user transaction, persist the new Song, and commit the user
transaction.

6.

Regardless of the operation invoked, the controller should forward


to a JSP called ListSongs.jsp, and should provide an attribute in
the request scope that carries the songs that should be displayed.

Task Create JSPs

no
a
1. Create a JSP called AddSong.jsp that includes
The form
as a form.
hTitle.
should have two fields: Artist and Song
When
submitted,
)

m
e
o
this JSP should trigger the add operation
c Guinidthe controller servlet.
o
o
2. Create a JSP called ListSongs.jsp.
ah dentThis should show the list of
y
songs created by the
controller
tu and be the target of the redirection
aj@
S
w
from the controller
after
each
d this operation. The servlet should include a
r
a
button labeled
Refresh
h
e that triggers the controllers list action.
b
s

t
u
n totuse
o the JSTL core tag library to create this JSP, as you will
3. ka
Expect
e
a
s
en to iterate over the elements of the List that is passed to the page
(um licneed

by the controller.
T

A
AK

UM

an
r
t
n

Task Test the Application


1.

Test the application by adding a few songs and ensuring that the list
of songs grows with each new addition.

Task Optional: Add Edit, Delete, and Find Operations


1.

Should you have spare time after finishing this lab, try adding
additional functions to complete the database set.

More Options for the Model


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

10-3

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

!
?

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

10-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 11

Asynchronous Servlets and Clients


Objectives
Upon completion of this lab, you should be able to:

Create servlets that use the asynchronous model

Create web pages that use asynchronous JavaScript updates

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

11-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will create a servlet that generates delayed responses
using the asynchronous servlet API and asynchronous JavaScript
techniques.

Preparation
No preparation is needed for this exercise.

Task Create a New Project and Asynchronous


Servlet

ns
a
r
t
1. Create a new project named SL314m11lab1. In the project
n- create a
o
n
servlet called Update in the package web.
a
s
a
h Do this using the
2. Set the servlet to support asynchronous) operation.
m
element asyncSupported = true
annotation.
ide
coin theu@WebServlet

o
o nt G method.
3. Delete the contents of the
processRequest
h
a
y ude
@
j
4. In the now-empty
processRequest
method:
a s St
w
i
rd asynchronous
h
a.
Start
the
processing and keep a handle on the
t
a
h
e
b
s

AsyncContext
in
a
final
variable.
t
u
n
o
a
t
e
ak b. nsConsult
the sample code Simple Asynchronous Client
m
u
e
(
lic Example on page 11-10 of the student guide for more guidance
T

N
KA

UM

11-2

on these steps.

5.

Create an anonymous inner class, implementing the Runnable


interface. In the run method of this class:
a.

Extract the request and response objects from the


AsyncContext and store them in local variables.

b.

Introduce a delay between 2 and 15 seconds.

c.

Select a word from this list at random:


wonderful, unexpected, strange, elegant
(you can add more adjectives if you choose, they will simply be
used to construct a changing random remark). Return the
chosen word as the entire body of the response (do not include
any HTML tags whatsoever).

d.

Call the complete method on the AsyncContext.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6.

Test the code. Run the application. To do this, build and deploy the
application, and then enter the URL:
http://localhost:8080/SL314m11lab1/Update directly into the
browsers URL window.

Task Create an Asynchronous Client


Edit the index.jsp file and the following text just after the top-level
heading (</h1>):
<p>Oh my, that was... <span id=adjective>let me
think...</span>!</p>

2.

Create a JavaScript block, after the end of the </body> tag. The script
opening and closing tags are exemplified inSimple Asynchronous
Client Example on page 11-10 of the student guide.

bl
a
r
fe

ns
a
r
t
3. In the JavaScript block, add the following elements. Refer
again to
onof-the student
Simple Asynchronous Client Example on page 11-10
n
a syntax.
guide if you need hints or guidance on the a
JavaScript
s
h
)variables
a.
Add variable declarations for two
m
o uide called req and
c

toUpdate.
o tG
o
h
b. Use the document.getElementById
method to obtain a
ya uden
@
j
t
reference toa
the adjective
span
that
was created in step one of
S
w
s
i
d
this a
task.
r
th
h
e
b
s req variable using either a new XMLHttpRequest,
c.ntInitialize
uthe
o
a
t
ak nsorea new ActiveXObject, depending on the browser support.
m
(u licd.e Declare a function called sendRequest().

A
AK

1.

e.

In the sendRequest() function, install a readystatechange


handler. In the handler, when a successful response is received,
update the innerHTML element of the toUpdate variable using
the responseText of the request.

f.

After the declaration of the readystatechange handler, call the


open and send methods on the req object to send the HTTP
request to the server. The request should send a GET request, to
the URL Update.

g.

Close the definition of the sendRequest method, then call the


sendRequest method directly.

UM

Asynchronous Servlets and Clients


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

11-3

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Test the Application.


1.

Run the application.

2.

The page should be displayed and show text that says


Oh my, that was... let me think...!

3.

After a few seconds, the text let me think... should change, and
continue changing at variable intervals of a few seconds.

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

11-4

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Asynchronous Servlets and Clients


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

11-5

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

UM

A
AK

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Lab 12

Implementing Security
Objectives
Upon completion of this lab, you should be able to:

Restrict access to regions of your web application to validated users

Enforce an SSL-encrypted connection to a GlassFish-hosted website

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

12-1
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
In this exercise, you will use role based security to restrict access to
elements of a web application.

Preparation
No preparation is needed for this exercise.

Task Verify the Project Prior to Adding Security

bl
1. Open the project SL314m12lab1 and run it. This is essentially theera
sf the
same as Lab 9, but without the filter. Verify that you can get to
all
n
a
-tr
pages, and can log in or not as you choose.
n
o
n
a
as
h
)
Task Configure Users in the GlassFish
m ide Server
o
c
Gu
o
o
1. Select the Services tab (second
ntot the right of the Projects tab, at
ah dtab
e
y
the top left of the jNetBeans
u
a @ s Stwindow).
w
ielement and right click the GlassFish Domain.
2. Open theaServers
rd tree
h
t
h
Select
se Console from the popup menu.
bView Admin
t
u
n
kaWhensethetoadmin console starts in your web browser, open the Tree
3.
a
enthe left side of the window. Find the hierarchy: Common Tasks >
(um licon

Configuration > Security > Realms > file, and click the file element.
T

A
AK

UM

4.

The right hand pane shows the page Edit Realm. Click the button
Manage Users just below this title.

5.

Click the New button to add a user. Add the User IDs Alice and
Maverick in each case, use the User ID (with the same capitalization)
as the password.

Task Assign Users to Roles

12-2

1.

In the Projects tab, open the tree SL314m12lab1 > Web Pages > Web
Inf. Right-click the sun-web.xml file and select edit.

2.

In the editor pane at the right, select the Security tab and click the
button at the right Add Security Role Mapping.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise 1
3.

Edit the field Security Role Name which currently contains the text
role1 and change the role name to Users.

4.

Click the button Add Principal and enter the user name Alice then
click OK.

5.

Type Control-S to save the file.

Task MandateLogin Before Access


1.

Right click on the project, and select New > Standard Deployment
Descriptor (web.xml).

an
r
t
n

UM

no
a
2. Select the Security tab, then open the Login Configuration
element
s
a
h
and select the radio button for Basic. )
ebutton, and enter
omtheuiAdd
d
c

3. Open the Security Roles element,


click
o tG
Users, then click OK. aho
y uden
@
j
t element (click the Add Security
4. Open the Security
S
wa Constraints
s
i
d
Constraint rbutton).
Enter
a
resource
name (TheConstraint is fine).
h
t
a
h
se located just under the Name column heading
bthe Addubutton
5. Click
t
n
toResource Collection block. In the dialog box that pops up,
kain thesWeb
e
a
en a resource name (MyResource will serve), then enter the URL
(um licenter

Pattern /ApplicationController. Ensure that All HTTP methods is


T

A
AK

selected and then click OK.

6.

Check the checkbox Enable Authentication Constraint, then click the


Edit button to the right of Role Name(s). Select the role Users and
click the Add > button. Click OK.

Task Run the Application and Verify Login


Requirement
1.

Run the program, and verify that before you can reach either the
Quote or Advertisement pages, you are forced to log in as Alice. You
should be rejected from the pages if you login as Maverick, since this
user was not added to the Users role.

Implementing Security
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

bl
a
r
fe

Note If this element isnt visible on the menu, select other from the
bottom of the list, then select Web and the Standard Deployment
Descriptor element will be the last entry in the list on the right hand side.

12-3

SOInfotech Pvt Ltd


Exercise 1

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Task Pick Up the Username from the Environment


1.

Edit the Application Controller servlet so that it does not look for a
username in the parameters, and does not provide a login operation

2.

In place of the old mechanism you just removed, extract the user
name from the Principal object that can be found from the
request.

Task Modify the Application to Use Form-based login


1.

1.

To this point, there has been no proper way to logout once you are
logged in. To provide for this, add a new operation Logout to the
ApplicationController servlet. When invoked, this should invoke
the method session.invalidate(), and dispatch back to the
index.jsp page.

2.

Add another option Logout to the index.jsp page.

3.

Test that the application now allows a user-controlled logout


operation.

UM

12-4

bl
a
r
fe

ns
a
r
t
n- submit and
2. Arrange two buttons on the form. One should be of o
type
n
labeled Login. The other should be of type resetaand labeled Clear.
has
3. Edit the web.xml file. Change the Login
Configuration
from Basic to
)
m
e
o
Form. In both the fields for Form
Page
id and Form Error Page,
cLogin
u
o
G
o
enter login.jsp
ah dent
y
4. Test that the application
now
tuuses the form you created for login,
aj@are
S
w
and that failed
logins
also
directed to the same login page.
d this
r
a
h
b
se

t
u
n
a e toa Logout Mechanism
kProvide
Task

a
m ens
u
(
lic
T

A
AK

Edit the login.jsp form that will be used to prompt for user login.
This should submit to the action j_security_check. The user name
field must be called j_username. Create a password field, which
must be called j_password.

Web Component Development With Servlet and JSP Technologies


Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

SOInfotech Pvt Ltd


Exercise Summary

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Exercise Summary

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.

Experiences

Interpretations

Conclusions

Applications

bl
a
r
fe

an
r
t
n

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

A
AK

UM

Implementing Security
Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D

12-5

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

SOInfotech Pvt Ltd

bl
a
r
fe

an
r
t
n

UM

A
AK

n
a
has
)
om uide
c

o tG
o
h
ya uden
@
j
a s St
w
i
d
r
h
t
a
h
se
b
t
u
n
ka se to
a
(um licen

Potrebbero piacerti anche