SlideShare a Scribd company logo
AdvancedAdvancedAdvancedAdvanced
ServletsServlets and JSPand JSP
AdvancedAdvanced ServletsServlets FeaturesFeatures
 Listenerss e e s
 Filters and wrappers
 Request dispatchers
 SecuritySecurity
2Advanced Servlets and JSP
ListenersListeners
– also called observers or event handlers
 ServletContextListener
– Web application initialized / shut downWeb application initialized / shut down
 ServletRequestListener
– request handler starting / finishingrequest handler starting / finishing
 HttpSessionListener
– session created / invalidatedsession created / invalidated
 ServletContextAttributeListener
– context attribute added / removed / replacedcontext attribute added / removed / replaced
 HttpSessionAttributeListener
– session attribute added / removed / replaced
3Advanced Servlets and JSP
– session attribute added / removed / replaced
Example:Example: SessionMonitorSessionMonitor (1/2)(1/2)
import javax.servlet.*;
import javax.servlet.http.*;import javax.servlet.http. ;
public class SessionMonitor
implements HttpSessionListener, ServletContextListener {
private int active = 0, max = 0;
public void contextInitialized(ServletContextEvent sce) {
store(sce getSer letConte t())store(sce.getServletContext());
}
public void contextDestroyed(ServletContextEvent sce) {}public void contextDestroyed(ServletContextEvent sce) {}
public void sessionCreated(HttpSessionEvent se) {
active++;
if (active>max)
max = active;
store(se.getSession().getServletContext());
4Advanced Servlets and JSP
}
Example:Example: SessionMonitorSessionMonitor (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 Integer(max));( , g ( ));
}
}
Registration in web.xml:
<listener>
<listener-class>SessionMonitor</listener-class>
<listener>
5Advanced Servlets and JSP
<listener>
FiltersFilters
 Code being executed before and after the servletg
• executed in stack-like fashion with servlet at the bottom
 Can intercept and redirect processingCan intercept and redirect processing
• security
• auditing• auditing
 Can modify requests and responses
d t i (XSLT i )• data conversion (XSLT, gzip, ...)
• specialized caching
– all without changing the existing servlet code!
6Advanced Servlets and JSP
Example:Example: LoggingFilterLoggingFilter (1/2)(1/2)
import java.io.*;
import javax.servlet.*;import javax.servlet. ;
import javax.servlet.http.*;
public class LoggingFilter implements Filter {public class LoggingFilter implements Filter {
ServletContext context;
int counter;
public void init(FilterConfig c) throws ServletException {
context = c.getServletContext();
}}
public void destroy() {}
7Advanced Servlets and JSP
Example:Example: LoggingFilterLoggingFilter (2/2)(2/2)
public void doFilter(ServletRequest request,
ServletResponse response,p p
FilterChain chain)
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.log("done processing request #"+n+", "+(t2-t1)+" ms");g( p g q , ( ) );
}
}
8Advanced Servlets and JSP
Registration of Filters inRegistration of Filters in web.xmlweb.xml
<web-app ...>pp
...
<filter>
<filter name>My Logging Filter</filter name><filter-name>My Logging Filter</filter-name>
<filter-class>LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>My Logging Filter</filter-name><filter name>My Logging Filter</filter name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
9Advanced Servlets and JSP
WrappersWrappers
 Used by filters to modify requests and responsesy y q p
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 Example: performing server-side XSLTExample: performing server side XSLT
transformation for older browsers
10Advanced Servlets and JSP
Example:Example: XSLTFilterXSLTFilter (1/5)(1/5)
import java.io.*;
import java.util.*;import java.util. ;
import javax.servlet.*;
import javax.servlet.http.*;
import org jdom *;import org.jdom. ;
import org.jdom.transform.*;
import org.jdom.input.*;
import org jdom output *;import org.jdom.output. ;
public class XSLTFilter implements Filter {
ServletContext context;ServletContext context;
public void init(FilterConfig c) throws ServletException {
context c getServletContext();context = c.getServletContext();
}
bli id d t () {}
11Advanced Servlets and JSP
public void destroy() {}
Example:Example: XSLTFilterXSLTFilter (2/5)(2/5)
public void doFilter(ServletRequest request,
ServletResponse response,ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest)request;HttpServletRequest hreq = (HttpServletRequest)request;
HttpServletResponse hresp = (HttpServletResponse)response;
boolean client_capable =
checkXSLTSupport(hreq getHeader("User-Agent"));checkXSLTSupport(hreq.getHeader( User-Agent ));
ServletResponse res;
if (client_capable)
res = response;res = response;
else
res = new BufferingResponseWrapper(hresp);
chain doFilter(request res);chain.doFilter(request, res);
12Advanced Servlets and JSP
Example:Example: XSLTFilterXSLTFilter (3/5)(3/5)
if (!client_capable) {
try {
hresp.setContentType("application/xhtml+xml");
transform(((BufferingResponseWrapper)res).getReader(),
response.getWriter());
} h ( h bl ) {} catch (Throwable e) {
context.log("XSLT transformation error", e);
hresp.sendError(500, "XSLT transformation error");
}}
}
}
boolean checkXSLTSupport(String user_agent) {
if (user_agent==null)
return false;
treturn
user_agent.indexOf("MSIE 5.5")!=-1 ||
user_agent.indexOf("MSIE 6")!=-1 ||
user agent.indexOf("Gecko")!=-1;
13Advanced Servlets and JSP
user_agent.indexOf( Gecko )! 1;
}
Example:Example: XSLTFilterXSLTFilter (4/5)(4/5)
void transform(Reader in, Writer out)
throws JDOMException, IOException {throws JDOMException, IOException {
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
SAXBuilder b = new SAXBuilder();SAXBuilder b = new SAXBuilder();
Document d = b.build(in);
List pi = d.getContent(new org.jdom.filter.ContentFilter
(org jdom filter ContentFilter PI));(org.jdom.filter.ContentFilter.PI));
String xsl = ((ProcessingInstruction)(pi.get(0)))
.getPseudoAttributeValue("href");
XSLTransformer t = new XSLTransformer(xsl);XSLTransformer t = new XSLTransformer(xsl);
Document h = t.transform(d);
(new XMLOutputter()).output(h, out);
}}
}
14Advanced Servlets and JSP
Example:Example: XSLTFilterXSLTFilter (5/5)(5/5)
class BufferingResponseWrapper extends HttpServletResponseWrapper {
CharArrayWriter buffer;CharArrayWriter buffer;
PrintWriter writer;
public BufferingResponseWrapper(HttpServletResponse res) {p g p pp p p
super(res);
buffer = new CharArrayWriter();
writer = new PrintWriter(buffer);( );
}
public PrintWriter getWriter() {
return writer;
}
Reader getReader() {
return new CharArrayReader(buffer.toCharArray());
}
15Advanced Servlets and JSP
}
Request DispatchersRequest Dispatchers
 Forwarding requests to other resourcesg q
 Often used with JSP Often used with JSP...
16Advanced Servlets and JSP
SecuritySecurity –– Roles and AuthenticationRoles and Authentication
<web-app ...>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>
/l i fi</login-config>
...
</web-app>
17Advanced Servlets and 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 ll ti</web-resource-collection>
<auth-constraint>
<role-name>administrator</role-name>
l h / l<role-name>teacher</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
18Advanced Servlets and JSP
...
Programmatic SecurityProgrammatic Security
Useful request methods:
 getRemoteUser()
 isUserInRole(String role)
i S () isSecure()
 getAuthType()
 getAttribute(”javax.servlet.request.X509Certificate”)getAttribute( javax.servlet.request.X509Certificate )
19Advanced Servlets and JSP
SummarySummary
 Servlets closely follow the request-responsey q p
pattern from HTTP
 Features:
• Multi-threadingg
• Declarative configuration
• Request parsing, including decoding of form dataq p g, g g
• Shared state
• Session managementg
• Advanced code structuring: listeners, filters, wrappers
• Client authentication, SSL
20Advanced Servlets and JSP
Client authentication, SSL
AdvancedAdvanced JSP FeaturesJSP Features
 XML version of JSP
 The expression language
 Tag files Tag files
 JSTL
 The Model-View-Controller pattern
21Advanced Servlets and 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
 <% %> is not well formed XML
22Advanced Servlets and 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:directive page contentType="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
23Advanced Servlets and JSP
</jsp:element>
</html>
</jsp:root>
• but it’s there...
The Expression LanguageThe Expression Language
 We want to avoid explicit Java code in JSP 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
• variables in the various scopesvariables in the various scopes
• implicit objects, such as param
 The usual operators are available
24Advanced Servlets and JSP
 The usual operators are available
An Expression ExampleAn Expression Example
<html><html>
<head><title>Addition</title></head>
<body bgcolor="${param.color}">
The sum of ${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>
25Advanced Servlets and JSP
Tag FilesTag Files
Define abstractions as new tagsDefine abstractions as new tags
wrap.tag:
<%@ tag %>
<%@ attribute name="title" required="true" %>
<html>
<head><title>${title}</title></head>
<body>
<jsp:doBody/>j
</body>
</html> <%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %>
<foo:wrap title="Addition">
The sum of ${param.x} and ${param.y} is
${param.x+param.y}
</foo:wrap>
26Advanced Servlets and 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 // b i dk/i /i /${ }"/<img src="http://www.brics.dk/ixwt/images/${src}"/>
<%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %>
<foo:image>widget jpg</foo:image><foo:image>widget.jpg</foo:image>
27Advanced Servlets and JSP
Declaring Variables: A Date Context TagDeclaring Variables: A Date Context Tag
date.tag:
<%@ tag import="java.util.*" %>
<%@ variable name-given="date" %>
<%@ variable name-given="month" %><%@ variable name given month %>
<%@ variable name-given="year" %>
<% Calendar cal = new GregorianCalendar();
i d l ( l d )int date = cal.get(Calendar.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));
jspContext setAttribute("year" String valueOf(year));jspContext.setAttribute( year , String.valueOf(year));
%>
<jsp:doBody/>
28Advanced Servlets and JSP
Using the Date ContextUsing the Date Context
<%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %><%@ taglib prefix= foo tagdir= /WEB INF/tags %>
<foo:date>
In the US today is
${ h}/${d }/${ }${month}/${date}/${year},
but in Europe it is
${date}/${month}/${year}.y
</foo:date>
29Advanced Servlets and JSP
Quick Poll Tags (1/2)Quick Poll Tags (1/2)
<%@ taglib prefix="poll" tagdir="/WEB-INF/tags/poll" %><%@ taglib prefix poll tagdir /WEB INF/tags/poll %>
<poll:quickpoll title="Quickies" duration="3600">
<poll:question>
The question has been set to "${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>
30Advanced Servlets and 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>
Sorry the polls have closedSorry, the polls have closed.
</poll:timeout>
</poll:quickpoll>
See the tag files in the book...
31Advanced Servlets and JSP
Tag LibrariesTag Libraries
 Libraries of tags capturing common patterns:Libraries of tags capturing common patterns:
• pagination of large texts
• date and timesdate and times
• database queries
• regular expressions• regular expressions
• HTML scraping
• bar charts• bar charts
• cookies
• e mail• e-mail
• WML
•
32Advanced Servlets and JSP
• ...
JSTL 1.1JSTL 1.1
 JSP Standard Tag Library covers: JSP Standard Tag Library covers:
• assigning to variables
iti t th t t t• writing to the output stream
• catching exceptions
di i l• conditionals
• iterations
• URL construction
• string formatting
• SQL queries
• XML manipulation
33Advanced Servlets and JSP
Selecting Some RecipesSelecting Some Recipes
34Advanced Servlets and 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>Select Some Recipes</title></head><head><title>Select Some Recipes</title></head>
<body>
<form method="post" action="show.jsp">
<x:forEach select="$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</form>
</body>
</html>
35Advanced Servlets and 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>
36Advanced Servlets and JSP
Using JSTL for the Table (2/3)Using JSTL for the Table (2/3)
<x:forEach select="$recipes//recipe">
f $<c:forEach 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>
37Advanced Servlets and JSP
Using JSTL for the Table (3/3)Using JSTL for the Table (3/3)
<td align="right">
<x:out select " //nutrition/@protein"/><x:out select= .//nutrition/@protein />
</td>
<td align="right">
x:out select " //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>
38Advanced Servlets and JSP
Evaluation of TagsEvaluation of Tags
 Make Web applications available to a Make Web applications available to a
wider range of developers
M b d t t t li ti May be used to structure applications
 A myriad of domain-specific languages
 Brittle implementation hard to debugBrittle implementation, hard to debug
39Advanced Servlets and JSP
The ModelThe Model--ViewView--Controller PatternController Pattern
Model View
C t llencapsulates data
provides views
to clients
Controllerencapsulates data
representation and
business logic
h dl i t tihandles interactions
with clients
40Advanced Servlets and JSP
Model 2Model 2 ArchitectureArchitecture
 Model 2 is an MVC architecture
41Advanced Servlets and JSP
The Benefit of MVCThe Benefit of MVC
Separation of concerns!
(high cohesion – low coupling)(high cohesion low coupling)
42Advanced Servlets and JSP
Using MVCUsing MVC
 Controller: one servlet
 View: JSP pages
 Model: pure Java (e g JavaBeans) Model: pure Java (e.g. JavaBeans)
[Example in the book: Business Card Server][ p ]
43Advanced Servlets and JSP
SummarySummary
 JSP templates are HTML/XHTML pages withp p g
embedded code
 The simple expression language is often
sufficient in place of full-blown Java code
 Tag files and libraries allow code to be hidden
under a tag-like syntax
 MVC provides separation of programming and
HTML design tasks
44Advanced Servlets and JSP

More Related Content

PPTX
Jdk 7 4-forkjoin
PPTX
Jersey framework
PDF
Apache Beam de A à Z
PPTX
Jdk(java) 7 - 6 기타기능
PDF
A Playful Introduction to Rx
PDF
Struts2 - 101
PDF
Session 40 : SAGA Overview and Introduction
PDF
RxJava 2.0 介紹
Jdk 7 4-forkjoin
Jersey framework
Apache Beam de A à Z
Jdk(java) 7 - 6 기타기능
A Playful Introduction to Rx
Struts2 - 101
Session 40 : SAGA Overview and Introduction
RxJava 2.0 介紹

What's hot (19)

PDF
Java9 Beyond Modularity - Java 9 más allá de la modularidad
DOCX
Winform
PDF
Riga Dev Day 2016 - Having fun with Javassist
PDF
Programming with ZooKeeper - A basic tutorial
PPTX
EPAM IT WEEK: AEM & TDD. It's so boring...
PDF
Testing Kafka - The Developer Perspective
PPTX
Introduction to rx java for android
PDF
Annotation processing and code gen
PDF
Java 7 LavaJUG
PDF
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
PDF
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
PDF
Tugas 2
PDF
Servletand sessiontracking
PPTX
Nancy + rest mow2012
PDF
Rxjava 介紹與 Android 中的 RxJava
PPTX
SCWCD : Thread safe servlets : CHAP : 8
DOCX
Registro de venta
PPT
Oracle database - Get external data via HTTP, FTP and Web Services
PPTX
Intro to Reactive Thinking and RxJava 2
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Winform
Riga Dev Day 2016 - Having fun with Javassist
Programming with ZooKeeper - A basic tutorial
EPAM IT WEEK: AEM & TDD. It's so boring...
Testing Kafka - The Developer Perspective
Introduction to rx java for android
Annotation processing and code gen
Java 7 LavaJUG
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
Tugas 2
Servletand sessiontracking
Nancy + rest mow2012
Rxjava 介紹與 Android 中的 RxJava
SCWCD : Thread safe servlets : CHAP : 8
Registro de venta
Oracle database - Get external data via HTTP, FTP and Web Services
Intro to Reactive Thinking and RxJava 2
Ad

Viewers also liked (6)

PDF
10 Insightful Quotes On Designing A Better Customer Experience
PDF
Learn BEM: CSS Naming Convention
PPTX
How to Build a Dynamic Social Media Plan
PDF
SEO: Getting Personal
PDF
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
PDF
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
10 Insightful Quotes On Designing A Better Customer Experience
Learn BEM: CSS Naming Convention
How to Build a Dynamic Social Media Plan
SEO: Getting Personal
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Ad

Similar to Advancedservletsjsp (20)

PDF
Prezo tooracleteam (2)
PPT
Java Servlets
PPTX
Servlets - filter, listeners, wrapper, internationalization
PPT
Server-side Technologies in Java
PDF
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
PDF
Solr @ Etsy - Apache Lucene Eurocon
PDF
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
PDF
Introduction tomcat7 servlet3
PPTX
Belfast JUG 23-10-2013
PPTX
Rx workshop
PPT
Chap4 4 1
PDF
JavaOne India 2011 - Servlets 3.0
PPTX
18CSC311J Web Design and Development UNIT-3
PPTX
Ajax
PDF
Azure Durable Functions (2019-03-30)
DOCX
Servlet
ODP
Finagle and Java Service Framework at Pinterest
PDF
Lecture 3: Servlets - Session Management
PDF
Servlet Filter
PPTX
Servlets
Prezo tooracleteam (2)
Java Servlets
Servlets - filter, listeners, wrapper, internationalization
Server-side Technologies in Java
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
Solr @ Etsy - Apache Lucene Eurocon
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Introduction tomcat7 servlet3
Belfast JUG 23-10-2013
Rx workshop
Chap4 4 1
JavaOne India 2011 - Servlets 3.0
18CSC311J Web Design and Development UNIT-3
Ajax
Azure Durable Functions (2019-03-30)
Servlet
Finagle and Java Service Framework at Pinterest
Lecture 3: Servlets - Session Management
Servlet Filter
Servlets

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Big Data Technologies - Introduction.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
KodekX | Application Modernization Development
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation theory and applications.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
The AUB Centre for AI in Media Proposal.docx
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Big Data Technologies - Introduction.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Understanding_Digital_Forensics_Presentation.pptx
KodekX | Application Modernization Development
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation theory and applications.pdf
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Advancedservletsjsp

  • 2. AdvancedAdvanced ServletsServlets FeaturesFeatures  Listenerss e e s  Filters and wrappers  Request dispatchers  SecuritySecurity 2Advanced Servlets and JSP
  • 3. ListenersListeners – also called observers or event handlers  ServletContextListener – Web application initialized / shut downWeb application initialized / shut down  ServletRequestListener – request handler starting / finishingrequest handler starting / finishing  HttpSessionListener – session created / invalidatedsession created / invalidated  ServletContextAttributeListener – context attribute added / removed / replacedcontext attribute added / removed / replaced  HttpSessionAttributeListener – session attribute added / removed / replaced 3Advanced Servlets and JSP – session attribute added / removed / replaced
  • 4. Example:Example: SessionMonitorSessionMonitor (1/2)(1/2) import javax.servlet.*; import javax.servlet.http.*;import javax.servlet.http. ; public class SessionMonitor implements HttpSessionListener, ServletContextListener { private int active = 0, max = 0; public void contextInitialized(ServletContextEvent sce) { store(sce getSer letConte t())store(sce.getServletContext()); } public void contextDestroyed(ServletContextEvent sce) {}public void contextDestroyed(ServletContextEvent sce) {} public void sessionCreated(HttpSessionEvent se) { active++; if (active>max) max = active; store(se.getSession().getServletContext()); 4Advanced Servlets and JSP }
  • 5. Example:Example: SessionMonitorSessionMonitor (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 Integer(max));( , g ( )); } } Registration in web.xml: <listener> <listener-class>SessionMonitor</listener-class> <listener> 5Advanced Servlets and JSP <listener>
  • 6. FiltersFilters  Code being executed before and after the servletg • executed in stack-like fashion with servlet at the bottom  Can intercept and redirect processingCan intercept and redirect processing • security • auditing• auditing  Can modify requests and responses d t i (XSLT i )• data conversion (XSLT, gzip, ...) • specialized caching – all without changing the existing servlet code! 6Advanced Servlets and JSP
  • 7. Example:Example: LoggingFilterLoggingFilter (1/2)(1/2) import java.io.*; import javax.servlet.*;import javax.servlet. ; import javax.servlet.http.*; public class LoggingFilter implements Filter {public class LoggingFilter implements Filter { ServletContext context; int counter; public void init(FilterConfig c) throws ServletException { context = c.getServletContext(); }} public void destroy() {} 7Advanced Servlets and JSP
  • 8. Example:Example: LoggingFilterLoggingFilter (2/2)(2/2) public void doFilter(ServletRequest request, ServletResponse response,p p FilterChain chain) 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.log("done processing request #"+n+", "+(t2-t1)+" ms");g( p g q , ( ) ); } } 8Advanced Servlets and JSP
  • 9. Registration of Filters inRegistration of Filters in web.xmlweb.xml <web-app ...>pp ... <filter> <filter name>My Logging Filter</filter name><filter-name>My Logging Filter</filter-name> <filter-class>LoggingFilter</filter-class> </filter> <filter-mapping> <filter-name>My Logging Filter</filter-name><filter name>My Logging Filter</filter name> <url-pattern>/*</url-pattern> </filter-mapping> ... </web-app> 9Advanced Servlets and JSP
  • 10. WrappersWrappers  Used by filters to modify requests and responsesy y q p  HttpServletRequestWrapper  HttpServletResponseWrapper  Example: performing server-side XSLTExample: performing server side XSLT transformation for older browsers 10Advanced Servlets and JSP
  • 11. Example:Example: XSLTFilterXSLTFilter (1/5)(1/5) import java.io.*; import java.util.*;import java.util. ; import javax.servlet.*; import javax.servlet.http.*; import org jdom *;import org.jdom. ; import org.jdom.transform.*; import org.jdom.input.*; import org jdom output *;import org.jdom.output. ; public class XSLTFilter implements Filter { ServletContext context;ServletContext context; public void init(FilterConfig c) throws ServletException { context c getServletContext();context = c.getServletContext(); } bli id d t () {} 11Advanced Servlets and JSP public void destroy() {}
  • 12. Example:Example: XSLTFilterXSLTFilter (2/5)(2/5) public void doFilter(ServletRequest request, ServletResponse response,ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)request;HttpServletRequest hreq = (HttpServletRequest)request; HttpServletResponse hresp = (HttpServletResponse)response; boolean client_capable = checkXSLTSupport(hreq getHeader("User-Agent"));checkXSLTSupport(hreq.getHeader( User-Agent )); ServletResponse res; if (client_capable) res = response;res = response; else res = new BufferingResponseWrapper(hresp); chain doFilter(request res);chain.doFilter(request, res); 12Advanced Servlets and JSP
  • 13. Example:Example: XSLTFilterXSLTFilter (3/5)(3/5) if (!client_capable) { try { hresp.setContentType("application/xhtml+xml"); transform(((BufferingResponseWrapper)res).getReader(), response.getWriter()); } h ( h bl ) {} catch (Throwable e) { context.log("XSLT transformation error", e); hresp.sendError(500, "XSLT transformation error"); }} } } boolean checkXSLTSupport(String user_agent) { if (user_agent==null) return false; treturn user_agent.indexOf("MSIE 5.5")!=-1 || user_agent.indexOf("MSIE 6")!=-1 || user agent.indexOf("Gecko")!=-1; 13Advanced Servlets and JSP user_agent.indexOf( Gecko )! 1; }
  • 14. Example:Example: XSLTFilterXSLTFilter (4/5)(4/5) void transform(Reader in, Writer out) throws JDOMException, IOException {throws JDOMException, IOException { System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); SAXBuilder b = new SAXBuilder();SAXBuilder b = new SAXBuilder(); Document d = b.build(in); List pi = d.getContent(new org.jdom.filter.ContentFilter (org jdom filter ContentFilter PI));(org.jdom.filter.ContentFilter.PI)); String xsl = ((ProcessingInstruction)(pi.get(0))) .getPseudoAttributeValue("href"); XSLTransformer t = new XSLTransformer(xsl);XSLTransformer t = new XSLTransformer(xsl); Document h = t.transform(d); (new XMLOutputter()).output(h, out); }} } 14Advanced Servlets and JSP
  • 15. Example:Example: XSLTFilterXSLTFilter (5/5)(5/5) class BufferingResponseWrapper extends HttpServletResponseWrapper { CharArrayWriter buffer;CharArrayWriter buffer; PrintWriter writer; public BufferingResponseWrapper(HttpServletResponse res) {p g p pp p p super(res); buffer = new CharArrayWriter(); writer = new PrintWriter(buffer);( ); } public PrintWriter getWriter() { return writer; } Reader getReader() { return new CharArrayReader(buffer.toCharArray()); } 15Advanced Servlets and JSP }
  • 16. Request DispatchersRequest Dispatchers  Forwarding requests to other resourcesg q  Often used with JSP Often used with JSP... 16Advanced Servlets and JSP
  • 17. SecuritySecurity –– Roles and AuthenticationRoles and Authentication <web-app ...>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> /l i fi</login-config> ... </web-app> 17Advanced Servlets and JSP
  • 18. 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 ll ti</web-resource-collection> <auth-constraint> <role-name>administrator</role-name> l h / l<role-name>teacher</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> 18Advanced Servlets and JSP ...
  • 19. Programmatic SecurityProgrammatic Security Useful request methods:  getRemoteUser()  isUserInRole(String role) i S () isSecure()  getAuthType()  getAttribute(”javax.servlet.request.X509Certificate”)getAttribute( javax.servlet.request.X509Certificate ) 19Advanced Servlets and JSP
  • 20. SummarySummary  Servlets closely follow the request-responsey q p pattern from HTTP  Features: • Multi-threadingg • Declarative configuration • Request parsing, including decoding of form dataq p g, g g • Shared state • Session managementg • Advanced code structuring: listeners, filters, wrappers • Client authentication, SSL 20Advanced Servlets and JSP Client authentication, SSL
  • 21. AdvancedAdvanced JSP FeaturesJSP Features  XML version of JSP  The expression language  Tag files Tag files  JSTL  The Model-View-Controller pattern 21Advanced Servlets and JSP
  • 22. 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  <% %> is not well formed XML 22Advanced Servlets and JSP  <%...%> is not well-formed XML
  • 23. 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:directive page contentType="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 23Advanced Servlets and JSP </jsp:element> </html> </jsp:root> • but it’s there...
  • 24. The Expression LanguageThe Expression Language  We want to avoid explicit Java code in JSP 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 • variables in the various scopesvariables in the various scopes • implicit objects, such as param  The usual operators are available 24Advanced Servlets and JSP  The usual operators are available
  • 25. An Expression ExampleAn Expression Example <html><html> <head><title>Addition</title></head> <body bgcolor="${param.color}"> The sum of ${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> 25Advanced Servlets and JSP
  • 26. Tag FilesTag Files Define abstractions as new tagsDefine abstractions as new tags wrap.tag: <%@ tag %> <%@ attribute name="title" required="true" %> <html> <head><title>${title}</title></head> <body> <jsp:doBody/>j </body> </html> <%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %> <foo:wrap title="Addition"> The sum of ${param.x} and ${param.y} is ${param.x+param.y} </foo:wrap> 26Advanced Servlets and JSP
  • 27. 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 // b i dk/i /i /${ }"/<img src="http://www.brics.dk/ixwt/images/${src}"/> <%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %> <foo:image>widget jpg</foo:image><foo:image>widget.jpg</foo:image> 27Advanced Servlets and JSP
  • 28. Declaring Variables: A Date Context TagDeclaring Variables: A Date Context Tag date.tag: <%@ tag import="java.util.*" %> <%@ variable name-given="date" %> <%@ variable name-given="month" %><%@ variable name given month %> <%@ variable name-given="year" %> <% Calendar cal = new GregorianCalendar(); i d l ( l d )int date = cal.get(Calendar.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)); jspContext setAttribute("year" String valueOf(year));jspContext.setAttribute( year , String.valueOf(year)); %> <jsp:doBody/> 28Advanced Servlets and JSP
  • 29. Using the Date ContextUsing the Date Context <%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %><%@ taglib prefix= foo tagdir= /WEB INF/tags %> <foo:date> In the US today is ${ h}/${d }/${ }${month}/${date}/${year}, but in Europe it is ${date}/${month}/${year}.y </foo:date> 29Advanced Servlets and JSP
  • 30. Quick Poll Tags (1/2)Quick Poll Tags (1/2) <%@ taglib prefix="poll" tagdir="/WEB-INF/tags/poll" %><%@ taglib prefix poll tagdir /WEB INF/tags/poll %> <poll:quickpoll title="Quickies" duration="3600"> <poll:question> The question has been set to "${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> 30Advanced Servlets and JSP
  • 31. 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> Sorry the polls have closedSorry, the polls have closed. </poll:timeout> </poll:quickpoll> See the tag files in the book... 31Advanced Servlets and JSP
  • 32. Tag LibrariesTag Libraries  Libraries of tags capturing common patterns:Libraries of tags capturing common patterns: • pagination of large texts • date and timesdate and times • database queries • regular expressions• regular expressions • HTML scraping • bar charts• bar charts • cookies • e mail• e-mail • WML • 32Advanced Servlets and JSP • ...
  • 33. JSTL 1.1JSTL 1.1  JSP Standard Tag Library covers: JSP Standard Tag Library covers: • assigning to variables iti t th t t t• writing to the output stream • catching exceptions di i l• conditionals • iterations • URL construction • string formatting • SQL queries • XML manipulation 33Advanced Servlets and JSP
  • 34. Selecting Some RecipesSelecting Some Recipes 34Advanced Servlets and JSP
  • 35. 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>Select Some Recipes</title></head><head><title>Select Some Recipes</title></head> <body> <form method="post" action="show.jsp"> <x:forEach select="$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</form> </body> </html> 35Advanced Servlets and JSP
  • 36. 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> 36Advanced Servlets and JSP
  • 37. Using JSTL for the Table (2/3)Using JSTL for the Table (2/3) <x:forEach select="$recipes//recipe"> f $<c:forEach 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> 37Advanced Servlets and JSP
  • 38. Using JSTL for the Table (3/3)Using JSTL for the Table (3/3) <td align="right"> <x:out select " //nutrition/@protein"/><x:out select= .//nutrition/@protein /> </td> <td align="right"> x:out select " //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> 38Advanced Servlets and JSP
  • 39. Evaluation of TagsEvaluation of Tags  Make Web applications available to a Make Web applications available to a wider range of developers M b d t t t li ti May be used to structure applications  A myriad of domain-specific languages  Brittle implementation hard to debugBrittle implementation, hard to debug 39Advanced Servlets and JSP
  • 40. The ModelThe Model--ViewView--Controller PatternController Pattern Model View C t llencapsulates data provides views to clients Controllerencapsulates data representation and business logic h dl i t tihandles interactions with clients 40Advanced Servlets and JSP
  • 41. Model 2Model 2 ArchitectureArchitecture  Model 2 is an MVC architecture 41Advanced Servlets and JSP
  • 42. The Benefit of MVCThe Benefit of MVC Separation of concerns! (high cohesion – low coupling)(high cohesion low coupling) 42Advanced Servlets and JSP
  • 43. Using MVCUsing MVC  Controller: one servlet  View: JSP pages  Model: pure Java (e g JavaBeans) Model: pure Java (e.g. JavaBeans) [Example in the book: Business Card Server][ p ] 43Advanced Servlets and JSP
  • 44. SummarySummary  JSP templates are HTML/XHTML pages withp p g embedded code  The simple expression language is often sufficient in place of full-blown Java code  Tag files and libraries allow code to be hidden under a tag-like syntax  MVC provides separation of programming and HTML design tasks 44Advanced Servlets and JSP