SlideShare une entreprise Scribd logo
1  sur  57
Télécharger pour lire hors ligne
An Introduction to XML and Web Technologies


Programming Web Applications
       with Servlets
         ith S  l t



        Anders Møller & Michael I. Schwartzbach
               © 2006 Addison Wesley
                        Addison-Wesley
Objectives

      How to program Web applications using servlets
      Advanced concepts such as listeners filters and
                 concepts,         listeners, filters,
      request dispatchers
      Running servlets using the Tomcat server




An Introduction to XML and Web Technologies                2
Web Applications

      Web servers
        • return files
        • run programs
      Web application: collection of servlets,
      JSP pages, HTML pages, GIF files, ...
      Servlets: programmed using the servlet API
                                               API,
      which is directly based on HTTP
      Lifecycles
        • application                  (shared state)
        • session                      (session state)
        • i t
          interaction
                 ti                    (transient state)
                                       (t    i t t t )
An Introduction to XML and Web Technologies                3
An Example Servlet

import java.io.*;
  p    j        ;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
                              l                   )
          throws IOException, ServletException {
         p                yp              ;
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<html><head><title>ServletExample</title></head>"+
                  "<body><h1>Hello World!</h1> +
                   <body><h1>Hello World!</h1>"+
                  "This page was last updated: "+
                  new java.util.Date()+
                  "</body></html>");
    }
}

An Introduction to XML and Web Technologies                             4
Requests

      Methods in HttpServletRequest
        •   getHeader
        •   getParameter
        •   getInputStream
        •   getRemoteHost, getRemoteAddr, getRemotePort
                tR t H t     tR   t Add     tR   t P t
        •   ...




An Introduction to XML and Web Technologies               5
Example: HttpServletRequest (1/2)
public class Requests extends HttpServlet {
  public oid doGet(HttpSer letReq est req est
  p blic void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>Requests</title></head><body>");
    out.println("<h1>Hello, visitor from "+request.getRemoteHost()+"</h1>");
    String useragent = request.getHeader("User-Agent");
    if (useragent!=null)
       (useragent! null)
      out.println("You seem to be using "+useragent+"<p>");
    String name = request.getParameter("name");
    if (name null)
       (name==null)
      out.println("No <tt>name</tt> field was given!");
    else
      out.println("The value of the <tt>name</tt> fi ld is: <tt>" +
            i l (" h     l    f h            /    field i       "
                  htmlEscape(name) + "</tt>");
    out.println("</body></html>");
  }
 An Introduction to XML and Web Technologies                               6
Example: HttpServletRequest (2/2)
  public void doPost(HttpServletRequest request,
                     HttpServletResponse
                     HttpSer letResponse response)
        throws IOException, ServletException {
   doGet(request, response);
  }
  private String htmlEscape(String s) {
    StringBuffer b = new StringBuffer();
    for (int i = 0; i<s.length(); i++) {
      char c = s.charAt(i);
      switch (c) {
        it h ( )
        case '<': b.append("&lt;"); break;
        case '>': b.append("&gt;"); break;
        case '"': b.append("&quot;"); break;
        case ''': b.append("&apos;"); break;
        case '&': b.append("&amp;"); break;
        default: b.append(c);
    } }
    return b.toString();
} }
 An Introduction to XML and Web Technologies         7
Responses

      Methods in HttpServletResponse
        •   setStatus
        •   addHeader,
            addHeader setHeader
        •   getOutputStream, getWriter
        •   setContentType
                tC t tT
        •   sendError, sendRedirect
        •   ...




An Introduction to XML and Web Technologies           8
Example: BusinessCardServlet

 public class BusinessCardServlet extends HttpServlet {

     public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, ServletException {
          p                 yp            ;
       response.setContentType("text/xml;charset=UTF-8");    ;
       long expires = new Date().getTime() + 1000*60*60*24;
       response.addDateHeader("Expires", expires);
       XMLOutputter outputter = new XMLOutputter();
       outputter.output(getBusinessCard(),
                         response.getOutputStream());
                         response getOutputStream());
     }
     ...                               using JDOM to generate an XML
 }                                            document with a reference to an
                                              XSLT stylesheet

An Introduction to XML and Web Technologies                                     9
Servlet Contexts

      One ServletContext object for each
      Web application

      getServerInfo
      getInitParameter
      ...
      Shared state:
        • setAttribute(“name”, value)
        • getAttribute(“name”)
          getAttribute(      )

        • don’t use for mission critical data!
          don t
An Introduction to XML and Web Technologies           10
Example: A Polling Service

 A Web application consisting of
      QuickPollQuestion.html
      QuickPollSetup.java
      Q i kP llS t   j
      QuickPollAsk.java
      QuickPollVote.java
      Q
      QuickPollResults.java
                       j




An Introduction to XML and Web Technologies      11
Example:
      Example: QuickPollQuestion.html

     <html>
     <head><title>QuickPoll</title></head>
     <body>
     <h1>QuickPoll</h1>
     <form method=post action=setup>
                  p               p
     What is your question?<br>
     <input name=question type=text size=40>?<br>
     <input type=submit name=submit
            value="Register my question">
     </form>
     </body>
     </html>



An Introduction to XML and Web Technologies         12
Example:
            Example: QuickPollSetup.java

 p
 public class Q
              QuickPollSetup extends HttpServlet {
                            p             p
   public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
         throws IOException, ServletException {
                 IOException
     String q = request.getParameter("question");
     ServletContext c = getServletContext();
     c.setAttribute("question", q);
     c.setAttribute("yes", new Integer(0));
     c.setAttribute( no
     c setAttribute("no", new Integer(0));
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("<html><head><title>QuickPoll</title></head><body>"+
           i (" h l h d        i l     i k ll / i l    /h d b d "
                "<h1>QuickPoll</h1>"+
                "Your question has been registered. "+
                      q                    g
                "Let the vote begin!"+
                "</body></html>");
 } }

An Introduction to XML and Web Technologies                           13
Example: QuickPollAsk.java
public class QuickPollAsk extends HttpServlet {
  public void d
    bli    id doGet(HttpServletRequest request,
                   (        l
                    HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print( <html><head><title>QuickPoll</title></head><body> +
    out print("<html><head><title>QuickPoll</title></head><body>"+
              "<h1>QuickPoll</h1>"+
              "<form method=post action=vote>");
    String question =
      (String)getServletContext().getAttribute("question");
    out.print(question+ ?<p> );
    out.print(question+"?<p>");
    out.print("<input name=vote type=radio value=yes> yes<br>"+
              "<input name=vote type=radio value=no> no<p>"+
              "<input type=submit name=submit value=Vote>"+
              " i            b i         b i    l        "
              "</form>"+
              "</body></html>");
} }
An Introduction to XML and Web Technologies                          14
Example: QuickPollVote.java (1/2)

p
public class QuickPollVote extends HttpServlet {
             Q                         p
  public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException {
    String vote = request.getParameter("vote");
    ServletContext c = getServletContext();
    if (vote.equals("yes")) {
      int yes = ((Integer)c.getAttribute("yes")).intValue();
      yes++;
      c.setAttribute("yes", new Integer(yes));
    } else if (vote.equals( no )) {
               (vote equals("no"))
      int no = ((Integer)c.getAttribute("no")).intValue();
      no++;
      c.setAttribute("no", new Integer(no));
    }


 An Introduction to XML and Web Technologies                   15
Example: QuickPollVote.java (2/2)

         response.setContentType("text/html");
            p                yp (     /     );
         PrintWriter out = response.getWriter();
         out.print("<html><head><title>QuickPoll</title></head><body>"+
                   "<h1>QuickPoll</h1>"+
                   "Thank you for your vote!"+
                   "</body></html>");
                    </body></html> );
     }
}




    An Introduction to XML and Web Technologies                      16
Example: QuickPollResult.java (1/2)

p
public class QuickPollResults extends HttpServlet {
             Q                           p
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws IOException, ServletException {
    ServletContext c = getServletContext();
    String question = (String)c.getAttribute("question");
                      (String)c.getAttribute( question );
    int yes = ((Integer)c.getAttribute("yes")).intValue();
    int no = ((Integer)c.getAttribute("no")).intValue();
    int total = yes+no;
    response.setContentType("text/html");
    response.setDateHeader( Expires
    response setDateHeader("Expires", 0);
    response.setHeader("Cache-Control",
                       "no-store, no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    PrintWriter out = response.getWriter();


 An Introduction to XML and Web Technologies                     17
Example: QuickPollResult.java (2/2)

      out.print("<html><head><title>QuickPoll</title></head><body>"+
          p    (                     Q         /       /        y
                 "<h1>QuickPoll</h1>");
      if (total==0)
        out.print("No votes yet...");
      else {
        out.print(question + "?<p>"+"<table border 0> +
                               ?<p> + <table border=0>"+
         "<tr><td>Yes:<td>"+drawBar(300*yes/total)+"<td>"+yes+
         "<tr><td>No:<td>"+drawBar(300*no/total)+"<td>"+no+
         "</table>");
      }
      out.print( </body></html> );
      out print("</body></html>");
  }

  String drawBar(int length) {
    return "<table><tr><td bgcolor=black height=20 width="+
           length+"></table>";
} }
 An Introduction to XML and Web Technologies                      18
Problems in QuickPoll

      Need access control to QuickPollSetup
      No escaping of special characters
      Need to check right order of execution
      Need to check that expected form field data is
      present
      No synchronization in QuickPollVote
      Should store state in database
      Redundancy in HTML generation



An Introduction to XML and Web Technologies            19
Example: Shopping Cart




An Introduction to XML and Web Technologies      20
Sessions

      One HttpSession object for each session
        • obtained by getSession in the
          HttpServletRequest object
          Htt S     l tR      t bj t


      Session state:
        • setAttribute(”name”, value)
          setAttribute(
        • getAttribute(”name”)


      Hides the technical details of tracking users with
      URL rewriting / cookies / SSL sessions

An Introduction to XML and Web Technologies                21
Web Applications

 A Web app is structured as a directory:
   myapp/
    – contains HTML/CSS/GIF/... files
   myapp/WEB-INF/
          /WEB INF/
    – contains the deployment descriptor web.xml
   myapp/ /WEB-INF/classes/
                     / l         /
    – contains servlet class files
      (in subdirs corresponding to package names)
   myapp/WEB-INF/lib/
          /WEB INF/lib/
    – contains extra jar files

An Introduction to XML and Web Technologies         22
Deployment Descriptors

 An XML file web xml describing
                web.xml
   mapping from URIs to application resources
   initialization parameters
   security constraints
   registration of listeners and filters




An Introduction to XML and Web Technologies      23
Example web.xml

 <web app xmlns="http://java.sun.com/xml/ns/j2ee”
 <web-app xmlns http://java.sun.com/xml/ns/j2ee
          version="2.4">

      <display-name>A Small Web Application</display-name>
       di l         A S ll W b A li ti      /di l

      <servlet>
       <servlet-name>MyFirstServlet</servlet-name>
       <servlet-class>HelloWorld</servlet-class>
      </servlet>

      <servlet mapping>
      <servlet-mapping>
        <servlet-name>MyFirstServlet</servlet-name>
             p       /     / /     p
        <url-pattern>/hello/*</url-pattern>
      </servlet-mapping>

 </web-app>
  / b
An Introduction to XML and Web Technologies              24
The Tomcat Server

      Reference Implementation, Open Source
                Implementation

      common/lib/servlet-api.jar

      bin/startup.sh, bin/shutdown.sh

      conf/server.xml

      webapps/myapp



An Introduction to XML and Web Technologies         25
Advanced Features

      Listeners

      Filters and wrappers

      Request dispatchers
      R     t di   t h

      Security


An Introduction to XML and Web Technologies        26
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
An Introduction to XML and Web Technologies               27
Example: SessionMonitor (1/2)
   import javax.servlet.*;
   import javax.servlet.http.*;

   public class SessionMonitor
       implements HttpSessionListener, ServletContextListener {
     private int active = 0, max = 0;

       public void contextInitialized(ServletContextEvent sce) {
         store(sce.getServletContext());
       }

       public void contextDestroyed(ServletContextEvent sce) {}

       public void sessionCreated(HttpSessionEvent se) {
         active++;
         if (active>max)
           max = active;
         store(se.getSession().getServletContext());
       }
An Introduction to XML and Web Technologies                        28
Example: SessionMonitor (2/2)
   public void sessionDestroyed(HttpSessionEvent se) {
       active--;
       store(se.getSession().getServletContext());
     }

       private void store(ServletContext c) {
         c.setAttribute( sessions_active
         c setAttribute("sessions active", new Integer(active));
         c.setAttribute("sessions_max", new Integer(max));
       }
   }



 Registration in web.xml:
       <listener>
         <listener-class>SessionMonitor</listener-class>
       <listener>

An Introduction to XML and Web Technologies                        29
Filters

      Code being executed before and after the servlet
        • executed in stack-like fashion with servlet at the bottom
      Can intercept and redirect processing
        • security
        • auditing
      Can
      C modify requests and responses
          dif        t    d
        • data conversion (XSLT, gzip, ...)
        • specialized caching


 – all without changing the existing servlet code!

An Introduction to XML and Web Technologies                       30
Example: LoggingFilter (1/2)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoggingFilter implements Filter {
  ServletContext context;
  int counter;

   p
   public void init(FilterConfig c) throws ServletException {
                               g                      p
     context = c.getServletContext();
   }

   public void destroy() {}




An Introduction to XML and Web Technologies                     31
Example: LoggingFilter (2/2)
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                             l
                         FilterChain chain)
        throws IOException, ServletException {
      String uri = ((HttpServletRequest)request).getRequestURI();
      int n = ++counter;
      context.log( starting
      context log("starting processing request # +n+ ("+uri+")");
                                               #"+n+" ( +uri+ ) );
      long t1 = System.currentTimeMillis();
      chain.doFilter(request, response);
      long t2 = System.currentTimeMillis();
      context.log("done processing request #"+n+", "+(t2-t1)+" ms");
    }
}




An Introduction to XML and Web Technologies                            32
Registration of Filters in web.xml

         <web-app ...>
            b
           ...
           <filter>
              <filter-name>My Logging Filter</filter-name>
              <filter-class>LoggingFilter</filter-class>
           </filter>

           <filter-mapping>
            fil        i
             <filter-name>My Logging Filter</filter-name>
             <url-pattern>/ </url-pattern>
             <url-pattern>/*</url-pattern>
           </filter-mapping>
           ...
         </web-app>



An Introduction to XML and Web Technologies                  33
Wrappers

      Used by filters to modify requests and responses



      HttpServletRequestWrapper

      HttpServletResponseWrapper

      Example: performing server-side XSLT
      transformation for older browsers
           f         f

An Introduction to XML and Web Technologies              34
Example: XSLTFilter (1/5)
import     java.io.*;
import     java.util.*;
import     javax.servlet.*;
import     javax.servlet.http. ;
           javax.servlet.http.*;
import     org.jdom.*;
import     org.jdom.transform.*;
import
i          org.jdom.input.*;
               jd   i     *
import     org.jdom.output.*;

public class XSLTFilter implements Filter {
  ServletContext context;

   public void init(FilterConfig c) throws ServletException {
     context = c.getServletContext();
   }

   public void destroy() {}

An Introduction to XML and Web Technologies                     35
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 =
    b l      li        bl
      checkXSLTSupport(hreq.getHeader("User-Agent"));
    ServletResponse res;
              p        ;
    if (client_capable)
      res = response;
    else
      res = new BufferingResponseWrapper(hresp);
    chain.doFilter(request, res);




An Introduction to XML and Web Technologies                      36
Example: XSLTFilter (3/5)
       if (!client_capable) {
        try {
          hresp.setContentType("application/xhtml+xml");
          transform(((BufferingResponseWrapper)res).getReader(),
                    response.getWriter());
        } 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;
    return
      user_agent.indexOf("MSIE 5.5")!=-1 ||
      user_agent.indexOf("MSIE 6")!=-1 ||
      user_agent.indexOf("Gecko")!=-1;
  }

An Introduction to XML and Web Technologies                        37
Example: XSLTFilter (4/5)
    void transform(Reader in, Writer out)
        throws JDOMException, IOException {
      System.setProperty("javax.xml.transform.TransformerFactory",
                          net.sf.saxon.TransformerFactoryImpl );
                         "net.sf.saxon.TransformerFactoryImpl");
      SAXBuilder b = new SAXBuilder();
      Document d = b.build(in);
      List pi = d.getContent(new org.jdom.filter.ContentFilter
       i    i   d           (        jd   fil            il
                             (org.jdom.filter.ContentFilter.PI));
      String xsl = ((ProcessingInstruction)(pi.get(0)))
           g                  g             p g
                   .getPseudoAttributeValue("href");
      XSLTransformer t = new XSLTransformer(xsl);
      Document h = t.transform(d);
                   t transform(d);
      (new XMLOutputter()).output(h, out);
    }
}




An Introduction to XML and Web Technologies                          38
Example: XSLTFilter (5/5)
class BufferingResponseWrapper extends HttpServletResponseWrapper {
  CharArrayWriter buffer;
  PrintWriter writer;

    public BufferingResponseWrapper(HttpServletResponse res) {
      super(res);
      buffer = new CharArrayWriter();
      writer = new PrintWriter(buffer);
    }

    public PrintWriter getWriter() {
      return writer;
    }

    Reader getReader() {
           g        ()
      return new CharArrayReader(buffer.toCharArray());
    }
}

An Introduction to XML and Web Technologies                           39
Request Dispatchers

      Forwarding requests to other resources

      Often used with JSP...




An Introduction to XML and Web Technologies        40
Security – Roles and Authentication

         <web-app ...>
            b
           ...
           <security role>
           <security-role>
              <role-name>administrator</role-name>
              <role-name>teacher</role-name>
              <role-name>student</role-name>
           </security-role>

           <login-config>
             <auth-method>BASIC</auth-method>
             <realm-name>Administration</realm-name>
               g        g
           </login-config>
           ...
         </web-app>


An Introduction to XML and Web Technologies            41
Security Constraints

       ...
       <security-constraint>
         <web-resource-collection>
           <web-resource-name>Restricted Area</web resource name>
           <web resource name>Restricted Area</web-resource-name>
           <url-pattern>/restricted/*</url-pattern>
           <http-method>GET</http-method>
           <http-method>POST</http-method>
         </web-resource-collection>
         <auth constraint>
         <auth-constraint>
           <role-name>administrator</role-name>
           <role-name>teacher</role-name>
         </auth-constraint>
          /   h         i
         <user-data-constraint>
                 p    g                      /     p    g
           <transport-guarantee>CONFIDENTIAL</transport-guarantee>
         </user-data-constraint>
       </security-constraint>
       ...

An Introduction to XML and Web Technologies                          42
Programmatic Security

 Useful request methods:
      getRemoteUser()
      isUserInRole(String role)
      isSecure()
      getAuthType()
      getAttribute(”javax.servlet.request.X509Certificate”)




An Introduction to XML and Web Technologies                   43
Summary

      Servlets closely follow the request response
                                  request-response
      pattern from HTTP

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

An Introduction to XML and Web Technologies                           44
Essential Online Resources

      The servlet API:
      http://jakarta.apache.org/tomcat/tomcat-
      5.5-doc/servletapi/
      5 5 d /     l t i/


      Sun's home page for servlets:
      http://java.sun.com/products/servlet/
      http://java sun com/products/servlet/


      The Tomcat server:
      http://jakarta.apache.org/tomcat/
         p //j        p       g/      /



An Introduction to XML and Web Technologies      45
Limitations of Servlets

      Low-level
      Low level construction of HTML documents
        • fragments (strings) written to output stream
        • no static well-formedness/validity guarantees


      Low-level session management
        • control-flow i often unclear
              t l fl   is ft      l
        • no enforcement of relation between showing a page
          and receiving form input
        • primitive session state management



An Introduction to XML and Web Technologies                   46
JWIG

      Research project (http://www jwig org/)
                       (http://www.jwig.org/)

      Session threads
        • showing a page and receiving form input modeled as a
          Remote Procedure Call (RPC)
              • explicit control-flow
              • simpler session state management
      Template-based page construction using XACT
           p          p g                  g
      Static checking of
        • output validity
        • form field consistency

An Introduction to XML and Web Technologies                      47
Example: The Guessing Game in JWIG




An Introduction to XML and Web Technologies   48
GuessingGameWrapper.xml




             <html>
             <head><title>The Guessing Game</title></head>
             <body bgcolor="aqua"><[BODY]></body>
             </html>




An Introduction to XML and Web Technologies                  49
GuessingGame (1/5)
import    java.io.*;
import    java.util.*;
import    javax.servlet.*;
import    javax.servlet.http. ;
          javax.servlet.http.*;
import    org.jwig.*;
import    dk.brics.xact.*;

public class GuessingGamePlay extends SessionThread {
  p
  public XML main() throws IOException, ServletException {
                                 p    ,            p
    XML wrapper = XML.loadConstant("GuessingGameWrapper.xml");
    XML form = [[
      <form><input name="guess" type "text" size "2" maxlength "2"/>
                   name guess type= text size= 2 maxlength= 2 />
      <input type="submit" name="continue" value="continue"/></form>
    ]];




 An Introduction to XML and Web Technologies                           50
GuessingGame (2/5)

    ServletContext c = getServletContext();
    Integer plays = (Integer)c.getAttribute("plays");
    if (plays null)
       (plays==null)
      plays = new Integer(0);
    else
      plays = new Integer(plays.intValue()+1);
       l                 ( l    i    l () 1)
    c.setAttribute("plays", plays);
    int number = (new Random()).nextInt(100)+1;

    show(wrapper.plug("BODY",
      [[Please guess a number between 1 and 100: <{form}>]]));




An Introduction to XML and Web Technologies                      51
GuessingGame (3/5)

    int guesses = 1;
    boolean done = false;
    while (!done) {
      int guess = Integer.parseInt(getParameter("guess"));
      if (guess==number)
        done = true;
      else {
        show(wrapper.plug("BODY", [[
                pp   p g
          That is not correct. Try a
          <b><{(guess>number)?"lower":"higher"}></b> number: <{form}>
        ]]));
        guesses++;
      }
    }




An Introduction to XML and Web Technologies                         52
GuessingGame (4/5)
    XML msg = [[You got it, using <b><{guesses}></b> guesses.]];
    XML thanks = [[Thank you for playing this exciting game!]];
    XML res;
    if (guesses<getCurrentRecord()) {
      show(wrapper.plug("BODY", [[
           (   pp   p g(       ,
        <{msg}><p/>
        That makes you the new record holder!<p/>
        Please enter your name for the hi-score list:
        <form><input name="name" type="text" size="20"/>
        <input type="submit" name="continue" value="continue"/></form>
      ]]));
      synchronized(c) {
        if (guesses<getCurrentRecord()) {
           c.setAttribute("holder", getParameter("name"));
           c.setAttribute("record",
           c setAttribute("record" new Integer(guesses));
        }
      }
      res = wrapper.plug( BODY , thanks);
             wrapper plug("BODY"
    } else
      res = wrapper.plug("BODY", [[<{msg}><p/><{thanks}>]]);
    return res;;
}
An Introduction to XML and Web Technologies                              53
GuessingGame (5/5)
     int getCurrentRecord() {
       Integer record = (Integer)c.getAttribute("record");
       if (record!=null)
         return record.intValue();
       else
         return Integer.MAX_VALUE; // no players yet
     }
}




    An Introduction to XML and Web Technologies              54
GuessingGameHiScore
    public class GuessingGameHiscore extends HttpServlet {
      public void doGet() throws IOException, ServletException {
        ServletContext c = getServletContext();
        Integer plays = (Integer)c.getAttribute( plays );
                        (Integer)c.getAttribute("plays");
        String holder = (String)c.getAttribute("holder");
        Integer record = (Integer)c.getAttribute("record");
        XML b d
            body;
        if (record!=null)
          body = [[In <{plays.toString()}> plays of this game,
             y          p y          g     p y           g   ,
                   the record holder is <b><{holder}></b> with
                   <b><{record.toString()}></b> guesses.]];
        else
          body = [[No players yet.]];
        XML.loadConstant("GuessingGameWrapper.xml")
          .plug("BODY", body).write(response.getWriter());
      }
    }

An Introduction to XML and Web Technologies                        55
Static Analysis of JWIG Programs



                                                                         plug analysis



class       flow graph
            fl       h              flow       summary graph   summary
files       constructor            graph          analysis      graphs   receive analysis



                                   string          regular
                                  analysis       languages               show analysis




 An Introduction to XML and Web Technologies                                             56
Catching Errors at Compile Time

    ...
    XML ask = [[ <form>Your name? <input name="NAME"/>
                 <input type="submit"/></form> ]];
    ...
                    *** Field ’NAME’ is never available on line 15
                    *** Invalid XHTML at line 14
                    --- element ’input’: requirement not satisfied:
                    <or>
                      <attribute name= type >
                                 name="type">
                        <union>
                          <string value="submit" />
                          <string value="reset" />
                                  value reset
                        </union>
                      </attribute>
                      <attribute name="name" />
                           ib         "    " /
                    </or>



An Introduction to XML and Web Technologies                           57

Contenu connexe

Tendances

LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersChristopher Batey
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Sven Efftinge
 
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)Christopher Batey
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?gedoplan
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersBen van Mol
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationMicha Kops
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
Testing RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkTesting RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkMicha Kops
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald PehlGWTcon
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Christopher Batey
 

Tendances (20)

LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java Developers
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
Cassandra Summit EU 2014 Lightning talk - Paging (no animation)
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Testing RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkTesting RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured framework
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?
 

Similaire à servlets

Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web developmentJohannes Brodwall
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
 
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
 
005428058.pdf
005428058.pdf005428058.pdf
005428058.pdfEidTahir
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3mihirio
 
Pracitcal AJAX
Pracitcal AJAXPracitcal AJAX
Pracitcal AJAXjherr
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authenticationWindowsPhoneRocks
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applicationsdominion
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web PerformanceAdam Lu
 

Similaire à servlets (20)

Servlets intro
Servlets introServlets intro
Servlets intro
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
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
 
Ajax
AjaxAjax
Ajax
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
005428058.pdf
005428058.pdf005428058.pdf
005428058.pdf
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Servlets
ServletsServlets
Servlets
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Pracitcal AJAX
Pracitcal AJAXPracitcal AJAX
Pracitcal AJAX
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
 
Ajax
AjaxAjax
Ajax
 

Plus de Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 

Dernier

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

servlets

  • 1. An Introduction to XML and Web Technologies Programming Web Applications with Servlets ith S l t Anders Møller & Michael I. Schwartzbach © 2006 Addison Wesley Addison-Wesley
  • 2. Objectives How to program Web applications using servlets Advanced concepts such as listeners filters and concepts, listeners, filters, request dispatchers Running servlets using the Tomcat server An Introduction to XML and Web Technologies 2
  • 3. Web Applications Web servers • return files • run programs Web application: collection of servlets, JSP pages, HTML pages, GIF files, ... Servlets: programmed using the servlet API API, which is directly based on HTTP Lifecycles • application (shared state) • session (session state) • i t interaction ti (transient state) (t i t t t ) An Introduction to XML and Web Technologies 3
  • 4. An Example Servlet import java.io.*; p j ; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) l ) throws IOException, ServletException { p yp ; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>ServletExample</title></head>"+ "<body><h1>Hello World!</h1> + <body><h1>Hello World!</h1>"+ "This page was last updated: "+ new java.util.Date()+ "</body></html>"); } } An Introduction to XML and Web Technologies 4
  • 5. Requests Methods in HttpServletRequest • getHeader • getParameter • getInputStream • getRemoteHost, getRemoteAddr, getRemotePort tR t H t tR t Add tR t P t • ... An Introduction to XML and Web Technologies 5
  • 6. Example: HttpServletRequest (1/2) public class Requests extends HttpServlet { public oid doGet(HttpSer letReq est req est p blic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Requests</title></head><body>"); out.println("<h1>Hello, visitor from "+request.getRemoteHost()+"</h1>"); String useragent = request.getHeader("User-Agent"); if (useragent!=null) (useragent! null) out.println("You seem to be using "+useragent+"<p>"); String name = request.getParameter("name"); if (name null) (name==null) out.println("No <tt>name</tt> field was given!"); else out.println("The value of the <tt>name</tt> fi ld is: <tt>" + i l (" h l f h / field i " htmlEscape(name) + "</tt>"); out.println("</body></html>"); } An Introduction to XML and Web Technologies 6
  • 7. Example: HttpServletRequest (2/2) public void doPost(HttpServletRequest request, HttpServletResponse HttpSer letResponse response) throws IOException, ServletException { doGet(request, response); } private String htmlEscape(String s) { StringBuffer b = new StringBuffer(); for (int i = 0; i<s.length(); i++) { char c = s.charAt(i); switch (c) { it h ( ) case '<': b.append("&lt;"); break; case '>': b.append("&gt;"); break; case '"': b.append("&quot;"); break; case ''': b.append("&apos;"); break; case '&': b.append("&amp;"); break; default: b.append(c); } } return b.toString(); } } An Introduction to XML and Web Technologies 7
  • 8. Responses Methods in HttpServletResponse • setStatus • addHeader, addHeader setHeader • getOutputStream, getWriter • setContentType tC t tT • sendError, sendRedirect • ... An Introduction to XML and Web Technologies 8
  • 9. Example: BusinessCardServlet public class BusinessCardServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { p yp ; response.setContentType("text/xml;charset=UTF-8"); ; long expires = new Date().getTime() + 1000*60*60*24; response.addDateHeader("Expires", expires); XMLOutputter outputter = new XMLOutputter(); outputter.output(getBusinessCard(), response.getOutputStream()); response getOutputStream()); } ... using JDOM to generate an XML } document with a reference to an XSLT stylesheet An Introduction to XML and Web Technologies 9
  • 10. Servlet Contexts One ServletContext object for each Web application getServerInfo getInitParameter ... Shared state: • setAttribute(“name”, value) • getAttribute(“name”) getAttribute( ) • don’t use for mission critical data! don t An Introduction to XML and Web Technologies 10
  • 11. Example: A Polling Service A Web application consisting of QuickPollQuestion.html QuickPollSetup.java Q i kP llS t j QuickPollAsk.java QuickPollVote.java Q QuickPollResults.java j An Introduction to XML and Web Technologies 11
  • 12. Example: Example: QuickPollQuestion.html <html> <head><title>QuickPoll</title></head> <body> <h1>QuickPoll</h1> <form method=post action=setup> p p What is your question?<br> <input name=question type=text size=40>?<br> <input type=submit name=submit value="Register my question"> </form> </body> </html> An Introduction to XML and Web Technologies 12
  • 13. Example: Example: QuickPollSetup.java p public class Q QuickPollSetup extends HttpServlet { p p public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { IOException String q = request.getParameter("question"); ServletContext c = getServletContext(); c.setAttribute("question", q); c.setAttribute("yes", new Integer(0)); c.setAttribute( no c setAttribute("no", new Integer(0)); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<html><head><title>QuickPoll</title></head><body>"+ i (" h l h d i l i k ll / i l /h d b d " "<h1>QuickPoll</h1>"+ "Your question has been registered. "+ q g "Let the vote begin!"+ "</body></html>"); } } An Introduction to XML and Web Technologies 13
  • 14. Example: QuickPollAsk.java public class QuickPollAsk extends HttpServlet { public void d bli id doGet(HttpServletRequest request, ( l HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print( <html><head><title>QuickPoll</title></head><body> + out print("<html><head><title>QuickPoll</title></head><body>"+ "<h1>QuickPoll</h1>"+ "<form method=post action=vote>"); String question = (String)getServletContext().getAttribute("question"); out.print(question+ ?<p> ); out.print(question+"?<p>"); out.print("<input name=vote type=radio value=yes> yes<br>"+ "<input name=vote type=radio value=no> no<p>"+ "<input type=submit name=submit value=Vote>"+ " i b i b i l " "</form>"+ "</body></html>"); } } An Introduction to XML and Web Technologies 14
  • 15. Example: QuickPollVote.java (1/2) p public class QuickPollVote extends HttpServlet { Q p public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String vote = request.getParameter("vote"); ServletContext c = getServletContext(); if (vote.equals("yes")) { int yes = ((Integer)c.getAttribute("yes")).intValue(); yes++; c.setAttribute("yes", new Integer(yes)); } else if (vote.equals( no )) { (vote equals("no")) int no = ((Integer)c.getAttribute("no")).intValue(); no++; c.setAttribute("no", new Integer(no)); } An Introduction to XML and Web Technologies 15
  • 16. Example: QuickPollVote.java (2/2) response.setContentType("text/html"); p yp ( / ); PrintWriter out = response.getWriter(); out.print("<html><head><title>QuickPoll</title></head><body>"+ "<h1>QuickPoll</h1>"+ "Thank you for your vote!"+ "</body></html>"); </body></html> ); } } An Introduction to XML and Web Technologies 16
  • 17. Example: QuickPollResult.java (1/2) p public class QuickPollResults extends HttpServlet { Q p public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletContext c = getServletContext(); String question = (String)c.getAttribute("question"); (String)c.getAttribute( question ); int yes = ((Integer)c.getAttribute("yes")).intValue(); int no = ((Integer)c.getAttribute("no")).intValue(); int total = yes+no; response.setContentType("text/html"); response.setDateHeader( Expires response setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.setHeader("Pragma", "no-cache"); PrintWriter out = response.getWriter(); An Introduction to XML and Web Technologies 17
  • 18. Example: QuickPollResult.java (2/2) out.print("<html><head><title>QuickPoll</title></head><body>"+ p ( Q / / y "<h1>QuickPoll</h1>"); if (total==0) out.print("No votes yet..."); else { out.print(question + "?<p>"+"<table border 0> + ?<p> + <table border=0>"+ "<tr><td>Yes:<td>"+drawBar(300*yes/total)+"<td>"+yes+ "<tr><td>No:<td>"+drawBar(300*no/total)+"<td>"+no+ "</table>"); } out.print( </body></html> ); out print("</body></html>"); } String drawBar(int length) { return "<table><tr><td bgcolor=black height=20 width="+ length+"></table>"; } } An Introduction to XML and Web Technologies 18
  • 19. Problems in QuickPoll Need access control to QuickPollSetup No escaping of special characters Need to check right order of execution Need to check that expected form field data is present No synchronization in QuickPollVote Should store state in database Redundancy in HTML generation An Introduction to XML and Web Technologies 19
  • 20. Example: Shopping Cart An Introduction to XML and Web Technologies 20
  • 21. Sessions One HttpSession object for each session • obtained by getSession in the HttpServletRequest object Htt S l tR t bj t Session state: • setAttribute(”name”, value) setAttribute( • getAttribute(”name”) Hides the technical details of tracking users with URL rewriting / cookies / SSL sessions An Introduction to XML and Web Technologies 21
  • 22. Web Applications A Web app is structured as a directory: myapp/ – contains HTML/CSS/GIF/... files myapp/WEB-INF/ /WEB INF/ – contains the deployment descriptor web.xml myapp/ /WEB-INF/classes/ / l / – contains servlet class files (in subdirs corresponding to package names) myapp/WEB-INF/lib/ /WEB INF/lib/ – contains extra jar files An Introduction to XML and Web Technologies 22
  • 23. Deployment Descriptors An XML file web xml describing web.xml mapping from URIs to application resources initialization parameters security constraints registration of listeners and filters An Introduction to XML and Web Technologies 23
  • 24. Example web.xml <web app xmlns="http://java.sun.com/xml/ns/j2ee” <web-app xmlns http://java.sun.com/xml/ns/j2ee version="2.4"> <display-name>A Small Web Application</display-name> di l A S ll W b A li ti /di l <servlet> <servlet-name>MyFirstServlet</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet mapping> <servlet-mapping> <servlet-name>MyFirstServlet</servlet-name> p / / / p <url-pattern>/hello/*</url-pattern> </servlet-mapping> </web-app> / b An Introduction to XML and Web Technologies 24
  • 25. The Tomcat Server Reference Implementation, Open Source Implementation common/lib/servlet-api.jar bin/startup.sh, bin/shutdown.sh conf/server.xml webapps/myapp An Introduction to XML and Web Technologies 25
  • 26. Advanced Features Listeners Filters and wrappers Request dispatchers R t di t h Security An Introduction to XML and Web Technologies 26
  • 27. 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 An Introduction to XML and Web Technologies 27
  • 28. Example: SessionMonitor (1/2) import javax.servlet.*; import javax.servlet.http.*; public class SessionMonitor implements HttpSessionListener, ServletContextListener { private int active = 0, max = 0; public void contextInitialized(ServletContextEvent sce) { store(sce.getServletContext()); } public void contextDestroyed(ServletContextEvent sce) {} public void sessionCreated(HttpSessionEvent se) { active++; if (active>max) max = active; store(se.getSession().getServletContext()); } An Introduction to XML and Web Technologies 28
  • 29. Example: SessionMonitor (2/2) public void sessionDestroyed(HttpSessionEvent se) { active--; store(se.getSession().getServletContext()); } private void store(ServletContext c) { c.setAttribute( sessions_active c setAttribute("sessions active", new Integer(active)); c.setAttribute("sessions_max", new Integer(max)); } } Registration in web.xml: <listener> <listener-class>SessionMonitor</listener-class> <listener> An Introduction to XML and Web Technologies 29
  • 30. Filters Code being executed before and after the servlet • executed in stack-like fashion with servlet at the bottom Can intercept and redirect processing • security • auditing Can C modify requests and responses dif t d • data conversion (XSLT, gzip, ...) • specialized caching – all without changing the existing servlet code! An Introduction to XML and Web Technologies 30
  • 31. Example: LoggingFilter (1/2) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoggingFilter implements Filter { ServletContext context; int counter; p public void init(FilterConfig c) throws ServletException { g p context = c.getServletContext(); } public void destroy() {} An Introduction to XML and Web Technologies 31
  • 32. Example: LoggingFilter (2/2) public void doFilter(ServletRequest request, ServletResponse response, l FilterChain chain) throws IOException, ServletException { String uri = ((HttpServletRequest)request).getRequestURI(); int n = ++counter; context.log( starting context log("starting processing request # +n+ ("+uri+")"); #"+n+" ( +uri+ ) ); long t1 = System.currentTimeMillis(); chain.doFilter(request, response); long t2 = System.currentTimeMillis(); context.log("done processing request #"+n+", "+(t2-t1)+" ms"); } } An Introduction to XML and Web Technologies 32
  • 33. Registration of Filters in web.xml <web-app ...> b ... <filter> <filter-name>My Logging Filter</filter-name> <filter-class>LoggingFilter</filter-class> </filter> <filter-mapping> fil i <filter-name>My Logging Filter</filter-name> <url-pattern>/ </url-pattern> <url-pattern>/*</url-pattern> </filter-mapping> ... </web-app> An Introduction to XML and Web Technologies 33
  • 34. Wrappers Used by filters to modify requests and responses HttpServletRequestWrapper HttpServletResponseWrapper Example: performing server-side XSLT transformation for older browsers f f An Introduction to XML and Web Technologies 34
  • 35. Example: XSLTFilter (1/5) import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http. ; javax.servlet.http.*; import org.jdom.*; import org.jdom.transform.*; import i org.jdom.input.*; jd i * import org.jdom.output.*; public class XSLTFilter implements Filter { ServletContext context; public void init(FilterConfig c) throws ServletException { context = c.getServletContext(); } public void destroy() {} An Introduction to XML and Web Technologies 35
  • 36. 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 = b l li bl checkXSLTSupport(hreq.getHeader("User-Agent")); ServletResponse res; p ; if (client_capable) res = response; else res = new BufferingResponseWrapper(hresp); chain.doFilter(request, res); An Introduction to XML and Web Technologies 36
  • 37. Example: XSLTFilter (3/5) if (!client_capable) { try { hresp.setContentType("application/xhtml+xml"); transform(((BufferingResponseWrapper)res).getReader(), response.getWriter()); } 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; return user_agent.indexOf("MSIE 5.5")!=-1 || user_agent.indexOf("MSIE 6")!=-1 || user_agent.indexOf("Gecko")!=-1; } An Introduction to XML and Web Technologies 37
  • 38. Example: XSLTFilter (4/5) void transform(Reader in, Writer out) throws JDOMException, IOException { System.setProperty("javax.xml.transform.TransformerFactory", net.sf.saxon.TransformerFactoryImpl ); "net.sf.saxon.TransformerFactoryImpl"); SAXBuilder b = new SAXBuilder(); Document d = b.build(in); List pi = d.getContent(new org.jdom.filter.ContentFilter i i d ( jd fil il (org.jdom.filter.ContentFilter.PI)); String xsl = ((ProcessingInstruction)(pi.get(0))) g g p g .getPseudoAttributeValue("href"); XSLTransformer t = new XSLTransformer(xsl); Document h = t.transform(d); t transform(d); (new XMLOutputter()).output(h, out); } } An Introduction to XML and Web Technologies 38
  • 39. Example: XSLTFilter (5/5) class BufferingResponseWrapper extends HttpServletResponseWrapper { CharArrayWriter buffer; PrintWriter writer; public BufferingResponseWrapper(HttpServletResponse res) { super(res); buffer = new CharArrayWriter(); writer = new PrintWriter(buffer); } public PrintWriter getWriter() { return writer; } Reader getReader() { g () return new CharArrayReader(buffer.toCharArray()); } } An Introduction to XML and Web Technologies 39
  • 40. Request Dispatchers Forwarding requests to other resources Often used with JSP... An Introduction to XML and Web Technologies 40
  • 41. Security – Roles and Authentication <web-app ...> b ... <security role> <security-role> <role-name>administrator</role-name> <role-name>teacher</role-name> <role-name>student</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> <realm-name>Administration</realm-name> g g </login-config> ... </web-app> An Introduction to XML and Web Technologies 41
  • 42. Security Constraints ... <security-constraint> <web-resource-collection> <web-resource-name>Restricted Area</web resource name> <web resource name>Restricted Area</web-resource-name> <url-pattern>/restricted/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth constraint> <auth-constraint> <role-name>administrator</role-name> <role-name>teacher</role-name> </auth-constraint> / h i <user-data-constraint> p g / p g <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> ... An Introduction to XML and Web Technologies 42
  • 43. Programmatic Security Useful request methods: getRemoteUser() isUserInRole(String role) isSecure() getAuthType() getAttribute(”javax.servlet.request.X509Certificate”) An Introduction to XML and Web Technologies 43
  • 44. Summary Servlets closely follow the request response request-response pattern from HTTP Features: • Multi-threading • Declarative configuration • Request parsing, including decoding of form data • Shared state • Session management • Advanced code structuring: listeners, filters, wrappers • Client authentication, SSL An Introduction to XML and Web Technologies 44
  • 45. Essential Online Resources The servlet API: http://jakarta.apache.org/tomcat/tomcat- 5.5-doc/servletapi/ 5 5 d / l t i/ Sun's home page for servlets: http://java.sun.com/products/servlet/ http://java sun com/products/servlet/ The Tomcat server: http://jakarta.apache.org/tomcat/ p //j p g/ / An Introduction to XML and Web Technologies 45
  • 46. Limitations of Servlets Low-level Low level construction of HTML documents • fragments (strings) written to output stream • no static well-formedness/validity guarantees Low-level session management • control-flow i often unclear t l fl is ft l • no enforcement of relation between showing a page and receiving form input • primitive session state management An Introduction to XML and Web Technologies 46
  • 47. JWIG Research project (http://www jwig org/) (http://www.jwig.org/) Session threads • showing a page and receiving form input modeled as a Remote Procedure Call (RPC) • explicit control-flow • simpler session state management Template-based page construction using XACT p p g g Static checking of • output validity • form field consistency An Introduction to XML and Web Technologies 47
  • 48. Example: The Guessing Game in JWIG An Introduction to XML and Web Technologies 48
  • 49. GuessingGameWrapper.xml <html> <head><title>The Guessing Game</title></head> <body bgcolor="aqua"><[BODY]></body> </html> An Introduction to XML and Web Technologies 49
  • 50. GuessingGame (1/5) import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http. ; javax.servlet.http.*; import org.jwig.*; import dk.brics.xact.*; public class GuessingGamePlay extends SessionThread { p public XML main() throws IOException, ServletException { p , p XML wrapper = XML.loadConstant("GuessingGameWrapper.xml"); XML form = [[ <form><input name="guess" type "text" size "2" maxlength "2"/> name guess type= text size= 2 maxlength= 2 /> <input type="submit" name="continue" value="continue"/></form> ]]; An Introduction to XML and Web Technologies 50
  • 51. GuessingGame (2/5) ServletContext c = getServletContext(); Integer plays = (Integer)c.getAttribute("plays"); if (plays null) (plays==null) plays = new Integer(0); else plays = new Integer(plays.intValue()+1); l ( l i l () 1) c.setAttribute("plays", plays); int number = (new Random()).nextInt(100)+1; show(wrapper.plug("BODY", [[Please guess a number between 1 and 100: <{form}>]])); An Introduction to XML and Web Technologies 51
  • 52. GuessingGame (3/5) int guesses = 1; boolean done = false; while (!done) { int guess = Integer.parseInt(getParameter("guess")); if (guess==number) done = true; else { show(wrapper.plug("BODY", [[ pp p g That is not correct. Try a <b><{(guess>number)?"lower":"higher"}></b> number: <{form}> ]])); guesses++; } } An Introduction to XML and Web Technologies 52
  • 53. GuessingGame (4/5) XML msg = [[You got it, using <b><{guesses}></b> guesses.]]; XML thanks = [[Thank you for playing this exciting game!]]; XML res; if (guesses<getCurrentRecord()) { show(wrapper.plug("BODY", [[ ( pp p g( , <{msg}><p/> That makes you the new record holder!<p/> Please enter your name for the hi-score list: <form><input name="name" type="text" size="20"/> <input type="submit" name="continue" value="continue"/></form> ]])); synchronized(c) { if (guesses<getCurrentRecord()) { c.setAttribute("holder", getParameter("name")); c.setAttribute("record", c setAttribute("record" new Integer(guesses)); } } res = wrapper.plug( BODY , thanks); wrapper plug("BODY" } else res = wrapper.plug("BODY", [[<{msg}><p/><{thanks}>]]); return res;; } An Introduction to XML and Web Technologies 53
  • 54. GuessingGame (5/5) int getCurrentRecord() { Integer record = (Integer)c.getAttribute("record"); if (record!=null) return record.intValue(); else return Integer.MAX_VALUE; // no players yet } } An Introduction to XML and Web Technologies 54
  • 55. GuessingGameHiScore public class GuessingGameHiscore extends HttpServlet { public void doGet() throws IOException, ServletException { ServletContext c = getServletContext(); Integer plays = (Integer)c.getAttribute( plays ); (Integer)c.getAttribute("plays"); String holder = (String)c.getAttribute("holder"); Integer record = (Integer)c.getAttribute("record"); XML b d body; if (record!=null) body = [[In <{plays.toString()}> plays of this game, y p y g p y g , the record holder is <b><{holder}></b> with <b><{record.toString()}></b> guesses.]]; else body = [[No players yet.]]; XML.loadConstant("GuessingGameWrapper.xml") .plug("BODY", body).write(response.getWriter()); } } An Introduction to XML and Web Technologies 55
  • 56. Static Analysis of JWIG Programs plug analysis class flow graph fl h flow summary graph summary files constructor graph analysis graphs receive analysis string regular analysis languages show analysis An Introduction to XML and Web Technologies 56
  • 57. Catching Errors at Compile Time ... XML ask = [[ <form>Your name? <input name="NAME"/> <input type="submit"/></form> ]]; ... *** Field ’NAME’ is never available on line 15 *** Invalid XHTML at line 14 --- element ’input’: requirement not satisfied: <or> <attribute name= type > name="type"> <union> <string value="submit" /> <string value="reset" /> value reset </union> </attribute> <attribute name="name" /> ib " " / </or> An Introduction to XML and Web Technologies 57