Advanced Advanced Advanced Advanced Servlets Servlets and JSP and JSP

tieplantlimabeansSoftware and s/w Development

Oct 28, 2013 (3 years and 10 months ago)

124 views

AdvancedAdvanced
Advanced

Advanced

ServletsServletsand JSPand JSP
Advanced Advanced ServletsServletsFeaturesFeatures
Li
s
t
e
n
e
r
s
sees
Filters and wrappers
Request dispatchers

Security
Security
2
AdvancedServletsand JSP
ListenersListeners
–also called observersor event handlers
ServletContextListener

Webapplicationinitialized/shutdown
Web

application

initialized

/

shut

down
ServletRequestListener

requesthandlerstarting/finishing
request

handler

starting

/

finishing
HttpSessionListener

sessioncreated/invalidated
session

created

/

invalidated
ServletContextAttributeListener

contextattributeadded/removed/replaced
context

attribute

added

/

removed

/

replaced
HttpSessionAttributeListener

sessionattributeadded/removed/replaced
3
AdvancedServletsand JSP

session

attribute

added

/

removed

/

replaced
Example: Example: SessionMonitor
SessionMonitor(1/2)
(1/2)
import javax.servlet.*;
importjavax.servlet.http.
*
;
import

javax.servlet.http.;
public class SessionMonitor
implements HttpSessionListener, ServletContextListener{
private int active = 0, max = 0;
public void contextInitialized(ServletContextEvent sce) {
store(scegetSerletContet())
store(sce
.
getSer
v
letConte
x
t())
;
}
publicvoidcontextDestroyed(ServletContextEventsce){}
public

void

contextDestroyed(ServletContextEvent

sce)

{}
public void sessionCreated(HttpSessionEvent se) {
active++;
if (active>max)
max = active;
store(se.getSession().getServletContext());
4
AdvancedServletsand JSP
}
Example: Example: SessionMonitor
SessionMonitor(2/2)
(2/2)
public void sessionDestroyed(HttpSessionEvent se) {
active
--
;
active
;
store(se.getSession().getServletContext());
}
private void store(ServletContext c) {
c.setAttribute("sessions_active", new Integer(active));
c.setAttribute
(
"sessions_max"
,
new Inte
g
er
(
max
));
(,g());
}
}
Registration in web.xml:
<listener>
<listener-class>SessionMonitor</listener-class>
<listener>
5
AdvancedServletsand JSP
<listener>
FiltersFilters
Code bein
g
executed before and after the servlet
g
•executed in stack-like fashion with servlet at the bottom

Can
intercept
and
redirect
processing
Can

intercept
and

redirect
processing
•security

auditing

auditing
Can modify requests and responses
dti(XSLTi)

d
a
t
a convers
i
on
(XSLT
, gz
i
p, ...
)
•specialized caching
–all without changing the existing servlet code!
6
AdvancedServletsand JSP
Example: Example: LoggingFilter
LoggingFilter(1/2)
(1/2)
import java.io.*;
importjavax.servlet.
*
;
import

javax.servlet.;
import javax.servlet.http.*;
publicclassLoggingFilterimplements
Filter
{
public

class

LoggingFilter

implements

Filter
{
ServletContext context;
int counter;
public void init(FilterConfig c) throws ServletException {
context = c.getServletContext();
}
}
public void destroy() {}
7
AdvancedServletsand JSP
Example: Example: LoggingFilter
LoggingFilter(2/2)
(2/2)
public void doFilter(ServletRequestrequest,
ServletRes
p
onseres
p
onse,
p
p
FilterChainchain)
throws IOException, ServletException {
String uri = ((HttpServletRequest)request).getRequestURI();
int n = ++counter;
context.log("starting processing request #"+n+" ("+uri+")");
long t1 = System.currentTimeMillis();
chain.doFilter(request, response);
long t2 = System.currentTimeMillis();
context.lo
g(
"done
p
rocessin
g
re
q
uest #"+n+"
,
"+
(
t2-t1
)
+" ms"
);
g(pgq,(
));
}
}
8
AdvancedServletsand JSP
Registration of Filters in Registration of Filters in web.xml
web.xml
<web-a
pp
...>
pp
...
<filter>
<filter
name>
MyLoggingFilter
</filter
name>
<filter
-
name>
My

Logging

Filter
</filter
-
name>
<filter-class>LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter
-
name>
MyLoggingFilter
</filter
-
name>
<filter
name>
My

Logging

Filter
</filter
name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
9
AdvancedServletsand JSP
WrappersWrappers
Used b
y
filters to modif
y
re
q
uests and res
p
onses
yyqp
HttpServletRequestWrapper
HttpServletResponseWrapper

Example:performing
server
-
side
XSLT
Example:

performing

server
side
XSLT

transformation for older browsers
10
AdvancedServletsand JSP
Example: Example: XSLTFilter
XSLTFilter(1/5)
(1/5)
import java.io.*;
importjava.util.
*
;
import

java.util.;
import javax.servlet.*;
import javax.servlet.http.*;
importorgjdom
*
;
import

org
.
jdom
.
;

import org.jdom.transform.*;
import org.jdom.input.*;
importorgjdomoutput
*
;
import

org
.
jdom
.
output
.
;

public class XSLTFilter implements Filter{
ServletContextcontext;
ServletContext

context;
public void init(FilterConfig c) throws ServletException {
contextcgetServletContext();
context
=
c
.
getServletContext();
}
bliiddt(){}
11
AdvancedServletsand JSP
pu
bli
c vo
id

d
es
t
roy
()

{}
Example: Example: XSLTFilter
XSLTFilter(2/5)
(2/5)
public void doFilter(ServletRequest request,
ServletResponseresponse,
ServletResponse

response,

FilterChain chain)
throws IOException, ServletException {
HttpServletRequesthreq=(HttpServletRequest)request;
HttpServletRequest

hreq

=

(HttpServletRequest)request;
HttpServletResponse hresp = (HttpServletResponse)response;
boolean client_capable =
checkXSLTSupport(hreqgetHeader(
"
User
-
Agent
"
));
checkXSLTSupport(hreq
.
getHeader(User
-
Agent));
ServletResponse res;
if (client_capable)
res=response;
res

=

response;
else
res = new BufferingResponseWrapper(hresp);
chain
doFilter
(requestres);
chain
.
doFilter
(request
,
res);

12
AdvancedServletsand JSP
Example: Example: XSLTFilter
XSLTFilter(3/5)
(3/5)
if (!client_capable) {
try {
hresp.setContentType("application/xhtml+xml");
transform(((BufferingResponseWrapper)res).getReader(),
response.getWriter());
}h(hbl){
}
catc
h

(
T
h
rowa
bl
e e
)

{
context.log("XSLT transformation error", e);
hresp.sendError(500, "XSLT transformation error");
}
}
}
}
boolean checkXSLTSupport(String user_agent) {
if (user_agent==null)
return false;
t
re
t
urn
user_agent.indexOf("MSIE 5.5")!=-1 ||
user_agent.indexOf("MSIE 6")!=-1 ||
useragent.indexOf(
"
Gecko
"
)!
=-
1;
13
AdvancedServletsand JSP
user
_
agent.indexOf(Gecko)!
1;
}
Example: Example: XSLTFilter
XSLTFilter(4/5)
(4/5)
void transform(Reader in, Writer out)
throwsJDOMException,IOException{
throws

JDOMException,

IOException

{
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
SAXBuilderb=newSAXBuilder();
SAXBuilder

b

=

new

SAXBuilder();
Document d = b.build(in);
List pi = d.getContent(new org.jdom.filter.ContentFilter
(orgjdomfilterContentFilterPI));
(org
.
jdom
.
filter
.
ContentFilter
.
PI));
String xsl = ((ProcessingInstruction)(pi.get(0)))
.getPseudoAttributeValue("href");
XSLTransformert=newXSLTransformer(xsl);
XSLTransformer

t

=

new

XSLTransformer(xsl);
Document h = t.transform(d);
(new XMLOutputter()).output(h, out);
}
}
}
14
AdvancedServletsand JSP
Example: Example: XSLTFilter
XSLTFilter(5/5)
(5/5)
class BufferingResponseWrapperextends HttpServletResponseWrapper{
CharArrayWriterbuffer;
CharArrayWriter

buffer;
PrintWriter writer;
p
ublic Bufferin
g
Res
p
onseWra
pp
er(Htt
p
ServletRes
p
onse res) {
pgppppp
super(res);
buffer = new CharArrayWriter();
writer = new PrintWriter
(
buffer
);
();
}
public PrintWriter getWriter() {
return writer;
}
Reader getReader() {
return new CharArrayReader(buffer.toCharArray());
}
15
AdvancedServletsand JSP
}
Request DispatchersRequest Dispatchers
Forwardin
g
re
q
uests to other resources
gq

佦瑥Ou獥sw楴i䩓J

佦瑥O

畳敤

睩瑨

䩓J
⸮.

䅤癡湣敤卥牶汥瑳慮搠䩓a
Security Security ––Roles and AuthenticationRoles and Authentication
<web-a
pp
...>
pp
...
<security-role>
<role
name>
administrator
</role
name>
<role
-
name>
administrator
</role
-
name>
<role-name>teacher</role-name>
<role-name>student</role-name>
</security-role>
<login
-
config>
<login
config>
<auth-method>BASIC</auth-method>
<realm-name>Administration</realm-name>
/li
fi
<
/l
og
i
n-con
fi
g>
...
</web-app>
17
AdvancedServletsand JSP
Security ConstraintsSecurity Constraints
...
<security
constraint>
<security
-
constraint>
<web-resource-collection>
<web-resource-name>Restricted Area</web-resource-name>
url
pattern
/restricted/*
/url
pattern
<
url
-
pattern
>
/restricted/*
<
/url
-
pattern
>
<http-method>GET</http-method>
<http-method>POST</http-method>
/b
llti
<
/
we
b
-resource-co
ll
ec
ti
on>
<auth-constraint>
<role-name>administrator</role-name>
l
h
/l
<ro
l
e-name>teac
h
er<
/
ro
l
e-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
18
AdvancedServletsand JSP
...
Programmatic SecurityProgrammatic Security
Useful request methods:
getRemoteUser()
isUserInRole(String role)
iS()

i
s
S
ecure
()
getAuthType()

getAttribute(

javax.servlet.request.X509Certificate

)
getAttribute(
javax.servlet.request.X509Certificate
)
19
AdvancedServletsand JSP
SummarySummary
Servlets closel
y
follow the re
q
uest-res
p
onse
y
q
p
pattern from HTTP
Features:
•Multi-threadin
g
g
•Declarative configuration
•Re
q
uest
p
arsin
g,
includin
g
decodin
g
of form data
qpg,gg
•Shared state
•Session mana
g
ement
g
•Advanced code structuring: listeners, filters, wrappers

Clientauthentication,SSL
20
AdvancedServletsand JSP
Client

authentication,

SSL
Advanced Advanced JSP FeaturesJSP Features
XML version of JSP
The expression language

呡T晩汥f

呡T

晩汥f
JSTL
The Model-View-Controller pattern
21
AdvancedServletsand JSP
JSP Pages Are Not XMLJSP Pages Are Not XML
<html>
<head><title>JSP Color</title></head>
<body bgcolor=<%= request.getParameter("color") %>>
<h1>Hello World!</h1>
<%! int hits = 0; %>
You are visitor number
<% synchronized(this) { out.println(++hits); } %>
since the last time the service was restarted.
<p>
This page was last updated:
<%= new java.util.Date().toLocaleString() %>
</body>
</html>
This page generates HTML, not XHTML

<%%>
isnotwell
formedXML
22
AdvancedServletsand JSP

<%
...
%>
is

not

well
-
formed

XML
XML Version of JSPXML Version of JSP
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
xmlns="http://http://www.w3.org/1999/xhtml">
<jsp:directivepagecontentType=
"
text/html
"
/>
•Uses <jsp:...>
<jsp:directive
.
page

contentType=text/html/>
<jsp:scriptlet>
response.addDateHeader("Expires", 0);
</jsp:scriptlet>
<html>
<head><title>JSP</title></head>
•No schema seems
<head><title>JSP</title></head>
<jsp:element name="body">
<jsp:attribute name="bgcolor">
<jsp:expression>
request.getParameter("color")
</jsp:expression>
to be available
</jsp:attribute>
<h1>Hello World!</h1>
<jsp:declaration>
int hits = 0;
</jsp:declaration>
•No validation
of the output
You are visitor number
<jsp:scriptlet>
synchronized(this) { out.println(++hits); }
</jsp:scriptlet>
since the last time the service was restarted.
/
•No validation
<p
/
>
This page was last updated:
<jsp:expression>
new java.util.Date().toLocaleString()
</jsp:expression>
</jsp:element>
of Java code
23
AdvancedServletsand JSP
</jsp:element>
</html>
</jsp:root>
•but it’s there...
The Expression LanguageThe Expression Language

Wewantto
avoidexplicitJavacode
inJSP

We

want

to
avoid

explicit

Java

code
in

JSP

templates
The syntax ${exp}may be used in
•template text
•attribute values in markup
The expression may access

variablesinthevariousscopes
variables

in

the

various

scopes
•implicit objects, such as param

Theusualoperatorsareavailable
24
AdvancedServletsand JSP

周T

畳畡u

潰敲慴潲o

慲a

慶慩污扬a
An Expression ExampleAn Expression Example
<html>
<html>
<head><title>Addition</title></head>
<body bgcolor="${param.color}">
Thesumof
${param.x}
and
${param.y}
is
${param.x+param.y}
The

sum

of

${param.x}
and

${param.y}
is

${param.x+param.y}
</body>
</html>
25
AdvancedServletsand JSP
Tag FilesTag Files
Define
abstractions
as
newtags
Define

abstractions
as

new

tags
wrap.tag:
<%@ tag %>
<%@ attribute name="title" required="true" %>
<html>
<head><title>${title}</title></head>
<body>
<
j
sp:doBody/>
j
</body>
</html>
<%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %>
<foo:wraptitle="Addition">
The sum of ${param.x} and ${param.y} is
${param.x+param.y}
</foo:wrap>
26
AdvancedServletsand JSP
Content as a Value: A New Image TagContent as a Value: A New Image Tag
image.tag:
image.tag:
<%@ tag %>
<jsp:doBody var="src"/>
i"h//bidk/i/i/
${}
"/
<
i
mg src=
"h
ttp:
//
www.
b
r
i
cs.
dk/i
xwt
/i
mages
/
${
src
}
"/
>
<%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %>
<foo:image>widgetjpg</foo:image>
<foo:image>widget
.
jpg</foo:image>
27
AdvancedServletsand JSP
Declaring Variables: A Date Context TagDeclaring Variables: A Date Context Tag
date.tag:
<%@ tag import="java.util.*" %>
<%@ variable name-given="date" %>
<%@variablename
-
given
="
month
"
%>
<%@

variable

name
givenmonth

%>
<%@ variable name-given="year" %>
<% Calendar cal = new GregorianCalendar();
idl(ld)
i
nt
d
ate = ca
l
.get
(
Ca
l
en
d
ar.DATE
)
;
int month = cal.get(Calendar.MONTH)+1;
int year = cal.get(Calendar.YEAR);
jspContext.setAttribute("date", String.valueOf(date));
jspContext.setAttribute("month", String.valueOf(month));
jspContextsetAttribute(
"
year
"
StringvalueOf(year));
jspContext
.
setAttribute(year
,
String
.
valueOf(year));
%>
<jsp:doBody/>
28
AdvancedServletsand JSP
Using the Date ContextUsing the Date Context
<%@taglibprefix=
"
foo
"
tagdir=
"
/WEB
-
INF/tags
"
%>
<%@

taglib

prefix=foo

tagdir=/WEB
INF/tags

%>
<foo:date>
In the US today is
${
h
}/${
d
}/${
}
${
mont
h
}/${
d
ate
}/${
year
}
,
but in Europe it is
${date}/${month}/${
y
ear}.
y
</foo:date>
29
AdvancedServletsand JSP
Quick Poll Tags (1/2)Quick Poll Tags (1/2)
<%@taglibprefix
="
poll
"
tagdir
="
/WEB
-
INF/tags/poll
"
%>
<%@

taglib

prefixpoll

tagdir/WEB
INF/tags/poll

%>
<poll:quickpoll title="Quickies" duration="3600">
<poll:question>
Thequestionhasbeensetto
"
${
question
}
"
.
The

question

has

been

set

to

${
question
}.
</poll:question>
<poll:ask>
${
question
}?
${
question
}?
<select name="vote">
<option>yes
<option>no
<option>no
</select>
<input type="submit" value="vote">
</poll:ask>
</poll:ask>
30
AdvancedServletsand JSP
Quick Poll Tags (2/2)Quick Poll Tags (2/2)
<poll:vote>
<poll:vote>
You have voted ${vote}.
</poll:vote>
<poll:results>
<poll:results>
In favor: ${yes}<br>
Against: ${no}<br>
Total:${
total
}
Total:

${
total
}
</poll:results>
<poll:timeout>
Sorrythepollshaveclosed
Sorry
,
the

polls

have

closed
.
</poll:timeout>
</poll:quickpoll>
See the tag files in the book...
31
AdvancedServletsand JSP
Tag LibrariesTag Libraries

Librariesoftagscapturingcommonpatterns:
Libraries

of

tags

capturing

common

patterns:
•pagination of large texts

dateandtimes
date

and

times
•database queries

regularexpressions

regular

expressions
•HTML scraping

barcharts

bar

charts
•cookies

e
mail

e
-
mail
•WML

32
AdvancedServletsand JSP

...
JSTL 1.1JSTL 1.1

JSPStandardTagLibrarycovers:

JSP

Standard

Tag

Library

covers:
•assigning to variables
ititthttt
•wr
iti
ng
t
o
th
e ou
t
pu
t
s
t
ream
•catching exceptions
diil
•con
di
t
i
ona
l
s
•iterations
•URL construction
•string formatting
•SQL queries
•XML manipulation
33
AdvancedServletsand JSP
Selecting Some RecipesSelecting Some Recipes
34
AdvancedServletsand JSP
Using JSTL for the MenuUsing JSTL for the Menu
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>
<c:import url="http://www.brics.dk/ixwt/recipes.xml" var="xml"/>
<x:parse xml="${xml}" var="recipes" scope="session"/>
<html>
<head><title>SelectSomeRecipes</title></head>
<head><title>Select

Some

Recipes</title></head>
<body>
<form method="post" action="show.jsp">
<x:forEachselect
="
$recipes//recipe
"
>
<x:forEach

select$recipes//recipe>
<c:set var="id"><x:out select="@id"/></c:set>
<input type="checkbox" name="selected" value="${id}"/>
<x:out select="title/text()"/>
<br/>
</x:forEach>
<input type="submit" value="Select"/>
/f
<
/f
orm>
</body>
</html>
35
AdvancedServletsand JSP
Using JSTL for the Table (1/3)Using JSTL for the Table (1/3)
<html>
<head><title>Nutrition Overview</title></head>
<body>
<table border="1">
<tr>
<td>Title</td>
<td>Calories</td>
<td>Fat</td>
<td>Carbohydrates</td>
<td>Protein</td>
<td>Alcohol</td>
</tr>
36
AdvancedServletsand JSP
Using JSTL for the Table (2/3)Using JSTL for the Table (2/3)
<x:forEach select="$recipes//recipe">
f$
<c:
f
orEach var="id" items="
$
{paramValues.selected}">
<x:if select="@id=$id">
<tr>
<td>
<x:out select=".//title"/>
</td>
<td align="right">
<x:out select=".//nutrition/@calories"/>
</td>
<td align="right">
<x:out select=".//nutrition/@fat"/>
</td>
<td align="right">
<x:out select=".//nutrition/@carbohydrates"/>
</td>
37
AdvancedServletsand JSP
Using JSTL for the Table (3/3)Using JSTL for the Table (3/3)
<td align="right">
<x:outselect
"
//nutrition/@protein
"
/>
<x:out

select
=.
//nutrition/@protein/>
</td>
<td align="right">
x:outselect"//nutrition/@alcohol"/
<
x:out

select
=
"
.
//nutrition/@alcohol"/
>
<x:if select="not(.//nutrition/@alcohol)">
0%
/if
<
/
x:
if
>
</td>
</tr>
/if
<
/
x:
if
>
</c:forEach>
</x:forEach>
</table>
</body>
</html>
38
AdvancedServletsand JSP
Evaluation of TagsEvaluation of Tags

MakeWebapplicationsavailabletoa

Make

Web

applications

available

to

a

wider range of developers
Mbdtttliti

M
ay
b
e use
d

t
o s
t
ruc
t
ure app
li
ca
ti
ons
A myriad of domain-specific languages

Brittleimplementationhardtodebug
Brittle

implementation
,
hard

to

debug
39
AdvancedServletsand JSP
The ModelThe Model--ViewView--Controller PatternController Pattern
Model
View
Ctll
encapsulatesdata
provides views
to clients
C
on
t
ro
ll
e
r
encapsulates

data

representation and
business logic
hdlitti
h
an
dl
es
i
n
t
erac
ti
ons
with clients
40
AdvancedServletsand JSP
Model 2 Model 2 ArchitectureArchitecture
Model 2 is an MVC architecture
41
AdvancedServletsand JSP
The Benefit of MVCThe Benefit of MVC
Separation of concerns!
(highcohesion

lowcoupling)
(high

cohesion

low

coupling)
42
AdvancedServletsand JSP
Using MVCUsing MVC
Controller: one servlet
View: JSP pages

䵯摥氺灵牥J慶a(eg䩡癡䉥慮猩

䵯摥氺

灵牥

䩡癡


.
g

䩡癡䉥慮猩
[
䕸慭
p
汥⁩渠瑨攠扯潫㨠䉵獩湥獳⁃慲搠卥牶敲
]
孰]

䅤癡湣敤卥牶汥瑳慮搠䩓a
SummarySummary
JSP tem
p
latesare HTML/XHTML
p
a
g
es with
p
pg
embedded code
The simple expression languageis often
sufficient in place of full-blown Java code
Tag files and librariesallow code to be hidden
under a tag-like syntax
MVCprovides separation of programming and
HTML design tasks
44
AdvancedServletsand JSP