SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialJeff Smith
 
EPAM IT WEEK: AEM & TDD. It's so boring...
EPAM IT WEEK: AEM & TDD. It's so boring...EPAM IT WEEK: AEM & TDD. It's so boring...
EPAM IT WEEK: AEM & TDD. It's so boring...Andrew Manuev
 
Taking advantage of Prometheus relabeling
Taking advantage of Prometheus relabelingTaking advantage of Prometheus relabeling
Taking advantage of Prometheus relabelingJulien Pivotto
 
Testing Kafka - The Developer Perspective
Testing Kafka - The Developer PerspectiveTesting Kafka - The Developer Perspective
Testing Kafka - The Developer Perspectivemaiktoepfer
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code genkoji lin
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8Ben Abdallah Helmi
 
Registro de venta
Registro de ventaRegistro de venta
Registro de ventalupe ga
 
Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesKim Berg Hansen
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 

Mais procurados (20)

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

Destaque

10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer ExperienceYuan Wang
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanPost Planner
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting PersonalKirsty Hulse
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldabaux singapore
 

Destaque (6)

10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media Plan
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
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?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Semelhante a Advancedservletsjsp

Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)Sharma Podila
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in JavaAnirban Majumdar
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Augemfrancis
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3JavaEE Trainers
 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013eamonnlong
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0Arun Gupta
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Paco de la Cruz
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 

Semelhante a Advancedservletsjsp (20)

Prezo tooracleteam (2)
Prezo tooracleteam (2)Prezo tooracleteam (2)
Prezo tooracleteam (2)
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Server-side Technologies in Java
Server-side Technologies in JavaServer-side Technologies in Java
Server-side Technologies in Java
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Belfast JUG 23-10-2013
Belfast JUG 23-10-2013Belfast JUG 23-10-2013
Belfast JUG 23-10-2013
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
 
Ajax
AjaxAjax
Ajax
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
Servlet
Servlet Servlet
Servlet
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Servlets
ServletsServlets
Servlets
 
servlets
servletsservlets
servlets
 

Último

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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