Lt 1 2 S l t Lecture 12: Servlets

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

13 Νοε 2013 (πριν από 4 χρόνια και 1 μήνα)

101 εμφανίσεις

CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 1
L t 12 S l t
L
ec
t
ure
12
:
S
erv
l
e
t
s
CSIE33000
N t k P i i
N
e
t
wor
k

P
rogramm
i
ng
i
n
Java
Motivation

HTML alone can only be used to create static
Web pages
Web

pages
.

Increasing number of applications need
dynamic Web pages.

Results of a real-time, online survey.
Results of a search operation
CSIE33000 Network Programming

Results

of

a

search

operation
.

Contents of an electronic shopping cart.

Java servlets are to the rescue.
Servlets 2
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 2
Servlet Basics

A servlet is a program written in Java that runs on a
Web server.

It is executed in response to a client’s HTTP request
and creates a document (HTML) to be returned.

It extends the functionality of the server.

All major Web servers now support servlets.
Note that
servlet
API is not part of J2SE but a part of

Note

that

servlet
API

is

not

part

of

J2SE

but

a

part

of

J2EE.

You must download an implementation of the servlet
API for J2SE.
CSIE33000 Network Programming Servlets 3
Setting up the Servlet API

The official Reference Implementation of the
Servlet
A
PI is
Ap
ache Tomcat.
p

Go to http://tomcat.apache.org/
to download
and install the Tomcat server.

Set JAVA_HOME env var to J2SE folder.

Set CATALINA_HOME env var to
y
our Tomcat
y
folder.

Add servlet-api.jar (in lib) to your CLASSPATH.

Add the bin folder of Tomcat to your PATH.
CSIE33000 Network Programming Servlets 4
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 3
Setting up the Servlet API

Execute the startup command (in a
command window
)
. This will startu
p
the
) p
Tomcat server.

In a browser, type http://localhost:8080
to
test if the Tomcat server is installed properly

To stop Tomcat, execute the shutdowm
d (b i
h d
)
comman
d

(b
etter rename
i
t to s
h
ut
d
owntc
)
.

For all our examples, Tomcat server will be
assumed.
CSIE33000 Network Programming Servlets 5
Creating a Web Application

Two possible methods for creating Web app:

Make use of the existing ROOT application (below
b
f ld i th T t f ld )
we
b
apps
f
o
ld
er
i
n
th
e
T
omca
t

f
o
ld
er
)

Create your own application at the same level as
ROOT, providing a similar folder structure.

The main part of ROOT folder is:
ROOT->WEB-INF->classes
To create a Web application called
mywebapp

To

create

a

Web

application

called

mywebapp
,
create a similar folder structure under webapps,
i.e.
mywebapp-> WEB-INF->classes
CSIE33000 Network Programming Servlets 6
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 4
Creating a Web Application

Place HTML files and JSPs (covered in next
lecture
)
within m
y
weba
pp
.
)
y pp

Place servlets within mywebapp\WEB-
INF\classes. If packages are used, must have a
folder structure here to reflect this.

Create a file called web.xml (the deployment
descriptor) within WEB-INF to specify details of
the Web application. Must contain <servlet>
and <servlet-mapping> for each servlet.
CSIE33000 Network Programming Servlets 7
The Deployment Descriptor

Assume a Web app containing a single
servlet called FirstServlet. A sam
p
le
p
deployment descriptor is shown below:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
CSIE33000 Network Programming Servlets 8
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 5
The Deployment Descriptor
<servlet>
<servlet-name>FirstServlet</servlet-name>
l t
l
Fi tS l t
/
l t
l
<serv
l
e
t
-c
l
ass>
Fi
rs
tS
erv
l
e
t
<
/
serv
l
e
t
-c
l
ass>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
/
l t
i
<
/
serv
l
e
t
-mapp
i
ng>
</web-app>

Note that you need to do the same thing for
each servlet added to your repository.
CSIE33000 Network Programming Servlets 9
URL of a Servlet

A servlet is usually called from a HTML page.

﹯ﱹ  
﵌ 
ﱷ 



﹯ﱹ





﵌








 

﵅d 異復數﹧若  イ
 若 ACTION attribute specifying
the URL address of the servlet.

The URL of a servlet has the format:
http://localhost:8080/<WebAppName>/<ServletName
>

For example
http://localhost:8080/mywebapp/FirstServlet
CSIE33000 Network Programming Servlets 10
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 6
Invoking a Servlet

The servlet above may be invoked via the
ACTION attribute of a FORM tag in a HTML page
as follows:
<FORM METHOD=GET ACTION=“FirstServlet”>

Note that the URL for the servlet is relative to
the Web application that contains both servlet
and HTML pages.
and

HTML

pages.

Open the page directly won’t work. Use
http://localhost:8080/mywebapp/FirstServlet.html
to open the Web page
CSIE33000 Network Programming Servlets 11
A Sample Web Page
(FirstServlet.html)
<HTML>
<HEAD>
<TITLE>A First
Servlet
</TITLE>
<TITLE>A

First

Servlet
</TITLE>
</HEAD>
<BODY>
<BR><BR><BR>
<CENTER>
<FORM METHOD=GET ACTION="FirstServlet">
<INPUT TYPE
="
Submit
"
VALUE
="
Click me!
"
>
<INPUT

TYPE Submit

VALUE

Click

me!>
</FORM>
</CENTER>
</BODY>
</HTML>
CSIE33000 Network Programming Servlets 12
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 7
Servlet Structure

Servlets must import javax.servlet and
javax.servlet.http, and java.io, of course.

Servlets that use HTTP must extend HttpServlet
from javax.servlet.http

The most common HTTP requests are GET and
POST.

At the servlet end, method service will dispatch
ith
d G t
d P t
i t th
e
ith
er
d
o
G
e
t
or
d
o
P
os
t
i
n response
t
o
th
e
requests.

The programmer should override at least one of
these two methods.
CSIE33000 Network Programming Servlets 13
Servlet Structure

In general, use POST for multiple data items
and either GET or POST for single item.

All three (service, doGet, doPost) return void
and take two arguments:

An HttpServletRequest object;

An HttpServletResponse object.

  ヲ ョ
「
  キ



ﵥ、



ョ

「




﹯

void setContentType(String) — set data type of
response, normally “text/HTML”

PrintWriter getWriter() — to write data to client
CSIE33000 Network Programming Servlets 14
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 8
4 Basic Steps in a Servlet
1.
Execute setContentType(“text/HTML”)
2
Execute
getWriter
to generate
PrintWriter
obj
2
.
Execute

getWriter
to

generate

PrintWriter
obj
3.
Retrieve any parameter(s) from the initial
Web page.
4.
Use the println to create elements of the
Web page to be

served up

by our Web
Web

page

to

be

served

up

by

our

Web

server.

Normally carried out by doGet or doPost

Generate IOException and ServletException
CSIE33000 Network Programming Servlets 15
FirstServlet.java (1)
import java.io.*;
import javax.servlet.*;
i t
j l t htt
*
i
mpor
t

j
avax.serv
l
e
t
.
htt
p.
*
;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
Htt S l tR
)
Htt
p
S
erv
l
e
tR
esponse response
)
throws IOException,ServletException
{
response.setContentType("text/HTML");
CSIE33000 Network Programming Servlets 16
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 9
FirstServlet.java (2)
PrintWriter out = response.getWriter();
out.println("<HTML>");
t i tl
("HEAD")
ou
t
.pr
i
n
tl
n
("
<
HEAD
>
")
;
out.println("<TITLE>Simple Servlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><BR>");
out.println("<CENTER><H1> A Simple Servlet </H1></CENTER>");
out println
(
"
</BODY>
"
);
out
.
println
( </BODY> );
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 17
Testing a Servlet (1)

If not already running the Tomcat server,
execute startu
p
.
p

Assuming the Web page FirstServlet.html, we
can use the browser and enter the address
http://localhost:8080/FirstServlet.html

You should be able to see the following
output screens.
CSIE33000 Network Programming Servlets 18
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 10
Testing a Servlet (2)
CSIE33000 Network Programming
Servlet 19
Testing a Servlet (3)
CSIE33000 Network Programming
Servlets 20
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 11
Passing Data

Lets modify the form as follows:
<FORM METHOD=GET ACTION="PersonalServlet">
Enter your first name:
<INPUT TYPE="Text" NAME="FirstName" VALUE="">
<BR><BR>
<INPUT TYPE="Submit" VALUE="Submit">
</FORM>

T
he form will accept the user’s first name
and pass it to the servlet which can access
the data for processing.
CSIE33000 Network Programming Servlets 21
Getting Client Data

HttpServletRequest has many methods for
p
rocessin
g
client data:
p g

String getParameter(String <name>) — returns
the value of a single parameter

Enumeration getParameterNames() — returns
the names of all parameters

﹧ﭝ ﱵ葉 ﹡ﵥ︩


﹧ﭝ

ﱵ葉

ﱮ

ﱵ ﵥ
ﵯ︠ョﱵ
聾ァﵭ葉 ﱥ
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 12
PersonalServlet.java (1)
import java.io.*;
import javax.servlet.*;
i t
j l t htt
*
i
mpor
t

j
avax.serv
l
e
t
.
htt
p.
*
;
public class PersonalServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
Htt S l tR
)
Htt
p
S
erv
l
e
tR
esponse response
)
throws IOException,ServletException
{
response.setContentType("text/HTML");
CSIE33000 Network Programming Servlets 23
PersonalServlet.java (2)
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.
p
rintln
(
"<HEAD>"
);
p
( );
out.println("<TITLE>Simple Servlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><BR>");
String name = request.getParameter("FirstName");
out.println("<CENTER><H1> A Simple Servlet for " + name
+ "</H1></CENTER>");
t i tl
("</BODY>")
ou
t
.pr
i
n
tl
n
("</BODY>")
;
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 24
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 13
PersonalServlet Execution
CSIE33000 Network Programming
Servlet 25
PersonalServlet Execution
CSIE33000 Network Programming
Servlets 26
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 14
Forced Reload

To have the Web page reload every time it is
accessed
(
such as a ‘Back’ button
)
:
( )
<META HTTP-EQUIV="Pragma" CONTENT="no cache">
<META HTTP-EQUIV="Cache-control" CONTENT="no cache">
<META HTTP-EQUIV="Expires" CONTENT="0">

These should be placed immediately after the
<HEAD> tag.
<HEAD>

tag.

What would happen if we don’t reload? Give
it a try!
CSIE33000 Network Programming Servlets 27
Example with More Data
<!-- SimpleAdder.html -->
<HTML>
<HEAD>
<META HTTP-EQUIV="ContentType" CONTENT="text/HTML">
<META HTTP-EQUIV ="Pragma" CONTENT="no cache">
<META HTTP-EQUIV ="Cache-control" CONTENT="no cache">
<META HTTP-EQUIV ="Expires" CONTENT="0">
<TITLE>Simple Adder</TITLE>
<HEAD>
<BODY>
<CENTER>
<CENTER>
<FORM METHOD=POST ACTION="AdderServlet">
<TABLE>
<TR>
<TD>First number</TD>
<TD><INPUT TYPE="Text" NAME="Num1" VALUE="" SIZE=5></TD>
</TR>
CSIE33000 Network Programming Servlets 28
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 15
Example with More Data
<TR>
<TD>Second number</TD>
<TD><INPUT TYPE="Text" NAME="Num2" VALUE="“
SIZE=5></TD>
</TR>
</TABLE>
<BR><BR><BR>
<INPUT TYPE="Submit" VALUE = "Submit"></TD>
<INPUT TYPE="Reset" VALUE="Clear"></TD>
</FORM>
</CENTER>
</BODY>
</HTML>
CSIE33000 Network Programming Servlets 29
AdderServlet.java (1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AdderServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
try {
String value1 = request.getParameter("Num1");
String value2 = request.getParameter("Num2");
int
num1 =
Integer parseInt
(value1);
int
num1

=

Integer
.
parseInt
(value1);
int num2 = Integer.parseInt(value2);
int sum = num1 + num2;
sendPage(response, "Result = " + sum);
}
CSIE33000 Network Programming Servlets 30
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 16
AdderServlet.java (2)
catch(NumberFormatException cnfEx)
{
sendPa
g
e
(
res
p
onse
,
"*** Invalid entr
y
! ***"
);
g
( p,y );
}
}
private void sendPage(HttpServletResponse reply, String result)
throws IOException
{
reply.setContentType("text/HTML");
PrintWriter out = reply.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Result</TITLE>");
CSIE33000 Network Programming Servlets 31
AdderServlet.java (3)
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><BR>");
out.println("<CENTER><H1>" + result
+ "</H1></CENTER>");
out.println("</BODY>");
out println
(
"
</HTML>
"
);
out
.
println
( </HTML> );
out.flush();
}
}
CSIE33000 Network Programming Servlets 32
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 17
AdderServlet Execution
CSIE33000 Network Programming
Servlets 33
AdderServlet Execution
CSIE33000 Network Programming
Servlet 34
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 18
Sessions (1)

HTTP is a stateless protocol.

ﵡﹹ 北說ﹳ ﹥

葉說 



ﵡﹹ

北說ﹳ

﹥


葉說





ー﹧

Java servlets support the session concept.

A session is a container to store a client's
activities for accessed by the servlets that have
access to the session ob
j
ect.
j

The session expires automatically after a
timeout (30m for Tomcat) has elapsed or
invalidated explicitly by the servlet (by execution
of method invalidate()).
CSIE33000 Network Programming Servlets 35
Sessions (2)

A session object is created by the getSession
method of the Htt
p
ServletRe
q
uest class.
p q

HttpSession getSession()

HttpSession getSession(boolean create)

w/o arg or true arg, returns the current session
if exists; otherwise, create a new one
HttpSession cart=request.getSession();

With false arg, the current session is returned if
exists; but null is returned otherwise.
CSIE33000 Network Programming Servlets 36
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 19
Session Object

A session object contains a set of name-value pairs.

Name is of type String. Value is of type Object.

Ob
j
ects added to a session must implement the
Serializable interface.

A pair can be added by
void setAttribute(String <name>, Object <val>)

Example
String
String

currentProduct=request.getParameter("Product");
HttpSession cart = request.getSession();
cart.setAttribute("currentProd",currentProduct);
CSIE33000 Network Programming Servlets 37
Manipulating Session Obj

To remove an item, use
Object removeAttribute(String <name>)
eg. cart.removeAttribute(currentProduct);

To retrieve a value, use
Object getAttribute(String <name>)
eg. String product =
(
Strin
g)
cart.
g
etAttribute
(
“currentProd”
);
( g)
g
(
);

To get a list of all named values, use
String[] getAttributeNames()
eg. String[] prodName = cart.getAttributeNames();
CSIE33000 Network Programming Servlets 38
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 20
Shopping Cart Example

The user may place a weight of apples
and
/
or a wei
g
ht of
p
ears.
T
hree servlets:
/g p

Selection (of apples/pears)

Weight (to be entered)

Checkout

If one servlet needs to transfer exec to
th th th d
dR di t
f l
ano
th
er,
th
e me
th
o
d
sen
dR
e
di
rec
t
o
f
c
l
ass
HttpServletResponse may be used.
CSIE33000 Network Programming Servlets 39
ShoppingCart.html (1)
<HTML>
<HEAD>
<META HTTP
EQUIV"
Pragma
"CONTENT"no cache">
<META

HTTP
-
EQUIV
=
"
Pragma
"

CONTENT
=
"no

cache">
<META HTTP-EQUIV ="Cache-control" CONTENT="no cache">
<META HTTP-EQUIV ="Expires" CONTENT="0">
<TITLE>Shopping Cart</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1><FONT COLOR="red">Simple Shopping Cart</FONT></H1>
<BR><BR><BR><BR><BR>
<FORM METHOD=POST ACTION="Selection">
CSIE33000 Network Programming Servlets 40
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 21
ShoppingCart.html (2)
<TABLE>
<TR>
<TD><INPUT TYPE=
"
Radio
"
NAME=
"
Product
"
VALUE =
"
Apples
"
<TD><INPUT

TYPE= Radio

NAME=
Product

VALUE

=

Apples

CHECKED>
<FONT COLOR="Blue">Apples</FONT></TD>
</TR>
<TR>
<TD><INPUT TYPE="Radio" NAME="Product" VALUE = "Pears">
<FONT COLOR="Blue">Pears</FONT></TD>
</TR>
</TR>
<TR>
<TD><INPUT TYPE="Radio" NAME="Product" VALUE = "Checkout">
<FONT COLOR="Red">Go to checkout</FONT></TD>
</TR>
</TABLE>
CSIE33000 Network Programming Servlets 41
ShoppingCart.html (3)
<BR><BR><BR>
<INPUT TYPE="Submit" VALUE="Submit">
</FORM>
</CENTER>
</BODY>
</HTML>
</HTML>
CSIE33000 Network Programming Servlets 42
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 22
ShoppingCart App
CSIE33000 Network Programming
Servlet 43
Selection.java (1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Selection extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
String currentProduct = request.getParameter("Product");
HttpSession cart = request.getSession();
cart.setAttribute("currentProd", currentProduct);
if (currentProduct.equals("Checkout"))
response.sendRedirect("Checkout");
else
sendPage(response, currentProduct);
}
CSIE33000 Network Programming Servlets 44
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 23
Selection.java (2)
private void sendPage(HttpServletResponse reply, String product)
throws IOException {
re
p
l
y
.setContentT
yp
e
(
"text
/
HTML"
);
p y yp
(/);
PrintWriter out = reply.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>" + product + "</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
out.println("<H1><FONT COLOR=Red>" + product + "</FONT></H1>");
out.println("<BR><BR><BR>");
out.println("<FORM METHOD=POST ACTION='Weight'");
CSIE33000 Network Programming Servlets 45
Selection.java (3)
out.println("<TABLE>");
out.println("<TR>");
out.println(" <TD>Quantity required (kg)");
out.println(
" <INPUT TYPE='Text' NAME='Qty'
VALUE='' SIZE=5></TD>");
t i tl
("/TR")
ou
t
.pr
i
n
tl
n
("
<
/TR
>
")
;
out.println("</TABLE>");
out.println("<BR><BR><BR>");
CSIE33000 Network Programming Servlets 46
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 24
Selection.java (4)
out.println("<TABLE>");
out.println("<TR>");
t i tl
(
ou
t
.pr
i
n
tl
n
(
" <TD><INPUT TYPE='Radio'NAME='Option'VALUE='Add'
CHECKED>");
out.println(" <FONT COLOR=blue> Add to cart.</FONT></TD>");
out.println("</TR>");
out.println("<TR>");
out.println(
" <TD><INPUT TYPE='Radio' NAME='Option'
VALUE='Remove'>");
out.println(
" <FONT COLOR=blue> Remove item from
cart.</FONT></TD>");
out.println("</TR>");
CSIE33000 Network Programming Servlets 47
Selection.java (5)
out.println("<TR>");
out.println(
" <TD><INPUT TYPE='Radio' NAME='Option' VALUE='Next'>");
out.println(
" <FONT COLOR=blue> Choose next item.</FONT></TD>");
out.println("</TR>");
out.println("<TR>");
out.println(
" <TD><INPUT TYPE='Radio' NAME='Option' VALUE='Checkout'>");
out.println(" <FONT COLOR=blue> Go to checkout.</FONT></TD>");
out println
(
"
</TR>
"
);
out
.
println
( </TR> );
out.println("</TABLE>");
out.println("<BR><BR><BR>");
CSIE33000 Network Programming Servlets 48
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 25
Selection.java (6)
out.println(
"<INPUT TYPE='Submit' VALUE='Submit'>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 49
Request Dispatching

An alternative to sendRedirect is to create a
Re
q
uestDis
p
atcher ob
j
ect and call its forward
q p
j
method.
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("Checkout");
requestDispatcher.forward(request, response);
CSIE33000 Network Programming Servlets 50
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 26
After selecting Apples
CSIE33000 Network Programming
Servlet 51
Weight.java (1)

In the Apples page, when a weight is entered and a
selection is made, the ‘Submit’ button will transfer
h
h
l
t
h
e execution to Wei
gh
t serv
l
et.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class
Weight
extends
HttpServlet
{
public

class

Weight
extends

HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException
{
CSIE33000 Network Programming Servlets 52
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 27
Weight.java (2)
HttpSession cart = request.getSession();
String currentProduct = (String)cart.getAttribute("currentProd");
String choice = request.getParameter("Option");
if (choice.equals("Next"))
response.sendRedirect("ShoppingCart.html");
if (choice.equals("Checkout"))
response.sendRedirect("Checkout");
if (
h i l
("dd"))
if

(
c
h
o
i
ce.equa
l
s
("
A
dd"))
{
doAdd(cart,request);
response.sendRedirect("ShoppingCart.html");
}
CSIE33000 Network Programming Servlets 53
Weight.java (3)
if (choice.equals("Remove"))
//Not really possible for it to be anything else, but play safe!
{
{
doRemove(cart);
response.sendRedirect("ShoppingCart.html");
}
}
private void doAdd(HttpSession cart,HttpServletRequest request)
{
Strin
g
currentProduct = (Strin
g
)cart.
g
etAttribute("currentProd");
String qty = request.getParameter("Qty");
if (qty!=null)
cart.setAttribute(currentProduct, qty);
}
CSIE33000 Network Programming Servlets 54
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 28
Weight.java (4)
private void doRemove(HttpSession cart) {
String currentProduct =
(String)cart.getAttribute("currentProd");
Object product =
cart.getAttribute(currentProduct);
if (product!=null)
ca t emo eAtt ib te(c entP od ct)
ca
r
t
.r
emo
v
eAtt
r
ib
u
te(c
urr
entP
r
od
u
ct)
;
}
}
CSIE33000 Network Programming Servlets 55
Chceking Out

Once all product selections have been made
and the ‘Checkout’ o
p
tion has been taken
,

p,
the Checkout servlet will be executed.

To print out the final costs, we need to
format decimal output.

This can be done with the format method of
h
P i W i
l
t
h
e
P
r
i
nt
W
r
i
ter c
l
ass.
CSIE33000 Network Programming Servlets 56
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 29
Checkout.java (1)
import java.io.*;
import javax.servlet.*;
im
p
ort
j
avax.servlet.htt
p
.*
;
p
j p
;
import java.util.Enumeration;
public class Checkout extends HttpServlet
{
private final float APPLES_PRICE = 1.45F;
private final float PEARS_PRICE = 1.75F;
//In a real application, above prices would be retrieved
//from a database of course
//from

a

database
,
of

course
.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException
{
CSIE33000 Network Programming Servlets 57
Checkout.java (2)
HttpSession cart = request.getSession();
response.setContentType("text/HTML");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Checkout</TITLE>");
out.println("</HEAD>");
out println
(
"
<BODY>
"
);
out
.
println
( <BODY> );
out.println("<BR><BR><BR>");
out.println("<CENTER>");
out.println("<H1><FONT COLOR=Red>Order List</FONT></H1>");
out.println("<BR><BR><BR>");
CSIE33000 Network Programming Servlets 58
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 30
Checkout.java (3)
out.println("<TABLE BGCOLOR=Aqua BORDER=2>");
out.println("<TR>");
l
("/")
out.print
l
n
("
<TH>Item<
/
TH>
")
;
out.println("<TH>Weight(kg)</TH>");
out.println("<TH>Cost(?</TH>");
out.println("</TR>");
cart.removeAttribute("currentProd");
d
b
()
Enumeration pro
d
Names = cart.getAttri
b
uteNames
()
;
float totalCost = 0;
int numProducts = 0;
CSIE33000 Network Programming Servlets 59
Checkout.java (4)
while (prodNames.hasMoreElements()) {
float wt=0,cost=0;
String product = (String)prodNames.nextElement();
St i
t i Wt
(St i )
t tAtt ib t
( d t)
St
r
i
ng s
t
r
i
ng
Wt
=
(St
r
i
ng
)
car
t
.ge
tAtt
r
ib
u
t
e
(
pro
d
uc
t)
;
wt = Float.parseFloat(stringWt);
if (product.equals("Apples"))
cost = APPLES_PRICE * wt;
else if (product.equals("Pears"))
cost = PEARS_PRICE * wt;
out.println("<TR>");
out println
(
"
<TD>
"
+ product +
"
</TD>
"
);
out
.
println
( <TD>

+

product

+

</TD> );
out.format("<TD> %4.2f </TD>%n", wt);
out.format("<TD> %5.2f </TD>%n", cost);
out.println("</TR>");
totalCost+=cost;
numProducts++;
}
CSIE33000 Network Programming Servlets 60
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 31
Checkout.java (5)
if (numProducts == 0) {
out.println("<TR BGCOLOR=Yellow>");
out.
p
rintln
(
"<TD>*** No orders
p
laced! ***<
/
TD><
/
TR>"
);
p ( p//);
}
else {
out.println("<TR BGCOLOR=Yellow>");
out.println("<TD></TD>"); //Blank cell.
out.println("<TD>Total cost:</TD>");
out.format("<TD> %5.2f </TD>%n", totalCost);
out.println("</TR>");
}
}
out.println("</TABLE>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 61
Checkout Execution
CSIE33000 Network Programming
Servlets 62
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 32
Cookies

Another way to store user’s data.

說
ョﱹ  イ  說 
ョ

說
ョﱹ







ョ



ョ


Cookies store information that may be
retrieved on subsequent visits to the site.

They can be used to personalize pages for
the user and/or select his/her preferences.

Cookies have been used with CGI for years.

Java servlets use them as well.
CSIE33000 Network Programming Servlets 63
What is a Cookie?

A cookie is an associated name-value pair in
which both name and value are strings.

Cookies are usually stored on the client
computer for future use.

Each cookie is held in a small file sent by the
server to the client and retrieved by the
server on subse
q
uent visits b
y
the user to
q
y
the site.

The constructor for a Java Cookie
Cookie(String <name>, String <name>)
CSIE33000 Network Programming Servlets 64
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 33
How to use Cookies?

A new cookie must be added to the
Htt
p
ServletRes
p
onse ob
j
ect.
p p
j
void addCookie(Cookie <name>)
eg. response.addCookie(myCookie);

Cookies are retrieved through
HttpServletRequest object.
Cookie[] getCookies()
eg. Cookie[] cookie = request.getCookies();
CSIE33000 Network Programming Servlets 65
More Cookie Methods

setMaxAge — set the lifetime of cookie

Positive number (usually large!) in seconds
N ti
l th ki h ld t f i t

N
ega
ti
ve va
l
ue means
th
e coo
ki
e s
h
ou
ld
go ou
t
o
f
ex
i
s
t
ence
when the client leaves the site

0 causes the cookie’s immediate destruction

void setComment(String <value>)

String getComment()

St
rin
g

get
N
a
m
e
()
St g
get a e
()

String getValue()

void setValue(String <value>)

int getMaxAge()
CSIE33000 Network Programming Servlets 66
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 34
Cookie Example

Modify the ‘Simple Adder’ example.

On first visit, user enters name and a choice of both
fore
g
round and back
g
round colors.

These values are saved in cookies and used in
subsequent visits.

No personalization w/o name

Use default colors if not specified.

The only differences in the HTML file
<FORM METHOD=POST ACTION="CookieAdder">
CSIE33000 Network Programming Servlets 67
CookieAdder.java (1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieAdder extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
int sum=0;
try {
String value1 =
request getParameter
(
"
Num1
"
);
String

value1

=

request
.
getParameter
( Num1 );
String value2 = request.getParameter("Num2");
int num1 = Integer.parseInt(value1);
int num2 = Integer.parseInt(value2);
sum = num1 + num2;
}
CSIE33000 Network Programming Servlets 68
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 35
CookieAdder.java (2)
catch(NumberFormatException nfEx)
{
sendPa
g
e
(
res
p
onse
,
"*** Invalid entr
y
! ***"
);
g
( p,y );
return;
}
HttpSession adderSession = request.getSession();
adderSession.setAttribute("sum", new Integer(sum));
Cookie[] cookie = request.getCookies();
int numCookies = cookie.length;
for (int i=0; i<numCookies; i++)
adderSession.setAttribute(
cookie[i].getName(), cookie[i].getValue());
CSIE33000 Network Programming Servlets 69
CookieAdder.java (3)
if (adderSession.getAttribute("firstVisit") == null)
// First visit!
f
response.sendRedirect("GetPre
f
erences");
else
response.sendRedirect("ShowSum");
}
i t id
dP
(
Htt S l tR
l
pr
i
va
t
e vo
id
sen
dP
a
g
e
(
Htt
p
S
erv
l
e
tR
esponse rep
l
y,
String message) throws IOException
{
reply.setContentType("text/HTML");
CSIE33000 Network Programming Servlets 70
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 36
CookieAdder.java (4)
PrintWriter out = reply.getWriter();
out.println("<HTML>");
out println
("<HEAD>");
out
.
println
("<HEAD>");
out.println("<TITLE>Result</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><BR>");
out.println("<CENTER>" + message + "</CENTER>");
out println
("</BODY>");
out
.
println
("</BODY>");
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 71
GetPreferences.java(1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetPreferences extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
response.setContentType("text/HTML");
HttpSession adderSession = request.getSession();
adderSession.setAttribute
(
"firstVisit"
,
"Yes"
);
(
,
);
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Preferences</TITLE>");
out.println("</HEAD>");
CSIE33000 Network Programming Servlets 72
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 37
GetPreferences.java(2)
out.println("<BODY>");
out.println("<BR><BR><BR>");
t i tl
("CENTER")
ou
t
.pr
i
n
tl
n
("
<
CENTER
>
")
;
out.println("<FORM METHOD=POST ACTION='ShowSum'>");
out.println("<FONT COLOR='Blue' SIZE=5>User Preferences</FONT>");
out.println("<BR>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>First name</TD>");
out.println("<TD><INPUT TYPE='Text' NAME='Name' VALUE=''
SIZE
=
15></TD>
"
);
SIZE 15></TD> );
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Foreground colour</TD>");
out.println("<TD><INPUT TYPE='Text' "
+ "NAME='ForeColour'VALUE='' SIZE=10></TD>");
CSIE33000 Network Programming Servlets 73
GetPreferences.java(3)
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Background colour</TD>");
t i tl
("TD INPUT TYPE'T t'"
ou
t
.pr
i
n
tl
n
("
<
TD
><
INPUT

TYPE
=
'T
ex
t'

"
+ "NAME='BackColour' VALUE='' SIZE=10></TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("<BR><BR>");
out.println("<INPUT TYPE='Submit' VALUE = 'Submit'></TD>");
out.println("<INPUT TYPE='Reset' VALUE='Clear'></TD>");
out println
(
"
</CENTER>
"
);
out
.
println
( </CENTER> );
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
CSIE33000 Network Programming Servlets 74
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 38
GetPreferences Execution
CSIE33000 Network Programming
Servlet 75
ShowSum.java (1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowSum extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
HttpSession adderSession = request.getSession();
String
firstTime
=
(String)
adderSession getAttribute
(
"
firstVisit
"
);
String

firstTime
=

(String)
adderSession
.
getAttribute
(
firstVisit
);
if (firstTime.equals("Yes"))
retrieveNewPreferences(request,response,adderSession);
sendPage(response,adderSession);
}
CSIE33000 Network Programming Servlets 76
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 39
ShowSum.java (2)
private void sendPage(HttpServletResponse reply,HttpSession session)
throws IOException
{
{
String userName,foreColour,backColour,sum;
userName = (String)session.getAttribute("name");
foreColour = (String)session.getAttribute("foreColour");
backColour = (String)session.getAttribute("backColour");
//Value of 'sum' originally saved as instance of class Integer
//(and saved as instance of class Object in session object)
//(and

saved

as

instance

of

class

Object

in

session

object)
,
//so we cannot typecast into class String as done for three
//values above. Instead, we use method toString of class Object...
sum = session.getAttribute("sum").toString();
reply.setContentType("text/HTML");
CSIE33000 Network Programming Servlets 77
ShowSum.java (3)
PrintWriter out = reply.getWriter();
out.println(
"
<HTML>
"
);
out.println( <HTML> );
out.println("<HEAD>");
out.println("<TITLE>Result</TITLE>");
out.println("</HEAD>");
out println(
"
<BODY TEXT=
"
+ foreColour
out
.
println( <BODY

TEXT=

+

foreColour

+" BGCOLOR=" + backColour + ">");
out.println("<CENTER>");
CSIE33000 Network Programming Servlets 78
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 40
ShowSum.java (4)
if (!userName.equals(""))
out.println("<H2>" + userName + "'s " + "Result</H2>");
out.
p
rintln
(
"<BR><BR><BR><H3>" + sum + "<
/
H3>"
);
p
(/);
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
private void retrieveNewPreferences(HttpServletRequest request,
HttpServletResponse
response HttpSession
session)
HttpServletResponse
response
,
HttpSession
session)
{
final int AGE = 180;//(180secs = 3mins)
String forename = request.getParameter("Name");
if (forename==null) return;//Should never happen!
CSIE33000 Network Programming Servlets 79
ShowSum.java (5)
if (!forename.equals(""))
{
Cookie nameCookie = new Cookie
(
"name"
,
forename
);
(
,
);
nameCookie.setMaxAge(AGE);
response.addCookie(nameCookie);
session.setAttribute("name",forename);
}
String fColour = request.getParameter("ForeColour");
if (fColour.equals(""))
fC l
"Bl k"
fC
o
l
our =
"Bl
ac
k"
;
Cookie foreColourCookie = new Cookie("foreColour",fColour);
foreColourCookie.setMaxAge(AGE);
response.addCookie(foreColourCookie);
session.setAttribute("foreColour",fColour);
CSIE33000 Network Programming Servlets 80
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 41
ShowSum.java (6)
String bColour = request.getParameter("BackColour");
if (bColour.equals(""))
bColour = "White";
Cookie backColourCookie = new
Cookie("backColour",bColour);
backColourCookie.setMaxAge(AGE);
response.addCookie(backColourCookie);
session.setAttribute("backColour",bColour);
Cookie visitCookie = new Cookie("firstVisit","No");
vi
s
it
Coo
ki
e
.
se
tM
a
xA
ge
(
A
G
E
);
s Coo e se a ge
( G );
response.addCookie(visitCookie);
session.setAttribute("firstVisit","No");
}
}
CSIE33000 Network Programming Servlets 81
Showsum Execution
CSIE33000 Network Programming
Servlet 82
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 42
Accessing DB via a Servlet

Many Web applications need to access DBs.

Combined with JDBC
,
a setvlet can access DBs.
,

Two additional servlet methods are required:

init — called up once at the start (initialization)

destroy — called up once at the end (clean-up)

They are methods of interface Servlet and are
implemented by class HttpServlet.

We should override init to load the JDBC driver and set
up a DB connection. (remember to call the init of super)

Also override destroy to close the DB connection.

Both methods throw ServletException.
CSIE33000 Network Programming Servlets 83
A Phonebook Example

Assume a HomeDB.mdb database with a
table called PhoneNums which has fields
Surname, Fornames and PhoneNum.

Also assume the DSN be HomeDB.

The HTML page (JDBCServletTest.html) uses
a form to accept a new record and passes
h l l h dd d
t
h
e va
l
ues to a serv
l
et t
h
at a
dd
s a recor
d
to
the PhoneNums table and displays the new
contents.
CSIE33000 Network Programming Servlets 84
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 43
JDBCServletTest.html (1)
<!-- JDBCServletTest.html -->
<HTML>
<HEAD>
<TITLE>Database Insertion Form</TITLE>
</HEAD>
<BODY>
<BODY>
<H1><CENTER>Phonebook</CENTER><H1>
<FORM METHOD=POST ACTION="DbServlet">
CSIE33000 Network Programming Servlets 85
JDBCServletTest.html (2)
<PRE>
Surname:<INPUT TYPE="Text" NAME="Surname">
Forenames:<INPUT TYPE="Text" NAME="Forenames">
Phone number:<INPUT TYPE="Text" NAME="PhoneNum">
</PRE>
<BR><BR>
<CENTER><INPUT TYPE="Submit“ VALUE="Commit"></CENTER>
</FORM>
</FORM>
</BODY>
</HTML>
CSIE33000 Network Programming Servlets 86
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 44
DbServlet Execution
CSIE33000 Network Programming
Servlet 87
DbServlet.java (1)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java sql
*
;
import

java
.
sql
.
;
public class DbServlet extends HttpServlet {
private Statement statement;
private Connection link;
private String URL = "jdbc:odbc:HomeDB";
public void init() throws ServletException {
su
p
er.init
();
p
();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //can omit with JDBC4.0
link = DriverManager.getConnection(URL,"","");
}
CSIE33000 Network Programming Servlets 88
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 45
DbServlet.java (2)
catch (Exception ex)
{
ex.printStackTrace();
System exit
(1);
System
.
exit
(1);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
String surname,forenames,telNum;
surname = request.getParameter("Surname");
forenames = request.getParameter("Forenames");
telNum = request.getParameter("PhoneNum");
response.setContentType("text/HTML");
PrintWriter out = response.getWriter();
CSIE33000 Network Programming Servlets 89
DbServlet.java (3)
out.println("<HTML>");
out.println("<HEAD>");
out.
p
rintln
(
"<TITLE>Servlet + JDBC<
/
TITLE>"
);
p
(
/);
out.println("</HEAD>");
out.println("<BODY>");
String insertion = "INSERT INTO PhoneNums“+ " VALUES('"
+ surname + "','“ + forenames + "','" + telNum + "')";
try
{
{
statement = link.createStatement();
statement.executeUpdate(insertion);
statement.close();//Ensures committal.
}
CSIE33000 Network Programming Servlets 90
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 46
DbServlet.java (4)
catch (SQLException sqlEx)
{
out.
p
rintln
(
"<BR><CENTER><H2>Unable to execute

p
(
+ “ insertion!</H2></CENTER>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
System.exit(1);
}
try
{
statement = link.createStatement();
ResultSet results = statement.executeQuery(
"SELECT * FROM PhoneNums");
CSIE33000 Network Programming Servlets 91
DbServlet.java (5)
out.println("Updated table:");
out.println("<BR><BR><CENTER>");
out.println("<TABLE BORDER>");
out.println("<TR><TH>Surname</TH>");
t i tl
("<TH>F ( )</TH>")
ou
t
.pr
i
n
tl
n
("<TH>F
orename
(
s
)</TH>")
;
out.println("<TH>Phone No.</TH></TR>");
while (results.next())
{
out.println("<TR>");
out.println("<TD>");
out.println(results.getString("Surname"));
out.println("</TD>");
out.println("<TD>");
t i tl
(
lt tSt i
("F"))
ou
t
.pr
i
n
tl
n
(
resu
lt
s.ge
tSt
r
i
ng
("F
orenames
"))
;
out.println("</TD>");
out.println("<TD>");
out.println(results.getString("PhoneNum"));
out.println("</TD>");
out.println("</TR>");
}
CSIE33000 Network Programming Servlets 92
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 47
DbServlet.java (6)
out.println("</TABLE>");
}
catch
(
S
Q
LExce
p
tion s
q
lEx
)
(
Q p
q
)
{
out.println("<BR><H2>Unable to retrieve data!</H2>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
System.exit(1);
}
out.println("</CENTER>");
out.println("<BODY>");
out.println("</HTML>");
out.flush();
}
CSIE33000 Network Programming Servlets 93
DbServlet.java (7)
public void destroy() {
try
{
{
link.close();
}
catch(Exception ex)
{
System.out.println("Error on closing database!");
ex printStackTrace
();
ex
.
printStackTrace
();
System.exit(1);
}
}
}
CSIE33000 Network Programming Servlets 94
CSIE 33000 Network Programming Lecture 12 Servlets
Shiow-yang Wu Note 48
DbServlet Execution
CSIE33000 Network Programming
Servlet 95