J2EE Bootcamp by ewghwehws

VIEWS: 15 PAGES: 126

									J2EE Bootcamp

     Part I – J2EE basics
    Bootcamp Part I
   Day 1
       Review HTML
       Review HTTP
       Servlets
   Day 2
       JSP’s
       Tag libraries
       Using Java Beans with JSP
   Day 3
       JDBC
       JNDI
       XML
HTML Review
   Structure of HTML page
       Header
       Body
   Tags
       Lists
       Tables
   Forms
       Button, input, select, etc.
HTML Sample
    <html>
      <head>
        <title>User Info Entry Form</title>
      </head>
      <body bgcolor="white">
        <form action="userinfo1.jsp" method="post">
           <table>
             <tr>
               <td>Name:</td>
               <td><input type="text" name="userName" >
               </td>
             </tr>
             <tr>
               <td>Birth Date:</td>
               <td><input type="text" name="birthDate" >
               </td>
               <td>(Use format yyyy-mm-dd)</td>
             </tr>
             <tr>
               <td colspan=2><input type="submit"></td>
             </tr>
           </table>
        </form>
      </body>
    </html>
HTTP Protocol
   Stateless protocol
   Request/Response
   Common Methods:
       Get – repeatable retrieval of the resource
       Post – send parameters to resource for
        action
       Put – send data to the resource for saving
       Delete – request that resource is deleted
Servlet
   Core building block of Java web
    applications
   Servlets software components that run
    on the server side.
   Run in a servlet container which
    manages the servlet lifecyle.
   Similar to CGI but more efficient and
    powerful.
Lab 1 – Build a simple Servlet
   Build a simple servlet using the Jbuilder
    Wizard.
   Make sure you handle both the GET and
    POST operations
   Modify the GET operation to print the
    current time.
       Life cycle (Diagram)
 Does not exist          Instantiation based on a                           Instantiated
                      Request or at container startup




                                                                         Initialized and/or
                  Unavailable                     Initiation failed
                                                                         Ready for requests

 Release                                Back to service if temporarily
Reference                                        unavailable                               End of Service
                                                                                              thread
                                                                            HTTP request
                                                                             from client


                                 Temporary or permanent
   Destroyed                            failure                               Service
                      Time-out or container shutdown
Life Cycle
   Several points to control behavior of servlet
       Constructor for when the servlet is first
        instantiated
       Initialization is guaranteed before service is called
       Service
       Destroy
   ServletException thrown if a problem is
    detected during the normal lifecycle
   UnavailableException is thrown when ever the
    servlet cannot fulfill the request (maybe only
    temporary)
            Servlet API Overview
             interface                                           interface               interface
              Servlet                                          ServletConfig        SingleThreadModel


                                       java.io.Serializable
                                         GenericServlet
                                                                 interface              Exception
                                                              ServletContext         ServiceException

    interface                 interface
ServletResponse            ServletRequest




   OutputStream             OutputStream                          interface
                                                                                  UnavailableException
ServletOutputStream      ServletOutputStream                  RequestDispatcher
            jaxax.servlet.http
       interface         interface         java.io.Serializable          EventListener
   ServletResponse    ServletRequest         GenericServlet                 interface
                                                                   HttpSessionBindingListener




     interface             interface        java.io.Serializable
HTTPServletResponse   HttpServletRequest        HttpServlet




    cloneable             interface                                      HttpUtils
     Cookie              HttpSession
Servlet Interface
   Init()
       Guaranteed to be called before service
       Used to initialize instance of servlet
   Service()
       Entry point of servlet
       Use the request to determine what to do in the
        service
   Destroy()
       Chance to clean up resourses or write info to logs
HTTP Servlet Interface
   Extension of servlet interface for HTTP
    protocol
   HttpServlet Class – default implementation
       Service()
            Dispatches to the doXXXX functions based on method
             type
       doXXXX()
            Don’t override doTrace or doOptions; implemented by
             HttpServlet class
       getLastModified()
            returns the time the servlet was modified
            Provides hooks for server-side caching
ServletConfig
   getInitParameter()
   getINitParameterNames()
   getServletContext()
       Object that is available to all servlets in the
        webapp
   getServletName()
   getServletConfig()
Servlet Exceptions
   ServletException
       Throw whenever there is an error
        preventing proper execution
   UnavailableException
       Throw when a resource is not available
       This may be temporary
Lab 2 (FreakServlet)
   Run the FreakServlet
   Add a method to report all the states
    just before the instance goes away.
HttpRequest interface
   Extends ServletRequest
       Methods for parameters, attributes, input
   Additional methods specific to HTTP protocol
       getAuthType()
       getCookie()
       getHeader()
       getPathInfo()
       getSession()
HttpResponse interface
   Extends ServletResponse Interface
       Methods for contentType, output objects, locale
   Additional methods specific to HTTP protocol
       addCookie()
       encodeURL()
       sendError()
       setRedirect()
Lab 3 – Working with Request
and Response
   Write servlet that outputs:
       All parameter names and values
       All attribute names and values
       Any cookies available
       All headers
       The method
       The query string
       The PathInfo
       The servlet path
Deployment Descriptor
   Web.xml file contains information to tell the
    web container how to use the servlet
   Servlet-name
   Servlet-classs
   Init-param
   Servlet-mapping
       Servlet-name
       url-pattern
Sessions
   HTTP is stateless protocol so some
    method of tracking sessions is needed
   Different forms for exchanging token
       URL Rewriting
       Hidden Form Fields
       Cookies
   Servlet API leaves the details to the
    web container
URL Rewrite
   All pages must be dynamically generated for
    this to work
   URL http://localhost/foo becomes
    http://localhost/foo;jsessionid=939456279
   If this is needed the servlet programmer must
    provide some additional support via
    response.encodeURL method
Hidden form fields
   Inbeds a hidden field in a form
    containing the sessionid
   Again requires dynamic creation
   Also requires each page to have a form
    and may not be appropriate in all apps
Cookies
   Textual information sent by the server
    to the client
   Client returns these cookies for the
    proper domain on subsequent HTTP
    calls
   Client can refuse cookies
   Advantage is that this separate from
    the HTML content
HttpSession interface
   Methods for managing session lifecycle
       Invalidate() used to get rid session
        explicitly
   Methods for managing state
       getAttribute()/setAttribute() most
        commonly used
Binding objects to session
   Objects bound to a session can implement
    HttpSessionBindingListener interface to be
    notified when they are bound or unbound to
    a session
   valueBound() and valueUnbound() are the
    two methods
   Uses the HttpSessionBindingEvent class
       getName()
       getSession()
Lab 4 – Session maintenance
   Create a servlet to report:
       sessionId
       Session create time and last access time
       Max inactive interval
       Whether the session is new or not
   If the parameter “action” has a value of
    “invalidate”, invalidate the session
   Set the default timeout for the session to be
    1 minutes
Servlet Context Interface
   Object that references resources common to
    all servlets in the webapp.
       getMimeType
       getResource
       getContext to get other applications context
       Log
       getInitParameters
       Get, set, remove attributes
Servlet Collaboration
   Chaining – old feature in some original
    implementations but not part of the
    standard API
   Filtering – new feature in Servlet 2.3
    spec
   Dispatching – pass control to another
    servlet
   Sharing information via ServletContext
Dispatcher
   Get through the ServletContext for absolute
    paths
   Or use relative paths through ServletRequest
   Forward() gives control to the target servlet
    and the current servlet never gets control
    again
   Include() calls the resource and includes the
    content of the resource into the current
    response
   One can manipulate the request or response
    object before calling forward or include
Lab 5 – Server Collaboration
   Create controller servlet that will uses the
    parameter “action” to determine whether to
    store or retrieve parameters
   If the action is store, convert all the
    parameters of the request to attributes with
    the exception of the action parameter
   If the action is retrieve, use include to call the
    retrieve servlet to get the session attributes
    of the corresponding parameter names
   The forward servlet takes the request
    attributes and assigns them to the session
    attributes
Threading Issues
   Instance variables vs method variables
   Synchronization
   SingleThreadModel
Lab 6 – Threading Examples
   Create a servlet with the following capability
      A static counter to represent the instance count

      An instance counter for each time the doGet function called

      If parameter “sleep” has a value greater than zero, sleep
        that long before incrementing the doGet counter
   Open two browser windows
   In one call the servlet to make sure it is working
   In the other call the servlet with a value of 6000
   While the second window is waiting, refresh the second window
    a couple times
   Wrap a synchronization block around the wait and counter
    update; recompile and re-run as above.
   Change the servlet to implement the SingleThreadModel;
    recompile and re-run as above.
Problems with Servlets
   Mix business logic with content
       Changes in presentation issues may
        introduce bugs in the business logic or
        vice-versa
   Must know a fair amount of Java to
    program
   Not very dynamic since they must be
    compiled and deployed
JavaServer Pages (JSP)
Overview
   JSP’s allow separation of business logic
    from presentation by use of java beans
    and custom tags
   Can code JSP’s with little to no Java
    knowledge (though it still helps a great
    deal)
   Very dynamic since they are compiled
    and deployed on the fly
JSP Overview (cont.)
   Sometimes referred to as inside-out
    servlets
   Mostly composed of HTML with
    smatterings of Java
   Can output XML or any markup
    language
JSP Lifecycle
   JSP is a servlet so it follows essentially the
    same lifecycle
   The difference is that a JSP starts as text file
   When first invoked it is translated into a valid
    servlet
   The servlet is compiled and loaded
   At this point it behaves like a regular servlet
    unless the container detects the original text
    file has changed. Then the process is started
    over.
   You can view translated file for edification
Lab 7
   Create a JSP using the Jbuilder wizard
       Don’t create a sample bean yet
   Add a page directive to import the
    java.util.Date class
       <%@page import=“java.util.Date” %>
   Add an expression to print the current date
    and time
       <%= new Date().toString %>
   Right click and Web-run the jsp page
   Open the projectdir/work directory; locate
    and view the translation file for your jsp
JSP Elements –
Script Elements
   Scriptlets
       Actual segments of Java code to be executed
       Enclosed in <% … %>
   Expressions
       Snippets of java that are evaluated in place
       Enclosed in <%= … %>
       Do not end expressions with a ‘;’
   Declarations
       Define class wide variables and methods
       Enclosed in <%! … %>
Scripting Elements –
Declarations
   Used to declare class variables and methods
   Example:
<%!
Int numTimes = 3;

Public String sayHello(String name) {
     Return "Hello, " + name + "!";
}
%>
<html>
   <body>
     <p>The value of numTimes is <%= numTimes %>
     <p>Saying hello to the reader: "<%=sayHello("reader") %>
   </body>
</html>
Scripting Elements –
Scriptlets
   Just valid java statements
<html>
  <body>
    <%
       for(int I=0;I<10;I++) {
       out.println("<b>Hello world. This is scriptlet test " + i + "</b><br>");
       system.out.println("This goes to the System.out stream." + i);
    %>
  </body>
</html>
Scripting Elements –
Expressions
   An expression is a small snippet of code
    that is evaluated and returned as a
    string to the client
<html>
  <body>
    <%! Int I; %>
    <% i++; %>
    Hello World!
    <%= "This JSP has been accessed " + i + " times." %>
  </body>
</html>
JSP Elements –
Directives
   JSP Directives
       Messages sent to the JSP container
       Have global scope
       Do not produce output to the client
        (directly)
JSP Directives
   Have the form of:
    <%@ directive attribute=“value” attribute=“value” … %>

   Can occur anywhere but typically at the
    top of the page
   Three directives
       Page
       Include
       Taglib
Page Directive
   As many as you page directives as you
    want as long as no duplicate
    attribute/value pairs with the exception
    of the import attribute
Page Directive Attributes
   language - defines the scripting language. “Java” is default.
   import - comma seperated list of packages or classes to import
   session - denotes if the page participates in an HTTP session. Default
    is true.
   buffer - specifies buffering model
   autoflush - if true (the default) flush buffer when full
   isThreadSafe - denotes if the JSP is thread safe
   info – short description of page made available to
    Servlet.getServletInfo()
   errorPage – URL to another JSP that catches exceptions
   isErrorPage – indicates the JSP is an error page and implicit variable
    exception is available
   contentType – deines the character encoding and MIME type of the
    JSP
Include Directive
   Format:
       <%@ include file="filename" %>
   Instructs the container to include the
    contents of the resource inline
   Happens at translationg/compile time
   Note - include action is used to include
    content at runtime.
Implicit Objects
   The JSP API specifies that some implicit
    variables should be made available
       request - HttpServletRequest
       response – HttpServletResponse
       pageContext – javax.servlet.jsp.PageContext
       session - HttpSession
       application - ServletContext
       out – buffered version of PrinterWriter
       config - ServletConfig
       page – reference to the current instance, ie. this
Lab 8
   Write a JSP that reports the session
    information like in lab 4
   Write another JSP that would be used as a
    footer that outputs a copyright notice and the
    current time.
   Without shutting down Tomcat, modify the
    first page to include the second page
    Get a meaningful value from
    Servlet.getServletInfo()
Problems with Scriptlets
Using scriptlets still means we are mixing
 code and presentation logic.
With JSP's the presentation logic is pre-
 dominant and the business logic is
 secondary. This the reverse of servlets
Tag libraries and Javabeans to the
 rescue.
Taglib Directive
   Format:
       <%@ taglib uri="taglibraryURI"
        prefix="tagprefix" %>
   Allows the page to use custom tags
   Names the tag library that contains the
    compiled classes
   Maps a prefix to denote which library to
    use – similar to namespaces in XML
JSP Elements –
Standard Tags
   Tag libraries invoke business logic
    components without using Java
   Appear as XML tags imbedded in the
    content
   Set of standard tag libraries available
   All use the tag prefix of jsp
Standard Tags –
useBean
Syntax:
  <jsp:useBean id="name"
  scope="scopeName" beandetails />
 Beandetails one of
     Class="className"
     Class="className" type="typeName"
     beanName="beanName" type="typeName"
     Type="typeName"
Standard Tags –
useBean (cont)
   Id – case sensitive name to identify bean
   Scope – values are "page", "request",
    "session", "application"
   Class – fully qualified bean name
   beanName – standard mechanism for
    instantiate beans
   Type – type of the scripting variables; must
    be superclass, implemented interface by the
    class or the class itself
Standard Tags –
useBean Scope
Scope determines the life of the bean
     Page scope binds the bean to the request for the
      current page only
     Request scope binds the bean to the request
      across many pages
     Session scope binds the bean to the session
     Application scope binds the bean to the
      servletContext
Binding is done by adding it as an attribute to
  the appropriate object with the id as the key
Standard Tags –
setProperty
Syntax:
  <jsp:setProperty name="beanName" propertydetails />
  Propertydetails one of:
       Property="*"
      Property="propertyName"

      Property="propertyName" param="parameterName"

      Proptery="propertyName" value="propertyValue"

  The * matches parameterNames to properties of the bean and
    sets them to the parameter values
  The value can be a request-time attribute or a static
    expression.
Standard Tags –
param
Syntax:
  <jsp:param name="paramname" value="paramvalue" />
     Name – the key to the attribute
     Value – the value of the attribute
Used to provide other tags with additional
 information.
Used mostly forward, include, and plugin
Standard Tags –
include
Performs a dispatcher.include()
Syntax:
  <jsp:include page="URL" flush="true" />
  Or
  <jsp:include page="URL" flush="true">
     <jsp:param name="param" value="paramvalue"
      />
     …
  </jsp:include>
Standard Tags –
forward
Implements the Dispatcher.forward()
Syntax:
  <jsp:forward page="uri" />
  Or
  <jsp:forward page="uri" >
    <jsp:param param="name" value="paramvalue"
     />
    …
  </jsp:forward>
Standard Tags –
plugin
Used to generate browser specific HTML
 to tell the browser to download and run
 an applet.
Using Beans
   Java beans are one way of seperating
    business logic from the presentation
   Can use to get information into and out
    of the JSP without writing Java
   Scriptlets can be used to invoke
    business logic in the bean
   The usebean, setProperty, getProperty
    are the standard tags used with beans
Java Beans
Any class that meets a few requirements can be
  a bean.
     Has a zero-argument constructor
     Some set of attributes are exposed via get/set
      methods
       Eg. Attribute myName is exposed via getMyName and
         setMyName
     When using beans with JSP properties need to be
      strings or the ability to be coerced into strings
Jsp:usebean example
See
  http://mystery.ucs.indiana.edu:8080/ex
  amples
Lab 9
   Build a bean to hold personal info
       Name, email, birtdate, sex, lucky # (1-100)
       Verify that lucky # is in the range
       Add an additional property to store
        validation errors – absence of a value is an
        error
Custom Tags
   Standard tags not the only ones
    available
   Can use third party custom tags such as
    the tag library in struts
Jakarta Tag Libraries
Application Taglib
     The APPLICATION custom tag library contains tags which can be used to access
        information contained in the ServletContext for a web application.
Benchmark Taglib
     The Benchmark taglib provides tags that aide in doing performance testing of JSP pages.
DateTime Taglib
The DateTime custom tag library contains tags which can be used to handle date
   and time related functions. Tags are provided for formatting a Date for output,
   generating a Date from HTML forum input, using time zones, and localization.
DBTags Taglib
     The DBTags (formerly called JDBC) custom tag library contains tags which can be used to
        read from and write to an SQL database.
Page Taglib
     The Page custom tag library contains tags which can be used to access all the information
        about the PageContext for a JSP page.
Regexp Taglib
     The Regexp custom tag library contains tags which can be used to perform Perl syntax
        regular expressions.
Jakarta Tag Libraries (cont.)
Request Taglib
   The Request custom tag library contains tags which can be used to access all
      the information about the HTTP request for a JSP page.
Response Taglib
   The Response custom tag library contains tags which can be used to set all the
      information for an HTTP response for a JSP page.
Session Taglib
   The Session JSP tag library provides tags for reading or modifying client
      HttpSession information.
Deploying Tag Libraries
   Place the tag library tld in the WEB-INF
    directory
   The tag library classes need to go in the
    WEB-INF/classes directory
   Jbuilder will do part of this for you
    when building a war
       A bug prevents the tld's from being copied
        correctly
Lab 10
   Use the DB tag library to query an
    Oracle table
   Load the row into a bean with session
    scope
   Display the bean information in a table
    format from another JSP
JDBC
   JDBC is an vendor independent
    mechanism for communicating with
    databases, primarily RDBMS
   Similar to ODBC
   JDBC assumes SQL
   Provides mappings between SQL
    datatypes and Java types
Database Driver
A database driver is required to connect to a
  database
 4 types of drivers exist
     Type 1: JDBC-ODBC Bridge – provided by Sun and
      good for learning JDBC but little more
     Type 2: Mix Java and Vendor API – efficient for
      middle tier implementation
     Type 3: Intermediate Server – Offers some
      benefits of both Type 2 and Type 4
     Type 4: Pure Java – good for applet and thin
      client use
Database Driver (cont.)
UIS will use Oracle Type 2 and Type 4
  drivers
 Type 2 drivers configured on application

  servers
 Type 4 on development environments
Logging
   Can pass a PrintWriter to the
    DriverManager via setLogWriter()
   Send output to the log with the
    DriverManagers println()
Defining Driver to Program
Register the driver with the DriverManager
(Driver names are vendor specific.)
     Load the driver directly
  Try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
  } catch(ClassNotFoundException e) {
    …
  }

     Load driver through system properties
  System.setProperty("jdbc.drivers",
     "oracle.jdbc.driver.OracleDriver");
  // multiple drivers seperated by ':'
Connections
   Connections are done by supplying a
    URL to the database
   The format of the URL is:
    jdbc:subprotocol:subname
   The subprotocol and subname are
    vendor specific
   Oracle uses:
    oracle:[thin|OCI]:@hostname:port:instance
Getting a connection –
URL only
   Supply a URL and the driver manager
    determines which if any of the
    registered drivers can satisfy the URL
String url = "jdbc:oracle:thin:@mystery:1521:TESTDB";
Connection conn = DriverManager.getConnection(url);
Getting a connection –
URL and properties
This method uses the URL and a
 properties object appropriate for the
 driver.
String url = "jdbc:oracle:thin:@es01:1521:GEN2DEV";
Properties p = new Properties();
p.put("user", "scott");
p.put("password", "tiger");
Connection conn = DriverManager.getConnection(url, p);

Can get list of valid properties via:
DriverPropertyInfo info[] = DriverManger.getDriver(url);
Getting a connection –
URL, username and password
Lastly we can just specify the username
  and password
String url = "jdbc:oracle:oci:@es51:1521:DSS1PRD";
String user = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection(url, user,
   password);



(Note: all the getConnections throw SQLException and
  must be caught.)
Lab 11
   Using a servelt, establish a connection
    to a database
   Query the driver to determine all the
    properties you can set
   Which properties are required?
   Send information to the JDBC log
Statements
   Connections are used to get statements
   Statements – straight SQL to be passed
    to the DBMS for processing
   Prepared Statements – holds
    precompiled SQL to which arguments
    are passed to its parameters
   Callable Statements – used to call
    stored procedures on the DBMS
Getting a statement
   Use conn.createStatement() to get a
    connection
   Use executeQuery() to get a ResultSet that
    can be processed for query results
   Use executeUpdate() to send an insert, delete
    or update to the database; returns the # of
    rows affected
   Use execute() if you are not sure what the
    SQL will do
        ResultSet
   Get a ResultSet from a executeQuery()
   Is a table of rows from the query
   To get the data from the ResultSet use:
getAsciiStream()   getTimestamp()      getTime()     getBigDecimal()
getBoolean()       getBinaryStream()   getString()   getMetaData()
getDate()          getBytes()          getByte()     getClob()
getInt()           getFloat()          getDouble()   getWarnings()
getShort()         getObject()         getLong()     getBlob()

   Specify either the column name or index
   Use the next() method to move to the next row
ResultMetaData
   The getMetaData() method returns a
    ResultMetaData object used to describe
    the data returned
getCatalogName()       getScale()             getPrecision()
getTableName()         getSchemaName()        isNullable()
getColumnCount()       isCurrency()           getColumnName()
isSearchable()         getColumnLabel()       isCaseSensitive()
getColumnType()        getColumnTypeName()    isSigned()
isAutoIncrement()      getColumnClassName() isReadOnly()
getColumnDisplaySize() isDefinitelyWritable()
SQL Types
   Because of variations between RDBMS
    vendors on SQL datatypes, JDBC
    provides a mapping for the most
    common types
   Examples are:
JDBC Type       SQL Type   Java Type
CHAR            CHAR       String
DATE            DATE       java.sql.Date
NUMERIC         NUMERIC    java.math.BigDecimal
INTEGER         INTEGER    int
VARCHAR         VARCHAR    String
SQL Types (cont.)
 Table of SQL type mappings:
http://java.sun.com/j2se/1.3/docs/guide/j
  dbc/getstart/mapping.html#table1
 Additional information at:

http://java.sun.com/j2se/1.3/docs/guide/j
  dbc/getstart/mapping.html#997737
Scrollable and Updatable
ResultSets
   With JDBC 2.1 support added for Scrollable
    and Updatable ResultSets
   Specify with the getStatement the scroll type
    and the concurrency
   Scrollable ResultSets allow back and forth
    processing of the result table
   Updatable ResultSets allow for modifications
    of the data to be stored back to the database
Scrollable ResultSet
Specify three types:
     TYPE_FORWARD_ONLY – default and only
      forward scrolling (ie. next() only)
     TYPE_SCROLL_INSENSITIVE – scroll in
      either direction
     TYPE_SCROLL_SENSITIVE – as above but
      concurrent with changes in the database
Scrollable ResultSet (cont.)
Various methods for scrolling are
 supported
     first()
     last()
     absolute()
     relative()
     previous()
     setFetchSize() and getFetchSize()
Updateable ResultSet
Can one of:
       CONCUR_READ_ONLY – default
       CONCUR_UPDATABLE – allows for inserts, deletes
        and updates
   updateXXX() methods to change the column
    of the current row with the appropriate type
   deleteRow() deletes the current row
   insertRow() inserts a row; call
    moveToInsertRow() first and populate with
    updateXXX() methods
Prepared Statements
   Prepared statements allow the DBMS to
    precompile the SQL
   The statement contains parameters which are
    filled with subsequent execute statements
   Parameters are specified with '?'
   Use the setXXX for the appropriate type
   setXXX() takes the parameter index and the
    object of the specific type
Prepared Statement Example
PreparedStatement ps = conn.prepareStatement("INSERT INTO
   catalogue(title, lead_actor, lead_actress, type,
   release_date) VALUES(?,?,?,?,?)");
try {
  do {
    ps.clearParameters();
    ps.setString(1, item.getProperty("title"));
    ps.setString(2, item.getProperty("actor"));
    ps.setString(3, item.getProperty("actress"));
    ps.setInt(4, item.getProperty("type"));
    ps.setDate(5, item.getProperty("date"));

      ps.executeUpdate();
    } while ( item = (Properties) iter.next())
}
SQLExceptions and warnings
   SQLExceptions can be nested
   Process by calling the exceptions
    getNextException() method
   Warnings can be sent to the connection
   Process in similar way with getNextWarning
   You must explicitly check for warnings while
    SQLExceptions you are required to handle
Transaction Support
   autoCommit is true by default
   Use setAutoCommit to false to enable
    control of transactions
   commit() commits the transactions
   rollback() rollbacks the transactions
   Support for distributed transactions with
    the help of a transaction manager
Batch Updates
   Statements can be batched to allow
    faster processing of a bunch of SQL
Statement statement = conn.createStatement();
try {
  do {
    String sql = "INSERT INTO catalogue VALUES('" + mr.title +
   "','" + mr.actor + "','" + mr.actress + "'," + mr.type +
   "," + mr.date ")";
    statement.addBatch(sql);
  } while ( mr = (MovieInfo) iter.next())
  statement.executeBatch();
}
Lab 12
   Write a servlet that handles 4 actions:
       Create a table – foo(int, char(20),
        char(10)) – drops if exists
       Insert a 1000 rows using a statement
       Insert a 1000 rows using a
        preparedstatement
       Insert a 1000 rows using a batch
        statement
       Query the first 15 rows of the table
Datasources
Connection Pooling
XML
   Extensible Markup Language
   Specification developed by the W3C
   A simplified version of SGML
   Markup meta-language – a language for
    describing markup languages
   XHTML is HTML defined using XML
XML and data
   HTML is great for describing how things
    should look:
    <strong>New York</strong>
     But what is this???

   XML is a way to put structured data in a
    text file
   No presentation info – just data
   We can give our data meaning
Well-formed XML

    <?xml version=‘1.0’?>
    <Student>
       <StudentID>999-88-7777</StudentID>
       <Name>Bill Smith</Name>
       <Email>bsmith@indiana.edu</Email>
       <Transfer/>
    </Student>
    Well-formed XML
   Must start with <?xml version=“1.0”?>
   Must have only one root tag
   Tags are case sensitive
   Beginning tags must have an ending tag
   Beginning tags can end with / if there is
    no content.
   Attribute values must be in quotes
XML Components
   Element: <lastname>
   Attribute: <cat name=“Sidney”>
   Comment: <!– Comment -->
   Processing Instruction: <?name data?>
   Node:
      <user>
         <lastname>Smith</lastname>
         <firstname>John</firstname>
      </user>
XML Escape Entities
   Internal Entities
       &lt; = <
       &gt; = >
       &amp; = &
       &apos; = ‘
       &quot; = “
   Blocks of data can be done with <![CDATA[ … ]]>
   External Entities can be defined in a
    document as shortcuts
       <!ENTITY IU “Indiana University">
       &IU; = Indiana University
Sharing XML
   Problem: if everyone makes up their own
    tags, how will we ever agree on what the
    data means?
   Answer: we need some rules
   We need a way to define our tags, plus any
    relationships between them
   People who share this set of rules can
    exchange data in a meaningful way
   This would be valid XML
                            <weather>
                             <city>
                               <name>Bloomington</name>
                              <report>


 DTD
                                <high>76</high>
                               <low>46</low>
                               <precip day_total=“0” type=“rain” force=“light”/>
                             </report>
                             </city>
                            </weather>


     Document Type Definition
<!--   ELEM NAME     CONTENT MODEL               -->
<!ELEMENT     weather       (city+)                >
<!ELEMENT     city   (name, report)                >
<!ELEMENT     name   (#PCDATA)                     >
<!ELEMENT     report (high, low, precip?)          >
<!ELEMENT     high   (#PCDATA)                     >
<!ELEMENT     low    (#PCDATA)                     >
<!ELEMENT     precip EMPTY                         >
<!ATTLIST     precip day_total     CDATA # REQUIRED
              type   (rain | snow) “rain”
              force (light | heavy)       #IMPLIED >
    Schemas

   Schemas provide the same functionality
    as DTDs, but in an XML format:
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema
     xmlns:xsd="http://www.w3.org/2000/10/XMLSchema">
<xsd:element name="weather">
 <xsd:complexType>
  <xsd:sequence>
   <xsd:element name="city" minOccurs="1" maxOccurs="Unbounded">
    <xsd:complexType>
     <xsd:element name="name" type="xsd:string"/>
     <xsd:element name="report">
      <xsd:complexType>
       <xsd:element name="high" type="xsd:integer"/>
       <xsd:element name="low" type="xsd:integer"/>
       <xsd:element name="precip">
        <xsd:complexType>
         <xsd:attribute name="day_total" type="xsd:decimal"/>
         <xsd:attribute name="type"      type="xsd:string"/>
Schema initiatives
   There are lots of schemas already out
    there
   Most are industry specific
   No need to reinvent the wheel
   Check out www.biztalk.org
Name Collisions
   What if somebody else is already using
    our tags???
   We need a way to allow people to
    define unique tags and attributes and
    have them coexist in the same
    document
   Namespaces solve this problem
 Namespaces
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/1999/XMLSchema">
 <SOAP-ENV:Body>
  <ns1:getTempResponse xmlns:ns1="urn:xmethods-Temperature"
   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <return xsi:type="xsd:float">73.0</return>
  </ns1:getTempResponse>
 </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Applications for XML
   Separate Presentation from Data
       Allows multiple presentations of same data
   Pass datasets to a browser. Browser
    script can manipulate data (IE 4&5, NS
    6 only)
   Store data
   Pass data between applications
Lab 13
   Write a XML file that is a personal
    address book
   People can have multiple addresses and
    phone numbers
   Denote whether the person is a friend,
    co-worker, or business contact
   Have Jbuilder generate a DTD for your
    address book
XML Parsers
   An XML Parser is used to read an XML
    file
   Parsers can verify that XML is Well-
    formed
   Parsers can validate XML against a DTD
    or Schema
   Parsers are available for just about any
    language/platform
XML Parsers
   Xerces – http://xml.apache.org (Java, C++)
   Dom4j – http://dom4j.org/ (Java)
   Oracle – http://technet.oracle.com/tech/xml
    (Java, C, C++)
   JDOM – http://www.jdom.org (Java)
   Sun – http://java.sun.com/xml (Java)
   Lots more!
XML Parser Types
   Java API for XML Processing (JAXP)
   Simple API for XML (SAX)
   Document Object Model (DOM)
Other Java XML processors
   Java Architecture for XML Binding
    (JAXB)
   Java API for XML Messaging (JAXM)
   Java API for XML-based RPC (JAX-RPC)
   Java API for XML Registries (JAXR)
JAXP
   Java API for XML Processing
   Provide a standard programming interface for
    transformation and processing of XML using
    either SAX or DOM
   Implementation can be switched without re-
    compiling
   Will be included in Java 2 Standard Edition
    1.4
   We’ll be using this in our examples
SAX Parser
   Simple API for XML
   Reads XML as a stream through a single pass
   Allows sequential access to document
   Calls handlers in your code based on contents
    of XML
   Use on huge XML files
   Fast
   Works by processing events beginDocument,
    endDocument, etc.
DOM Parser
   Document Object Model Parser
   Builds a tree representation of document in
    memory
   The tree can be navigated in code
   Use on smaller XML files
   Slower than SAX parser
   Allows Random access to document
   Allows easy document modification
JDOM
   More Java specific – uses Collections
    Framework rather than Enumerations
   Rather than making everything a node
    in a tree, explicitly types the XML
    elements
   Ability to translate to DOM objects
   Can parse from either SAX or DOM
    objects
Parser Implementations
   Java
       Sun - JAXP
       Apache – Xerces
   Other
       Oracle – XDK for Java, C, C++, PL/SQL




             There are a lot more!
Lab 13
Writing Tag Libraries
JNDI
MVC Issues
Design issues
Web Deployment
   Authentication
   Deployment Configuration

								
To top