Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. AdvancedAdvancedAdvancedAdvancedServletsServlets and JSPand JSP
  2. 2. AdvancedAdvanced ServletsServlets FeaturesFeatures Listenerss e e s Filters and wrappers Request dispatchers SecuritySecurity2Advanced Servlets and JSP
  3. 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 / replaced3Advanced Servlets and JSP– session attribute added / removed / replaced
  4. 4. Example:Example: SessionMonitorSessionMonitor (1/2)(1/2)import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.http. ;public class SessionMonitorimplements 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. 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. 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 responsesd t i (XSLT i )• data conversion (XSLT, gzip, ...)• specialized caching– all without changing the existing servlet code!6Advanced Servlets and JSP
  7. 7. Example:Example: LoggingFilterLoggingFilter (1/2)(1/2)import*;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. 8. Example:Example: LoggingFilterLoggingFilter (2/2)(2/2)public void doFilter(ServletRequest request,ServletResponse response,p pFilterChain 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. 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. 10. WrappersWrappers Used by filters to modify requests and responsesy y q p HttpServletRequestWrapper HttpServletResponseWrapper Example: performing server-side XSLTExample: performing server side XSLTtransformation for older browsers10Advanced Servlets and JSP
  11. 11. Example:Example: XSLTFilterXSLTFilter (1/5)(1/5)import*;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 JSPpublic void destroy() {}
  12. 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;elseres = new BufferingResponseWrapper(hresp);chain doFilter(request res);chain.doFilter(request, res);12Advanced Servlets and JSP
  13. 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;treturnuser_agent.indexOf("MSIE 5.5")!=-1 ||user_agent.indexOf("MSIE 6")!=-1 ||user agent.indexOf("Gecko")!=-1;13Advanced Servlets and JSPuser_agent.indexOf( Gecko )! 1;}
  14. 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 =;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. 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 psuper(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. 16. Request DispatchersRequest Dispatchers Forwarding requests to other resourcesg q Often used with JSP Often used with JSP...16Advanced Servlets and JSP
  17. 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. 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. 19. Programmatic SecurityProgrammatic SecurityUseful 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. 20. SummarySummary Servlets closely follow the request-responsey q ppattern 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, SSL20Advanced Servlets and JSPClient authentication, SSL
  21. 21. AdvancedAdvanced JSP FeaturesJSP Features XML version of JSP The expression language Tag files Tag files JSTL The Model-View-Controller pattern21Advanced Servlets and JSP
  22. 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 XML22Advanced Servlets and JSP <%...%> is not well-formed XML
  23. 23. XML Version of JSPXML Version of JSP<jsp:root xmlns:jsp="" version="2.0"xmlns="http://"><jsp:directive page contentType="text/html"/>• Uses <jsp:...>< 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 validationof the outputYou 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 code23Advanced Servlets and JSP</jsp:element></html></jsp:root>• but it’s there...
  24. 24. The Expression LanguageThe Expression Language We want to avoid explicit Java code in JSP We want to avoid explicit Java code in JSPtemplates 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 available24Advanced Servlets and JSP The usual operators are available
  25. 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. 26. Tag FilesTag FilesDefine abstractions as new tagsDefine abstractions as new tagswrap.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. 27. Content as a Value: A New Image TagContent as a Value: A New Image Tagimage.tag:image.tag:<%@ tag %><jsp:doBody var="src"/>i "h // b i dk/i /i /${ }"/<img src="${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. 28. Declaring Variables: A Date Context TagDeclaring Variables: A Date Context Tagdate.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. 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. 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. 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. 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. 33. JSTL 1.1JSTL 1.1 JSP Standard Tag Library covers: JSP Standard Tag Library covers:• assigning to variablesiti t th t t t• writing to the output stream• catching exceptionsdi i l• conditionals• iterations• URL construction• string formatting• SQL queries• XML manipulation33Advanced Servlets and JSP
  34. 34. Selecting Some RecipesSelecting Some Recipes34Advanced Servlets and JSP
  35. 35. Using JSTL for the MenuUsing JSTL for the Menu<%@ taglib uri="" prefix="c"%><%@ taglib uri="" prefix="x"%><c:import url="" 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. 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. 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. 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. 39. Evaluation of TagsEvaluation of Tags Make Web applications available to a Make Web applications available to awider range of developersM 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 debug39Advanced Servlets and JSP
  40. 40. The ModelThe Model--ViewView--Controller PatternController PatternModel ViewC t llencapsulates dataprovides viewsto clientsControllerencapsulates datarepresentation andbusiness logich dl i t tihandles interactionswith clients40Advanced Servlets and JSP
  41. 41. Model 2Model 2 ArchitectureArchitecture Model 2 is an MVC architecture41Advanced Servlets and JSP
  42. 42. The Benefit of MVCThe Benefit of MVCSeparation of concerns!(high cohesion – low coupling)(high cohesion low coupling)42Advanced Servlets and JSP
  43. 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. 44. SummarySummary JSP templates are HTML/XHTML pages withp p gembedded code The simple expression language is oftensufficient in place of full-blown Java code Tag files and libraries allow code to be hiddenunder a tag-like syntax MVC provides separation of programming andHTML design tasks44Advanced Servlets and JSP