Programming Web Applications with Servlets

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

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

76 εμφανίσεις

An Introduction to XML and Web Technologies

Programming Web Applications
with Servlets

Anders Møller
&
Michael I. Schwartzbach
©
2006 Addison-Wesley
2
An Introduction to XML and Web Technologies
Objectives
§

How to
program
Web
applications

using

servlets



Requests

(HTTP(+XML))


Responses

(XHTML or XML)


Servlet
Contexts

(
shared

state
)


Sessions
(session
state
)

§

Exercises
:


Deploy+manage

servlets

using
the
Tomcat
server
(with
help
from the
TAs
)


Program
web
applications

using

servlets
!
3
An Introduction to XML and Web Technologies
Web Applications

§

Web server:


accepts
(HTTP)
requests,
returns files or runs applications
that produce responses
§

Web application:


a collection of programs
(e.g., Java Servlets, JSP pages, ...)
and auxiliary files
(e.g., static HTML pages, GIF files, ...)
§

Servlets:


web applications programmed using the Servlet API
(directly based on HTTP)
Java Servlets
e
"
e
"
e
"
Web!
Service
!
client
HTML
HTML
form input
server
www
HTML
HTML
CODE
CODE
CODE
CODE
JSP
(next week)
e
"
e
"
e
"
Web!
Service
!
client
HTML
HTML
form input
server
www
CODE
CODE
HTML
6
An Introduction to XML and Web Technologies
State

(3 kinds)

STATE
:
§

Shared state:


(Lifecycle:
application
)


usually stored in DB
§

Session state:


(Lifecycle:
session
)


many ways to handle (more about this later)
§

Transient state:


(Lifecycle:
one interaction
)


usually stored in local variables
An Introduction to XML and Web Technologies
Hello World Servlet

import
java.io
.*;
import
javax.servlet
.*;
import
javax.servlet.http
.*;

public
class

HelloWorld

extends

HttpServlet
{

public
void

doGet
(
HttpServletRequest

request
,

HttpServletResponse

response
)

throws

IOException
,
ServletException
{

response.setContentType
("
text
/html");

PrintWriter
out =
response.getWriter
();

out.println
("
<html><head><
title
>
ServletExample
</
title
></head>
"+
"
<
body
><h1>
Hello
World!</h1>
"+
"
This page was last updated:
"+
new
java.util.Date
()+
"
</body></html>
");
}
}

Hello World!

This page was last updated: Tues Feb 28 17:15 CET 2012
Static vs Dynamic Validation
§

Static Validation
:
(last week's topic!)
§

Web Services require:
Dynamic

Validation
:
input
dynamic

html
client

e
www
e
server
web
application

(e.g., Java Servlet / JSP)
VALID
? ! ?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Hello!</title>
</head>
<body>
<b>hello world!</b>
</body>
</html>
Validate:
9
An Introduction to XML and Web Technologies
Requests
§

Methods in
HttpServletRequest



getHeader

(HTTP header values)


getRemoteHost
,
getRemoteAddr
,
getRemotePort



getParameter

(GET/POST variables)


getInputStream

(for reading request body)


...
request
10
An Introduction to XML and Web Technologies
Example:
HttpServletRequest
(1/2)

public
class

Requests

extends

HttpServlet
{
public
void

doGet
(
HttpServletRequest

request
,

HttpServletResponse

response
)

throws

IOException
,
ServletException
{

response.setContentType
("
text
/html");

PrintWriter
out =
response.getWriter
();

out.println
("
<html><head><
title
>
Requests
</
title
></head><
body
>
");

out.println
("
<h1>
Hello
,
visitor
from
"+
request.
getRemoteHost
()+"
</h1>
");

String

useragent
=
request.
getHeader
("
User-Agent
");

if
(
useragent
!=
null
)

out.println
("
You

seem
to
be

using
"+
useragent
+"
<p>
");

String

name
=
request.
getParameter
("
name
");

if
(
name
==
null
)
out.println
("
No <
tt
>
name
</
tt
>
field

was
given!
");

else

out.println
("
The
value
of the <
tt
>
name
</
tt
>
field
is: <
tt
>
" +

htmlEscape
(
name
) + "
</
tt
>
");

out.println
("
</
body
></html>
");
}
10
11
An Introduction to XML and Web Technologies
Example:
HttpServletRequest
(2/2)

public
void

doPost
(
HttpServletRequest

request
,

HttpServletResponse

response
)

throws

IOException
,
ServletException
{

doGet
(
request
,
response
);
}


String

htmlEscape
(
String
s) {

StringBuffer
b = new
StringBuffer
();
for (
int
i = 0; i<
s.length
(); i++) {

char
c =
s.charAt
(i);
switch (c) {
case '<':
b.append
("&
lt
;"); break;
case '>':
b.append
("&
gt
;"); break;
case '"':
b.append
("&
quot
;"); break;
case '\'':
b.append
("&
apos
;"); break;
case '&':
b.append
("&
amp
;"); break;
default:
b.append
(c);
} }

return

b.toString
();
} }
12
An Introduction to XML and Web Technologies
Responses

§

Methods in
HttpServletResponse


setStatus
("200 OK" by default)


addHeader, setHeader


getOutputStream, getWriter


setContentType


sendError, sendRedirect


...
response
13
An Introduction to XML and Web Technologies
Example:
BusinessCardServlet
public class
BusinessCardServlet
extends
HttpServlet
{

public void
doGet
(
HttpServletRequest
request,

HttpServletResponse
response
)
throws
IOException
,
ServletException
{

response.
setContentType
("
text/
xml;charset
=UTF-8
");
long expires = new Date().
getTime
() + 1000*60*60*24;

response.
addDateHeader
("
Expires
", expires);

XMLOutputter

outputter
= new
XMLOutputter
();

outputter.output
(
...XML document...
,

response.getOutputStream
());
}
...
}
using JDOM to generate an XML
document
(with a reference to an
XSLT
stylesheet
)
14
An Introduction to XML and Web Technologies
Servlet Contexts
(shared state!)

§

One
ServletContext
object for each
Web application (
c =
getServletContext
()
)
§

c.getServerInfo
()
§

c.getInitParameter
(x)
§

...
§

Shared state
:


c.setAttribute
("
name

",
value
);
// write


value =
c.getAttribute
("
name

");
// read



don’t use for mission critical data!
(then use database!)
15
An Introduction to XML and Web Technologies
A Web application consisting of:
1) QuickPollQuestion.html
2) QuickPollSetup.java
3) QuickPollAsk.java
4) QuickPollVote.java
5) QuickPollResults.java
Example: A Polling Service

QuickPoll

Thank you for
your vote!
submit
Admin
Use
1
3
4
5
QuickPoll

Your question has
been registered.
Let the vote begin!
submit
2
16
An Introduction to XML and Web Technologies
Example:
QuickPollQuestion.html
<html>
<head><title>
QuickPoll
</title></head>
<body>
<h1>
QuickPoll
</h1>
<form method=post
action=
setup
>
What is your question?<
br
>
<input
name=question
type=text size=40>?<
br
>
<input type=submit
name=submit

value="Register my question">
</form>
</body>
</html>
1
17
An Introduction to XML and Web Technologies
Example:
QuickPollSetup.java
public class
QuickPollSetup
extends
HttpServlet
{
public void
doPost
(
HttpServletRequest
request,

HttpServletResponse
response)
throws
IOException
,
ServletException
{
String q =
request.
getParameter
("
question
");

ServletContext
c =
getServletContext
();

c.
setAttribute
("
question
", q);

c.
setAttribute
("
yes
", new Integer(0));

c.
setAttribute
("
no
", new Integer(0));

response.setContentType
("text/html");

PrintWriter
out =
response.getWriter
();

out.print
("<html><head><title>
QuickPoll
</title></head><body>"+
"<h1>
QuickPoll
</h1>"+
"Your question has been registered. "+
"Let the vote begin!"+
"</body></html>");
} }
QuickPoll

Your question has
been registered.
Let the vote begin!
2
18
An Introduction to XML and Web Technologies
Example:
QuickPollAsk.java
public class
QuickPollAsk
extends
HttpServlet
{
public void
doGet
(
HttpServletRequest
request,

HttpServletResponse
response)
throws
IOException
,
ServletException
{

response.setContentType
("text/html");

PrintWriter
out =
response.getWriter
();

out.print
("<html><head><title>
QuickPoll
</title></head><body>"+
"<h1>
QuickPoll
</h1>"+
"<form method=post action=
vote
>");
String question =

(String)
getServletContext
().
getAttribute
("question")
;

out.print
(question + "?<p>");

out.print
("<input name=vote type=radio value=yes> yes<
br
>"+
"<input name=vote type=radio value=no> no<p>"+
"<input type=submit name=submit value=Vote>"+
"</form>"+
"</body></html>");
} }
3
19
An Introduction to XML and Web Technologies
Example:
QuickPollVote.java
(1/2)

public class
QuickPollVote
extends
HttpServlet
{
public void
doPost
(
HttpServletRequest
request,

HttpServletResponse
response)
throws
IOException
,
ServletException
{
String vote =
request.
getParameter
("vote")
;

ServletContext
c =
getServletContext
();
if (
vote.equals
("yes")) {

int
yes = ((Integer)
c.
getAttribute
("yes")
).
intValue
();
yes++;

c.
setAttribute
("yes",
new Integer(yes)
)
;
} else if (
vote.equals
("no")) {

int
no = ((Integer)
c.
getAttribute
("no")
).
intValue
();
no++;

c.
setAttribute
("no",
new Integer(no)
)
;
}
4
20
An Introduction to XML and Web Technologies
Example:
QuickPollVote.java
(2/2)

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html><head><title>QuickPoll</title></head><body>"+
"<h1>QuickPoll</h1>"+
"Thank you for your vote!"+
"</body></html>");
}
}
QuickPoll

Thank you for
your vote!
4
21
An Introduction to XML and Web Technologies
Example:
QuickPollResult.java
(1/2)
public class
QuickPollResults
extends
HttpServlet
{
public void
doGet
(
HttpServletRequest
request,

HttpServletResponse
response)
throws
IOException
,
ServletException
{

ServletContext
c =
getServletContext
();
String question = (String)
c.
getAttribute
("
question
");

int
yes = ((Integer)
c.
getAttribute
("
yes
")).
intValue
();

int
no = ((Integer)
c.
getAttribute
("
no
")).
intValue
();

int
total =
yes+no
;

response.setContentType
("text/html");

response.
setDateHeader
("Expires", 0)
;

response.
setHeader
("Cache-Control",
"no-store, no-cache, must-revalidate")
;

response.
setHeader
("Pragma", "no-cache"
);

PrintWriter
out =
response.getWriter
();
5
22
An Introduction to XML and Web Technologies
Example:
QuickPollResult.java
(2/2)
out.print("<html><head><title>QuickPoll</title></head><body>"+
"<h1>QuickPoll</h1>");
if (total==0)
out.print("No votes yet...");
else {
out.print(question + "?<p>"+"<table border=0>"+
"<tr><td>Yes:<td>"+drawBar(300*yes/total)+"<td>"+yes+
"<tr><td>No:<td>"+drawBar(300*no/total)+"<td>"+no+
"</table>");
}
out.print("</body></html>");
}

String drawBar(int length) {
return "<table><tr><td bgcolor=black height=20 width="+
length+"></table>";
} }
5
23
An Introduction to XML and Web Technologies
Problems in QuickPoll

§

Need
access control
to
QuickPollSetup

§

No
escaping of special characters
§

Need to
check right order of execution
§

Need to check that expected
form field data
is
present and have appropriate formats
(validation)
§

No
synchronization
in
QuickPollVote

(x=x+1)

§

Should store state in
database

§

Redundancy
in HTML generation
§

...

24
An Introduction to XML and Web Technologies
Sessions

§

One
HttpSession
object for each session


obtained by
getSession
in the
HttpServletRequest
object

§

Session state
:


setAttribute
("
name

",
value
);
// write


value =
getAttribute
("
name

");
// read

§

Hides the technical details of tracking users with
URL rewriting / cookies / SSL sessions
25
An Introduction to XML and Web Technologies
Example: Shopping Cart

(See example in the book)
26
An Introduction to XML and Web Technologies
Limitations of Servlets
§

Low-level
construction of HTML documents:


fragments (strings) written to output stream


no static well-
formedness
/validity guarantees
§

Low-level
session management:


control-flow is often unclear
(implicit)


no enforcement of relation between showing a page
and receiving form input


primitive session state management
27
An Introduction to XML and Web Technologies
Summary

§

Servlets closely follow the
request-response

pattern from HTTP
§

Features:


Multi-threading


Declarative configuration
(Tomcat)


Request parsing, including decoding of form data


Shared state
(servlet context)


Session management
(session object)


Advanced code structuring: listeners, filters, wrappers


Client authentication, SSL
28
An Introduction to XML and Web Technologies
Essential Online Resources

§

The servlet API:

http://jakarta.apache.org/tomcat/
tomcat-5.5-doc/servletapi/

§

Sun's home page for servlets:
http://java.sun.com/products/servlet/

§

The Tomcat server:
http://jakarta.apache.org/tomcat/