Advanced Servlets and JSP

51 downloads 198 Views 135KB Size Report
Example: SessionMonitor (1/2) import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http. ; public class SessionMonitor implements ...
Advanced Servlets and JSP

Advanced Servlets Features  Listeners se es  Filters and wrappers  Request dispatchers  Security

Advanced Servlets and JSP

2

Listeners – also called observers or event handlers  ServletContextListener – Web application initialized / shut down  ServletRequestListener – request handler starting / finishing  HttpSessionListener – session created / invalidated  ServletContextAttributeListener – context attribute added / removed / replaced  HttpSessionAttributeListener – session attribute added / removed / replaced Advanced Servlets and JSP

3

Example: SessionMonitor (1/2) import javax.servlet.*; import javax.servlet.http. 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 sessionCreated(HttpSessionEvent se) { active++; if (active>max) max = active; store(se.getSession().getServletContext()); } Advanced Servlets and JSP

4

Example: SessionMonitor (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: SessionMonitor Advanced Servlets and JSP

5

Filters  Code being g executed before and after the servlet • executed in stack-like fashion with servlet at the bottom

 Can intercept and redirect processing • security • auditing

 Can modify requests and responses • data d t conversion i (XSLT (XSLT, gzip, i ...)) • specialized caching

– all without changing the existing servlet code! Advanced Servlets and JSP

6

Example: LoggingFilter (1/2) import java.io.*; import javax.servlet. javax.servlet.*; ; import javax.servlet.http.*; public class LoggingFilter implements Filter { ServletContext context; int counter; public void init(FilterConfig c) throws ServletException { context = c.getServletContext(); } public void destroy() {}

Advanced Servlets and JSP

7

Example: LoggingFilter (2/2) public void doFilter(ServletRequest request, ServletResponse p response, 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 g( processing p g request q #"+n+", , "+(t2-t1)+" ( ) ms"); ); } }

Advanced Servlets and JSP

8

Registration of Filters in web.xml ... My Logging Filter My Filter LoggingFilter My My Logging Filter /* ...

Advanced Servlets and JSP

9

Wrappers  Used byy filters to modify y requests q and responses p

 HttpServletRequestWrapper  HttpServletResponseWrapper  Example: performing server server-side side XSLT transformation for older browsers Advanced Servlets and JSP

10

Example: XSLTFilter (1/5) import import import import import import import import

java.io.*; java.util. java.util.*; ; javax.servlet.*; javax.servlet.http.*; org.jdom. org jdom *; ; org.jdom.transform.*; org.jdom.input.*; org.jdom.output. org jdom output *; ;

public class XSLTFilter implements Filter { ServletContext context; public void init(FilterConfig c) throws ServletException { context = c.getServletContext(); c getServletContext(); } public bli void id destroy() d t () {} Advanced Servlets and JSP

11

Example: XSLTFilter (2/5) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 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; else res = new BufferingResponseWrapper(hresp); chain doFilter(request res); chain.doFilter(request,

Advanced Servlets and JSP

12

Example: XSLTFilter (3/5) if (!client_capable) { try { hresp.setContentType("application/xhtml+xml"); transform(((BufferingResponseWrapper)res).getReader(), response.getWriter()); } catch h (Throwable ( h bl e) ) { context.log("XSLT transformation error", e); hresp.sendError(500, "XSLT transformation error"); } } } boolean checkXSLTSupport(String user_agent) { if (user_agent==null) return false; return t user_agent.indexOf("MSIE 5.5")!=-1 || user_agent.indexOf("MSIE 6")!=-1 || user agent.indexOf("Gecko")!=-1; user_agent.indexOf( Gecko )! 1; } Advanced Servlets and JSP

13

Example: XSLTFilter (4/5) void transform(Reader in, Writer out) throws JDOMException, IOException { System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); 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); Document h = t.transform(d); (new XMLOutputter()).output(h, out); } }

Advanced Servlets and JSP

14

Example: XSLTFilter (5/5) class BufferingResponseWrapper extends HttpServletResponseWrapper { CharArrayWriter buffer; PrintWriter writer; public BufferingResponseWrapper(HttpServletResponse p g p pp p p res) { super(res); buffer = new CharArrayWriter(); writer = new PrintWriter(buffer); ( ); } public PrintWriter getWriter() { return writer; } Reader getReader() { return new CharArrayReader(buffer.toCharArray()); } } Advanced Servlets and JSP

15

Request Dispatchers  Forwarding g requests q to other resources  Often used with JSP JSP...

Advanced Servlets and JSP

16

Security – Roles and Authentication ... administrator administrator teacher student BASIC Administration /l i fi ... Advanced Servlets and JSP

17

Security Constraints ... Restricted Area /restricted/* url pattern /restricted/* /url pattern GET POST / b ll ti administrator teacher l h / l CONFIDENTIAL ... Advanced Servlets and JSP

18

Programmatic Security Useful request methods:     

getRemoteUser() isUserInRole(String role) i S isSecure() () getAuthType() getAttribute(”javax.servlet.request.X509Certificate”) getAttribute( )

Advanced Servlets and JSP

19

Summary  Servlets closelyy follow the request-response q p pattern from HTTP  Features: • • • • • • •

Multi-threading g Declarative configuration Request q p parsing, g, including g decoding g of form data Shared state Session management g Advanced code structuring: listeners, filters, wrappers Client authentication, SSL

Advanced Servlets and JSP

20

Advanced JSP Features     

XML version of JSP The expression language Tag files JSTL The Model-View-Controller pattern

Advanced Servlets and JSP

21

JSP Pages Are Not XML JSP Color

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated:

 This page generates HTML, not XHTML  is not well well-formed formed XML Advanced Servlets and JSP

22

XML Version of JSP response.addDateHeader("Expires", 0); JSP request.getParameter("color")

Hello World!

int hits = 0; You are visitor number synchronized(this) { out.println(++hits); } since the last time the service was restarted.

/ This page was last updated: new java.util.Date().toLocaleString()

Advanced Servlets and JSP

• Uses • No schema seems to be available • No validation of the output • No validation of Java code • but it’s there... 23

The Expression Language  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 scopes • implicit objects, such as param

 The usual operators are available Advanced Servlets and JSP

24

An Expression Example Addition The sum of ${param.x} and ${param.y} is ${param.x+param.y}

Advanced Servlets and JSP

25

Tag Files Define abstractions as new tags wrap.tag: ${title} j The sum of ${param.x} and ${param.y} is ${param.x+param.y}

Advanced Servlets and JSP

26

Content as a Value: A New Image Tag image.tag: "h // b i dk/i /i /${ }"/

widget jpg widget.jpg

Advanced Servlets and JSP

27

Declaring Variables: A Date Context Tag date.tag:

Advanced Servlets and JSP

28

Using the Date Context In the US today is ${ ${month}/${date}/${year}, h}/${d }/${ } but in Europe it is ${date}/${month}/${year}. y

Advanced Servlets and JSP

29

Quick Poll Tags (1/2) The question has been set to "${question}". ${question} . ${question}? yes no

Advanced Servlets and JSP

30

Quick Poll Tags (2/2) You have voted ${vote}. In favor: ${yes}
Against: ${no}
Total: ${total} Sorry the polls have closed. Sorry, closed

See the tag files in the book... Advanced Servlets and JSP

31

Tag Libraries  Libraries of tags capturing common patterns: • • • • • • • • • •

pagination of large texts date and times database queries regular expressions HTML scraping bar charts cookies e mail e-mail WML ...

Advanced Servlets and JSP

32

JSTL 1.1  JSP Standard Tag Library covers: • • • • • • • • •

assigning to variables writing iti tto th the output t t stream t catching exceptions conditionals di i l iterations URL construction string formatting SQL queries XML manipulation

Advanced Servlets and JSP

33

Selecting Some Recipes

Advanced Servlets and JSP

34

Using JSTL for the Menu Select Some Recipes $recipes//recipe >
/f

Advanced Servlets and JSP

35

Using JSTL for the Table (1/3) Nutrition Overview



Advanced Servlets and JSP

36

Using JSTL for the Table (2/3) $

Advanced Servlets and JSP

37

Using JSTL for the Table (3/3) / if
Title Calories Fat Carbohydrates Protein Alcohol
/> select " //nutrition/@alcohol"/ 0% / if


Advanced Servlets and JSP

38

Evaluation of Tags  Make Web applications available to a wider range of developers  May M b be used d tto structure t t applications li ti  A myriad of domain-specific languages implementation hard to debug  Brittle implementation,

Advanced Servlets and JSP

39

The ModelModel-ViewView-Controller Pattern

View

Model

provides views to clients encapsulates data representation and business logic

C t ll Controller

handles h dl iinteractions t ti with clients Advanced Servlets and JSP

40

Model 2 Architecture  Model 2 is an MVC architecture

Advanced Servlets and JSP

41

The Benefit of MVC

Separation of concerns! (high cohesion – low coupling)

Advanced Servlets and JSP

42

Using MVC  Controller: one servlet  View: JSP pages  Model: pure Java (e (e.g. g JavaBeans)

[[Example p in the book: Business Card Server]]

Advanced Servlets and JSP

43

Summary  JSP templates p are HTML/XHTML p pages g with 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 Advanced Servlets and JSP

44

Suggest Documents