SlideShare una empresa de Scribd logo
1 de 97
Descargar para leer sin conexión
Module 3:
  Servlet Advanced


Thanisa Kruawaisayawan
 Thanachart Numnonda
 www.imcinstitute.com
Objectives
   Including, forwarding to, and redirecting to
    other web resources
   Servlet & JDBC
   Session Tracking API
   Scope Objects
   Servlet Listener
   Servlet Filter


                                                   2
When to Include another Web resource?
 When it is useful to add static or dynamic
 contents already created by another web
 resource
   Adding a banner content or copyright information in
   the response returned from a Web component




                                                      3
How to Include another Web resource?

   Get RequestDispatcher object from ServletContext
    object
    RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher(“/banner");
   Then, invoke the include() method of the
    RequestDispatcher object passing request and
    response objects
     dispatcher.include(request,   response);

                                                           4
When to use “Forwarding” to another
              Web resource?
   When you want to have one Web component do preliminary
    processing of a request and have another component
    generate the response
   You might want to partially process a request and then
    transfer to another component depending on the nature of
    the request



                                                               5
How to do “Forwarding” to another Web
              resource?
   Get RequestDispatcher object from HttpServletRequest object
      Set “request URL” to the path of the forwarded page
     RequestDispatcher dispatcher
              = request.getRequestDispatcher(“/template.jsp");
   If the original URL is required for any processing, you can save
    it as a request attribute
   Invoke the forward() method of the RequestDispatcher object
        dispatcher.forward(request, response);
                                                                       6
Redirecting a Request
 Two programming models for
 directing a request
 Method   1:
 response.setStatus(response.SC_MOVED_PERMANTLY);
 response.setHeader("Location", "http://...");


 Method   2:
 response.sendRedirect("http://...");
                                                    7
Servlet & JDBC




                 8
What is JDBC?
Standard Java API for accessing
relational database
 Hides  database specific details from
  application
Part of Java SE (J2SE)
 Java   SE 7 has JDBC 4.1




                                          9
JDBC API
   Defines a set of Java Interfaces, which are implemented by
    vendor-specific JDBC Drivers
        Applications use this set of Java interfaces for performing
         database operations - portability
   Majority of JDBC API is located in java.sql package
        DriverManager, Connection, ResultSet, DatabaseMetaData,
         ResultSetMetaData, PreparedStatement, CallableStatement and
         Types
   Other advanced functionality exists in the javax.sql package
        DataSource

                                                                       10
JDBC Driver

   Database specific implemention of JDBC
    interfaces
     Everydatabase server has corresponding
      JDBC driver(s)
   You can see the list of available drivers
    from
     http://industry.java.sun.com/products/jdbc/
      drivers
                                                    11
Database URL
   Used to make a connection to the database
    – Can contain server, port, protocol etc…

    jdbc:subprotocol_name:driver_dependant_databasename
    – Oracle thin driver
       jdbc:oracle:thin:@machinename:1521:dbname
    – MySQL
       jdbc:mysql://localhost:3306/test


                                                          12
MySQL Tools

 mysql-installer-5.5.22.1.msi (Database)
 mysql-workbench-gpi-5.2-40-win32.msi (GUI)
 mysql-connector-java-5.1.19-bin.jar (Driver)
     Copy   to C:Program FilesApache Software
     FoundationApache Tomcat 7.0.27lib




                                                   13
SQL Commands
   CREATE   - Builds a new table with the specified field name and
    types
   INSERT - Adds a new record to the named table
   SELECT - Retrieves records from the named table
   DELETE - Removes one or more record(s) from the table
   UPDATE - Modified one or more field(s) of particular record(s)
   DROP - Completely removes a table from the database




                                                                      14
CREATE Statement
   The formal syntax
    CREATE TABLE table_name(column [ , column] …)


   For example
    CREATE TABLE Books(ISBN varchar(5) not null PRIMATY KEY,
                     title varchar(50) not null,
           author varchar(50), price float);




                                                               15
INSERT Statement
   The formal syntax
    INSERT INTO table_name (column [ , column] …) VALUES
    (value [, value] …)


   For example
    INSERT INTO Books VALUES('11111', 'J2ME on Symbian OS',
                   'Sam', 40);




                                                              16
SELECT Statement
   The formal syntax
    SELECT [table.]column [ , [table].column] …
    FROM table [ , table] …
    [WHERE [table.]column OPERATOR VALUE
    [AND] OR [table.]column OPERATOR VALUE …
    [ORDER BY [table.]column [DESC] [ ,[table.]column
      [DESC}]


   For example
    SELECT * FROM Books WHERE ISBN = '11111';
                                                        17
DELETE Statement
 The   formal syntax
 DELETE FROM table_name WHERE column OPERATOR value
   [AND | OR column OPERATOR value ] …


 For   example
 DELETE FROM Book WHERE ISBN = '11111';




                                                      18
Steps of Using JDBC

1. Load DB-specific JDBC driver
2. Get a Connection object
3. Get a Statement object
4. Execute queries and/or updates
5. Read results
6. Read Meta-data (optional step)
7. Close Statement and Connection objects

                                            19
1. Load DB-Specific Database Driver

   To manually load the database driver and register
    it with the DriverManager, load its class file
    – Class.forName(<database-driver>)

       try {
          // This loads an instance of the Pointbase DB Driver.
          // The driver has to be in the classpath.
          Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException cnfe){
           System.out.println("" + cnfe);
       }
                                                                  20
2. Get a Connection Object
   DriverManager class is responsible for selecting the
    database and and creating the database connection
      Using  DataSource is a prefered means of getting a
       conection object
   Create the database connection as follows:
try {
    Connection connection =
      DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
                               "root",   "root");
} catch(SQLException sqle) {
   System.out.println("" + sqle);
}
                                                                        21
DriverManager & Connection

   java.sql.DriverManager
       •   getConnection(String url, String user, String password) throws
           SQLException


   java.sql.Connection
       •   Statement createStatement() throws SQLException
       •   void close() throws SQLException
       •   void setAutoCommit(boolean b) throws SQLException
       •   void commit() throws SQLException
       •   void rollback() throws SQLException


                                                                            22
Sub-Topics
   DataSource interface and DataSource
    object
   Properties of a DataSource object
   JNDI registration of a DataSource object
   DataSource object that implements
    Connection pooling


                                               23
javax.sql.DataSource Interface and
          DataSource Object

 Driver   vendor implements the interface
 DataSource object is the factory for creating
 database connections




                                                  24
Properties of DataSource Object
   A DataSource object has properties that can be modified when
    necessary – these are defined in a container's configuration file
      location   of the database server
      name     of the database
      network    protocol to use to communicate with the
       server
   The benefit is that because the data source's properties can be
    changed, any code accessing that data source does not need to
    be changed
   In the GlassFish Application Server, a data source is called a
    JDBC resource
                                                                        25
JNDI Registration of a DataSource (JDBC
           Resource) Object
   The JNDI name of a JDBC resource is expected
    in the java:comp/env/jdbc subcontext
     For example, the JNDI name for the resource of
      a BookDB database could be
      java:comp/env/jdbc/BookDB
   Because all resource JNDI names are in the
    java:comp/env subcontext, when you specify the
    JNDI name of a JDBC resource enter only
    jdbc/name. For example, for a payroll database,
    specify jdbc/BookDB                             26
Why Connection Pooling?
   Database connection is an expensive and limited
    resource
     Using connection pooling, a smaller number of
      connections are shared by a larger number of clients
   Creating and destroying database connections are
    expensive operations
     Using  connection pooling, a set of connections are pre-
      created and are available as needed basis cutting down
      on the overhead of creating and destroying database
      connections

                                                                 27
Connection Pooling & DataSource

   DataSource objects that implement connection
    pooling also produce a connection to the
    particular data source that the DataSource class
    represents
   The connection object that the getConnection
    method returns is a handle to a PooledConnection
    object rather than being a physical connection
      The   application code works the same way

                                                       28
3. Get a Statement Object

 Create   a Statement Object from Connection
 object
    • java.sql.Statement
        – ResultSet executeQuery(string sql)
        – int executeUpdate(String sql)
    • Example:
       Statement statement = connection.createStatement();
 The
    same Statement object can be used for
 many, unrelated queries
                                                             29
4. Executing Query or Update

   From the Statement object, the 2 most used
    commands are
    – (a) QUERY (SELECT)
       •   ResultSet rs = statement.executeQuery("select * from
           customer_tbl");


    – (b) ACTION COMMAND (UPDATE/DELETE)
       •   int iReturnValue = statement.executeUpdate("update
           manufacture_tbl set name = ‘IBM' where mfr_num = 19985678");



                                                                          30
5. Reading Results

   Loop through ResultSet retrieving information
      java.sql.ResultSet
            boolean next()
            xxx getXxx(int columnNumber)
            xxx getXxx(String columnName)
            void close()
   The iterator is initialized to a position before the first
    row
     – You must call next() once to move it to the first row


                                                                 31
5. Reading Results (cont.)
   Once you have the ResultSet, you can easily
    retrieve the data by looping through it
       while (rs.next()){
        // Wrong this will generate an error
        String value0 = rs.getString(0);

           // Correct!
           String value1 = rs.getString(1);
           int value2 = rs.getInt(2);
           int value3 = rs.getInt(“ADDR_LN1");
       }

                                                  32
5. Reading Results (cont.)

 When retrieving data from the ResultSet, use
 the appropriate getXXX() method
    •   getString()
    •   getInt()
    •   getDouble()
    •   getObject()
 Thereis an appropriate getXXX method of
 each java.sql.Types datatype

                                                 33
6. Read ResultSet MetaData and
        DatabaseMetaData (Optional)
 Once you have the ResultSet or Connection
  objects, you can obtain the Meta Data about
  the database or the query
 This gives valuable information about the data
  that you are retrieving or the database that you
  are using
    – DatabaseMetaData dbmd = connection.getMetaData();
    – ResultSetMetaData rsMeta = rs.getMetaData();
       •   There are approximately 150 methods in the
           DatabaseMetaData class.

                                                          34
Example
public void showDBInfo() {{
 public void showDBInfo()
    try {{
     try
         DatabaseMetaData dbmd == connection.getMetaData();
          DatabaseMetaData dbmd    connection.getMetaData();
         System.out.println("Product: "" ++ dbmd.getDatabaseProductName());
          System.out.println("Product:       dbmd.getDatabaseProductName());
         System.out.println("Version: "" ++ dbmd.getDatabaseProductVersion());
          System.out.println("Version:       dbmd.getDatabaseProductVersion());
         System.out.println ("Stored Procedures: "" ++
          System.out.println ("Stored Procedures:
                         dbmd.supportsStoredProcedures());
                          dbmd.supportsStoredProcedures());
         System.out.println("Transactions: "" ++
          System.out.println("Transactions:
                         dbmd.supportsTransactions());
                          dbmd.supportsTransactions());
    }} catch (SQLException ex) {{
        catch (SQLException ex)
         ex.getMessage();
          ex.getMessage();
    }}
}}




                                                                              35
ResultSetMetaData Example
ResultSetMetaData meta = rs.getMetaData();
//Return the column count
int iColumnCount = meta.getColumnCount();

for (int i =1 ; i <= iColumnCount ; i++){
  System.out.println(“Column Name: " + meta.getColumnName(i));
  System.out.println(“Column Type" + meta.getColumnType(i));
  System.out.println("Display Size: " + meta.getColumnDisplaySize(i) );
  System.out.println("Precision: " + meta.getPrecision(i));
  System.out.println(“Scale: " + meta.getScale(i) );
}


                                                                          36
What Are They?

 PreparedStatement
    • SQL is sent to the database and compiled or prepared
      beforehand
 CallableStatement
    • Executes SQL Stored Procedures




                                                             37
PreparedStatement                Interface
   To call the same SQL statement multiple times, use a
    PrepareStatement object.
   Extend PreparedStatement from Statement class.
       public interface PreparedStatement extends Statement
   Advantage
     Using Statement  needs to compile every times.
       PreparedStatement will compile only once.




                                                               38
Example
 public void insertData() {{
  public void insertData()
     PreparedStatement pstmt;
      PreparedStatement pstmt;
     String insertCmd == "INSERT INTO Book VALUES(?,?,?,?)";
      String insertCmd      "INSERT INTO Book VALUES(?,?,?,?)";
     try {{
      try
           pstmt == connection.prepareStatement(insertCmd);
            pstmt    connection.prepareStatement(insertCmd);
           pstmt.setString(1,"11111");
            pstmt.setString(1,"11111");
           pstmt.setString(2,"J2ME on Symbian OS");
            pstmt.setString(2,"J2ME on Symbian OS");
           pstmt.setString(3,"Sam");
            pstmt.setString(3,"Sam");
           pstmt.setDouble(4,40);
            pstmt.setDouble(4,40);
           pstmt.executeUpdate();
            pstmt.executeUpdate();
     }} catch (SQLException ex) {{
         catch (SQLException ex)
           ex.getMessage();
            ex.getMessage();
     }}
}}




                                                                  39
CallableStatement
   The interface used to execute SQL stored procedures
   A stored procedure is a group of SQL statements that form
    a logical unit and perform a particular task
   A CallableStatement object contains a call to a stored
    procedure; it does not contain the stored procedure itself.
   The part that is enclosed in curly braces is the escape
    syntax for stored procedures.
     CallableStatement cs = connection.prepareCall("{call SHOW_SUPPLIERS}");
      ResultSet rs = cs.executeQuery();



                                                                           40
JDBC Core API




                41
Servlet & JDBC




                 42
Servlet & JDBC (cont.)




                         43
Why Session Tracking?
   Need a mechanism to maintain state across a
    series of requests from the same user (or
    originating from the same browser) over some
    period of time
      Example:   Online shopping cart
   Yet, HTTP is stateless protocol
      Each time, a client talks to a web server, it opens a new
       connection
      Server does not automatically maintains
       “conversational state” of a user
                                                                   44
Session Tracking Use Cases
 When    clients at an on- line store add an
  item to their shopping cart, how does
  the server know what’s already in the
  cart?
 When clients decide to proceed to
  checkout, how can the server determine
  which previously created shopping cart
  is theirs?                                    45
A Session Maintains Client Identity and State across
            multiple HTTP requests

 Client 1


                            server
                                     Session 1
             Session ID 1




  Client 2   Session ID 2

                                     Session 2


                                                       46
Three “underlying” Session Tracking
           Mechanisms
   Cookies
   URL rewriting
   Hidden form fields
   Note that these are just underlying mechanisms of
    passing “session id”
      do not provide high-level programming APIs
      do not provide a framework for managing sessions
      This is what Servlet Session Tracking feature provides


                                                                47
What is HTTP Cookie?
   Cookie is a small amount of information sent by a
    servlet to a Web browser
   Saved by the browser, and later sent back to the
    server in subsequent requests
      A cookie has a name, a single value, and optional attributes
      A cookie's value can uniquely identify a client

   Server uses cookie's value to extract information
    about the session from some location on the server

                                                                      48
Class Cookie




               49
Cookies as Session Tracking
              Mechanism
   Advantages:
     Very easy to implement
     Highly customizable
     Persist across browser shut-downs
   Disadvantages:
     Often: users turn off cookies for privacy or
     security reason
     Not quite universal browser support
                                                     50
URL Rewriting
 URLs   can be rewritten or encoded to include
  session information.
 URL rewriting usually includes a session id
 Example:
http://localhost:8080/bookstore1/cashier;jsessionid
   =c0o7fszeb1




                                                      51
URL Rewriting as Session Tracking
         Mechanism
   Advantages:
     Letuser remain anonymous
     They are universally supported(most styles)
   Disadvantages:
     Tediousto rewrite all URLs
     Only works for dynamically created
     documents

                                                    52
If Cookie is turned off..
   If your application makes use of session
    objects
     you must ensure that session tracking is enabled
     by having the application rewrite URLs whenever
     the client turns off cookies
     by calling the response's encodeURL(URL)
     method on all URLs returned by a servlet
     This method includes the session ID in the URL
     only if cookies are disabled; otherwise, it returns
     the URL unchanged                                   53
Example: response.encodeURL()
out.println("<strong><a href="" +
    response.encodeURL(request.getContextPath() + "/cashier") +
  ""></a></strong>");



   If cookies are turned off
        http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1
   If cookies are turned on
        http://localhost:8080/bookstore1/cashier

                                                                          54
Hidden Form Fields
   Hidden form fields do not display in the
    browser, but can be sent back to the server by
    submit
<INPUT TYPE=”HIDDEN” NAME=”session” VALUE=”...”>
   Fields can have identification (session id) or just
    some thing to remember (occupation)
   Servlet reads the fields using req.getParameter()



                                                          55
Hidden Form Fields as Session Tracking
            Mechanism
   Advantages:
     Universally
                supported.
     Allow anonymous users
   Disadvantages:
     Only works for a sequence of dynamically
     generated forms.
     Breaks down with static documents, emailed
     documents, bookmarked documents.
     No browser shutdowns.                        56
HttpSession
 Toget a user's existing or new session
 object:
   HttpSession      session = request.getSession(true);
        "true"
             means the server should create a new
      session object if necessary
   HttpSession is Java interface

        Container   creates a object of HttpSession type

                                                            57
Example: Getting HttpSession Object
public class CatalogServlet extends HttpServlet {
   public void doGet (HttpServletRequest request,
                  HttpServletResponse response)
     throws ServletException, IOException {

     // Get the user's session and shopping cart
     HttpSession session = request.getSession(true);
           ...
     out = response.getWriter();
           ...
       }
  }
  ...



                                                       58
HttpSession Java Interface
 Contains   Methods to
   View  and manipulate information about a session,
   such as the session identifier, creation time, and
   last accessed time
   Bind objects to sessions, allowing user
   information to persist across multiple user
   connections


                                                        59
HttpSession Methods
   getId()
      Returns the unique identifier
   isNew()
      Determines if session is new to client (not page)
   getCreationTime()
      Returns time at which session was first created
   getLastAccessedTime()
      Returns time at which the session was last sent from the
       client
   invalidate()
      Invalidate the session and unbind all objects associated
       with it
                                                                  60
Store and Retrieve of Attribute
 To   stores values:
   session.setAttribute("cart",   cart);
 To   retrieves values:
   session.getAttribute("cart");




                                            61
Session Timeout
   Used when an end-user can leave the browser without
    actively closing a session
   Sessions usually timeout after 30 minutes of inactivity
      Product   specific
      A different   timeout may be set by server admin
   getMaxInactiveInterval(), setMaxInactiveInterval()
    methods of HttpSession interface
      Gets or sets the amount of time, session should go without
       access before being invalidated
                                                                    62
Issues with “Stale” Session Objects

   The number of “stale” session objects that are in “to
    be timed out” could be rather large
   Example
      1000  users with average 2 minutes session time, thus 15000
       users during the 30 minutes period
      4K bytes of data per session
      15000 sessions * 4K -= 60M bytes of session data
      This is just for one Web application

   Could have an performance impact
      Use   the data space in Session object with care
                                                                     63
Session Invalidation
   Can be used by servlet programmer to end a session
    proactively
      when a user at the browser clicks on “log out” button
      when a business logic ends a session (“checkout” page in the example
       code in the following slide)
   public void invalidate()
        Expire the session and unbinds all objects with it
   Caution
        Remember that a session object is shared by multiple servlets/JSP-
         pages and invalidating it could destroy data that other servlet/JSP-
         pages are using
                                                                                64
Example: Invalidate a Session
 public class ReceiptServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
       throws ServletException, IOException {
                ...
       scart = (ShoppingCart)
          session.getAttribute("examples.bookstore.cart");
                ...
       // Clear out shopping cart by invalidating the session
       session.invalidate();

        // set content type header before accessing the Writer
        response.setContentType("text/html");
        out = response.getWriter();
        ...
    }
}


                                                                 65
Scope Objects
   Enables sharing information among
    collaborating web components via attributes
    maintained in Scope objects
     Attributes   are name/object pairs
   Attributes maintained in the Scope objects
    are accessed with
     getAttribute()   & setAttribute()
   4 Scope objects are defined
     Web   context, session, request, page
                                                  66
Four Scope Objects: Accessibility
   Web context (ServletContext)
     Accessible   from Web components within a Web
      context
   Session
     Accessible from Web components handling a request
      that belongs to the session
   Request
     Accessible   from Web components handling the
      request
   Page
     Accessible   from JSP page that creates the object   67
Four Scope Objects: Class
   Web context
     javax.servlet.ServletContext

   Session
     javax.servlet.http.HttpSession

   Request
     javax.servlet.http.HttpServletRequest

   Page
     javax.servlet.jsp.PageContext

                                              68
Session, Application Scope
Client 1


                             server
                                      Session 1
              Session ID 1




 Client 2     Session ID 2

                                      Session 2



 Client 1


                             server



                                      application

   Client 2
Session, Request, Page Scope
                                                   client




             request
                                  response         request               response




 Page 1        forward      Page 2                          Page 3                   Page 4
                                                                     forward



Page scope                Page scope                        Page scope          Page scope


          request scope
                                                                     request scope



                                       Session scope
Scope of Objects




                   71
What is ServletContext For?
   Used by servlets to
      Set and get context-wide (application-wide) object-
       valued attributes
      Get request dispatcher
            To forward to or include web component
      Access Web  context-wide initialization parameters set in
       the web.xml file
      Access Web resources associated with the Web context
      Log
      Access other misc. information

                                                                   72
Scope of ServletContext
   Context-wide scope
     Shared by all servlets and JSP pages within a "web
      application"
           Why it is called “web application scope”
     A "web   application" is a collection of servlets and content
      installed under a specific subset of the server's URL
      namespace and possibly installed via a *.war file
           All servlets in BookStore web application share same
            ServletContext object
     There is one ServletContext object per "web application"
      per Java Virtual Machine
                                                                      73
Example: Getting Attribute Value
         from ServletContext
public class CatalogServlet extends HttpServlet {
    private BookDB bookDB;
    public void init() throws ServletException {
        // Get context-wide attribute value from
        // ServletContext object
        bookDB = (BookDB)getServletContext().
                         getAttribute("bookDB");
        if (bookDB == null) throw new
         UnavailableException("Couldn't get database.");
    }
}                                                      74
What is Servlet Request?
   Contains data passed from client to servlet
   All servlet requests implement ServletRequest interface
    which defines methods for accessing
        Client sent parameters
        Object-valued attributes
        Locales
        Client and server
        Input stream
        Protocol information
        Content type
        If request is made over secure channel (HTTPS)       75
Requests
data,
client, server, header
servlet itself
       Request                  Servlet 1



                                Servlet 2



      Response                  Servlet 3


                               Web Server   76
Servlet Lifecycle Events
 Support   event notifications for state changes
 in
   ServletContext
       Startup/shutdown

       Attribute   changes
   HttpSession
       Creationand invalidation
       Changes in attributes


                                                    77
Listener Interfaces
   ServletContextListener
        contextInitialized/Destroyed(ServletContextEvent)
   ServletContextAttributeListener
        attributeAdded/Removed/Replaced(ServletContextAttributeEvent)
   HttpSessionListener
        sessionCreated/Destroyed(HttpSessionEvent)
   HttpSessionAttributeListener
        attributedAdded/Removed/Replaced(HttpSessionBindingEvent)
   HttpSessionActivationListener
        Handles sessions migrate from one server to another
        sessionWillPassivate(HttpSessionEvent)
        sessionDidActivate(HttpSessionEvent)                            78
Listener Registration
   Web container
      creates  an instance of each listener class
      registers it for event notifications before processing first
       request by the application
      Registers the listener instances according to
          the interfaces they implement

          the order in which they appear in the deployment

           descriptor web.xml
   Listeners are invoked in the order of their registration
    during execution                                                79
Steps for Implementing Servlet Lifecycle
                   Event
1. Decide which scope object you want to receive an event
   notification
2. Implement appropriate interface
3. Override methods that need to respond to the events of interest
4. Obtain access to important Web application objects and use them
5. Configure web.xml accordingly
6. Provide any needed initialization parameters


                                                                     80
Example: Context Listener
public final class ContextListener
    implements ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
         context = event.getServletContext();

         try {
            BookDB bookDB = new BookDB();
            context.setAttribute("bookDB", bookDB);
         } catch (Exception ex) {
            context.log("Couldn't create bookstore
                         database bean: " + ex.getMessage());
         }

         Counter counter = new Counter();
         context.setAttribute("hitCounter", counter);
         counter = new Counter();
         context.setAttribute("orderCounter", counter);
    }

                                                                  81
Example: Context Listener
    public void contextDestroyed(ServletContextEvent event) {
         context = event.getServletContext();
         BookDB bookDB =(BookDB)context.getAttribute("bookDB");
         bookDB.remove();
         context.removeAttribute("bookDB");
         context.removeAttribute("hitCounter");
         context.removeAttribute("orderCounter");
    }
}




                                                                  82
Listener Configuration
<web-app>
  <display-name>Bookstore1</display-name>
  <description>no description</description>

  <filter>..</filter>
  <filter-mapping>..</filter-mapping>
  <listener>
    <listener-class>listeners.ContextListener</listener-class>
  </listener>
  <servlet>..</servlet>
  <servlet-mapping>..</servlet-mapping>
  <session-config>..</session-config>
  <error-page>..</error-page>
  ...
</web-app>
                                                            83
What are Java Servlet Filters?
   New component framework for intercepting and
    modifying requests and responses
     Filters
            can be chained and plugged in to the system during
      deployment time
   Allows range of custom activities:
     Marking    access, blocking access
     Caching,   compression, logging
     Authentication,   access control, encryption
   Introduced in Servlet 2.3 (Tomcat 4.0)
     Content   transformations
                                                                 84
What Can a Filter Do?
   Examine the request headers
   Customize the request object if it wishes to modify
    request headers or data
   Customize the response object if it wishes to modify
    response headers or data
   Invoke the next entity in the filter chain
   Examine response headers after it has invoked the
    next filter in the chain
   Throw an exception to indicate an error in processing
                                                            85
How Servlet Filter Work?
 Servlet                                                                      Servlet
Container                       Filter Chain




                 Filter 1         Filter 2                 Filter N




                                        doFilter(
   User             Servlet                                           service(
                                        ServletRequest,
   implemented      container                                         ServletRequest,
   filters          filter
                                        ServletResponse,
                                        FilterChain)
                                                                      ServletResponse)   86
javax.servlet.Filter Interface
   init(FilterConfig)
      called only once when the filter is first initialized
      get ServletContext object from FilterConfig object and
       save it somewhere so that doFilter() method can access it
      read filter initialization parameters from FilterConfig
       object through getInitParameter() method
   destroy()
      called only once when container removes filter object
      close files or database connections



                                                                   87
How Filter Chain Works
   Multiple filters can be chained
        order is dictated by the order of <filter> elements in the web.xml
         deployment descriptor
   The first filter of the filter chain is invoked by the
    container
      via doFilter(ServletRequest req, ServletResponse res, FilterChain
       chain)
      the filter then perform whatever filter logic and then call the next
       filter in the chain by calling chain.doFilter(..) method
   The last filter's call to chain.doFilter() ends up calling
    service() method of the Servlet
                                                                              88
Steps for Building a Servlet Filter
   Decide what custom filtering behavior you want to
    implement for a web resource
   Create a class that implements Filter interface
     Implement  filtering logic in the doFilter() method
     Call the doFilter() method of FilterChain object

   Configure the filter with Target servlets and JSP
    pages
     use   <filter> and <filter-mapping> elements

                                                            89
Example: HitCounterFilter
public final class HitCounterFilter implements Filter
  {
  private FilterConfig filterConfig = null;

  public void init(FilterConfig filterConfig)
    throws ServletException {
    this.filterConfig = filterConfig;
  }
  public void destroy() {
    this.filterConfig = null;
  }

  // Continued in the next page...

                                                        90
Example: HitCounterFilter
    public void doFilter(ServletRequest request,
                ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

        if (filterConfig == null) return;
        StringWriter sw = new StringWriter();
        PrintWriter writer = new PrintWriter(sw);
        Counter counter = (Counter)
           filterConfig.getServletContext().getAttribute("hitCounter");
        writer.println("The number of hits is: " + counter.incCounter());

        // Log the resulting string
        writer.flush();
        filterConfig.getServletContext().log(sw.getBuffer().toString());
        ...
        chain.doFilter(request, wrapper);
        ...
    }
}                                                                           91
HitCounterFilter Configuration
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web
   Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>

<web-app>
  <display-name>Bookstore1</display-name>
  <description>no description</description>

  <filter>
    <filter-name>HitCounterFilter</filter-name>
    <filter-class>filters.HitCounterFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>HitCounterFilter</filter-name>
    <url-pattern>/enter</url-pattern>
  </filter-mapping>
  ...                                                                92
Configuration in web.xml
   <filter>
      <filter-name>: assigns a name of your choosing to the filter
      <filter-class>: used by the container to identify the filter class
   </filter>
   <filter-mapping>
      <filter-name>: assigns a name of your choosing to the filter
      <url-pattern>: declares a pattern URLs (Web resources) to which
        the filter applies
   </filter-mapping>


                                                                            93
Concurrency Issues on a Servlet
 The service() method of a servlet instance can be
  invoked by multiple clients (multiple threads)
 Servlet programmer has to deal with concurrency
  issue
     shared   data needs to be protected
     this is called “servlet synchronization”

   use of synchronized block


                                                      94
Many Threads,
 One Servlet Instance
                   Web Server

request
          thread

request   thread

request   thread
                       Servlet
          thread
request
          thread

request            Servlet container
                                       95
Use of synchronized block

 Synchronized blocks are used to
 guarantee only one thread at a time
 can execute within a section of code

 synchronized(this) {
      myNumber = counter + 1;
      counter = myNumber;
  }
 ...
 synchronized(this) {
      counter = counter + 1 ;
  }
                                        96
Thank you

   thananum@gmail.com
www.facebook.com/imcinstitute
   www.imcinstitute.com



                                97

Más contenido relacionado

La actualidad más candente

springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesArun Gupta
 
Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Tri Nguyen
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questionsArun Vasanth
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEEFahad Golra
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJini Lee
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the clientSebastiano Armeli
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6Lokesh Singrol
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 

La actualidad más candente (20)

springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
 
Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
Jdbc
JdbcJdbc
Jdbc
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEE
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Jsf Framework
Jsf FrameworkJsf Framework
Jsf Framework
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 

Similar a Java Web Programming [3/9] : Servlet Advanced

Similar a Java Web Programming [3/9] : Servlet Advanced (20)

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
JDBC
JDBCJDBC
JDBC
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Spring database - part2
Spring database -  part2Spring database -  part2
Spring database - part2
 
22jdbc
22jdbc22jdbc
22jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Lecture12
Lecture12Lecture12
Lecture12
 

Más de IMC Institute

นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14IMC Institute
 
Digital trends Vol 4 No. 13 Sep-Dec 2019
Digital trends Vol 4 No. 13  Sep-Dec 2019Digital trends Vol 4 No. 13  Sep-Dec 2019
Digital trends Vol 4 No. 13 Sep-Dec 2019IMC Institute
 
บทความ The evolution of AI
บทความ The evolution of AIบทความ The evolution of AI
บทความ The evolution of AIIMC Institute
 
IT Trends eMagazine Vol 4. No.12
IT Trends eMagazine  Vol 4. No.12IT Trends eMagazine  Vol 4. No.12
IT Trends eMagazine Vol 4. No.12IMC Institute
 
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformationเพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital TransformationIMC Institute
 
IT Trends 2019: Putting Digital Transformation to Work
IT Trends 2019: Putting Digital Transformation to WorkIT Trends 2019: Putting Digital Transformation to Work
IT Trends 2019: Putting Digital Transformation to WorkIMC Institute
 
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรมมูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรมIMC Institute
 
IT Trends eMagazine Vol 4. No.11
IT Trends eMagazine  Vol 4. No.11IT Trends eMagazine  Vol 4. No.11
IT Trends eMagazine Vol 4. No.11IMC Institute
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationIMC Institute
 
บทความ The New Silicon Valley
บทความ The New Silicon Valleyบทความ The New Silicon Valley
บทความ The New Silicon ValleyIMC Institute
 
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10IMC Institute
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationIMC Institute
 
The Power of Big Data for a new economy (Sample)
The Power of Big Data for a new economy (Sample)The Power of Big Data for a new economy (Sample)
The Power of Big Data for a new economy (Sample)IMC Institute
 
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง IMC Institute
 
IT Trends eMagazine Vol 3. No.9
IT Trends eMagazine  Vol 3. No.9 IT Trends eMagazine  Vol 3. No.9
IT Trends eMagazine Vol 3. No.9 IMC Institute
 
Thailand software & software market survey 2016
Thailand software & software market survey 2016Thailand software & software market survey 2016
Thailand software & software market survey 2016IMC Institute
 
Developing Business Blockchain Applications on Hyperledger
Developing Business  Blockchain Applications on Hyperledger Developing Business  Blockchain Applications on Hyperledger
Developing Business Blockchain Applications on Hyperledger IMC Institute
 
Digital transformation @thanachart.org
Digital transformation @thanachart.orgDigital transformation @thanachart.org
Digital transformation @thanachart.orgIMC Institute
 
บทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.orgบทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.orgIMC Institute
 
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital Transformationกลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital TransformationIMC Institute
 

Más de IMC Institute (20)

นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14
 
Digital trends Vol 4 No. 13 Sep-Dec 2019
Digital trends Vol 4 No. 13  Sep-Dec 2019Digital trends Vol 4 No. 13  Sep-Dec 2019
Digital trends Vol 4 No. 13 Sep-Dec 2019
 
บทความ The evolution of AI
บทความ The evolution of AIบทความ The evolution of AI
บทความ The evolution of AI
 
IT Trends eMagazine Vol 4. No.12
IT Trends eMagazine  Vol 4. No.12IT Trends eMagazine  Vol 4. No.12
IT Trends eMagazine Vol 4. No.12
 
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformationเพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
 
IT Trends 2019: Putting Digital Transformation to Work
IT Trends 2019: Putting Digital Transformation to WorkIT Trends 2019: Putting Digital Transformation to Work
IT Trends 2019: Putting Digital Transformation to Work
 
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรมมูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
 
IT Trends eMagazine Vol 4. No.11
IT Trends eMagazine  Vol 4. No.11IT Trends eMagazine  Vol 4. No.11
IT Trends eMagazine Vol 4. No.11
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformation
 
บทความ The New Silicon Valley
บทความ The New Silicon Valleyบทความ The New Silicon Valley
บทความ The New Silicon Valley
 
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformation
 
The Power of Big Data for a new economy (Sample)
The Power of Big Data for a new economy (Sample)The Power of Big Data for a new economy (Sample)
The Power of Big Data for a new economy (Sample)
 
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
 
IT Trends eMagazine Vol 3. No.9
IT Trends eMagazine  Vol 3. No.9 IT Trends eMagazine  Vol 3. No.9
IT Trends eMagazine Vol 3. No.9
 
Thailand software & software market survey 2016
Thailand software & software market survey 2016Thailand software & software market survey 2016
Thailand software & software market survey 2016
 
Developing Business Blockchain Applications on Hyperledger
Developing Business  Blockchain Applications on Hyperledger Developing Business  Blockchain Applications on Hyperledger
Developing Business Blockchain Applications on Hyperledger
 
Digital transformation @thanachart.org
Digital transformation @thanachart.orgDigital transformation @thanachart.org
Digital transformation @thanachart.org
 
บทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.orgบทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.org
 
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital Transformationกลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
 

Último

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Java Web Programming [3/9] : Servlet Advanced

  • 1. Module 3: Servlet Advanced Thanisa Kruawaisayawan Thanachart Numnonda www.imcinstitute.com
  • 2. Objectives  Including, forwarding to, and redirecting to other web resources  Servlet & JDBC  Session Tracking API  Scope Objects  Servlet Listener  Servlet Filter 2
  • 3. When to Include another Web resource?  When it is useful to add static or dynamic contents already created by another web resource  Adding a banner content or copyright information in the response returned from a Web component 3
  • 4. How to Include another Web resource?  Get RequestDispatcher object from ServletContext object RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(“/banner");  Then, invoke the include() method of the RequestDispatcher object passing request and response objects  dispatcher.include(request, response); 4
  • 5. When to use “Forwarding” to another Web resource?  When you want to have one Web component do preliminary processing of a request and have another component generate the response  You might want to partially process a request and then transfer to another component depending on the nature of the request 5
  • 6. How to do “Forwarding” to another Web resource?  Get RequestDispatcher object from HttpServletRequest object  Set “request URL” to the path of the forwarded page RequestDispatcher dispatcher = request.getRequestDispatcher(“/template.jsp");  If the original URL is required for any processing, you can save it as a request attribute  Invoke the forward() method of the RequestDispatcher object  dispatcher.forward(request, response); 6
  • 7. Redirecting a Request  Two programming models for directing a request  Method 1: response.setStatus(response.SC_MOVED_PERMANTLY); response.setHeader("Location", "http://...");  Method 2: response.sendRedirect("http://..."); 7
  • 9. What is JDBC? Standard Java API for accessing relational database  Hides database specific details from application Part of Java SE (J2SE)  Java SE 7 has JDBC 4.1 9
  • 10. JDBC API  Defines a set of Java Interfaces, which are implemented by vendor-specific JDBC Drivers  Applications use this set of Java interfaces for performing database operations - portability  Majority of JDBC API is located in java.sql package  DriverManager, Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement, CallableStatement and Types  Other advanced functionality exists in the javax.sql package  DataSource 10
  • 11. JDBC Driver  Database specific implemention of JDBC interfaces  Everydatabase server has corresponding JDBC driver(s)  You can see the list of available drivers from  http://industry.java.sun.com/products/jdbc/ drivers 11
  • 12. Database URL  Used to make a connection to the database – Can contain server, port, protocol etc…  jdbc:subprotocol_name:driver_dependant_databasename – Oracle thin driver jdbc:oracle:thin:@machinename:1521:dbname – MySQL jdbc:mysql://localhost:3306/test 12
  • 13. MySQL Tools  mysql-installer-5.5.22.1.msi (Database)  mysql-workbench-gpi-5.2-40-win32.msi (GUI)  mysql-connector-java-5.1.19-bin.jar (Driver)  Copy to C:Program FilesApache Software FoundationApache Tomcat 7.0.27lib 13
  • 14. SQL Commands  CREATE - Builds a new table with the specified field name and types  INSERT - Adds a new record to the named table  SELECT - Retrieves records from the named table  DELETE - Removes one or more record(s) from the table  UPDATE - Modified one or more field(s) of particular record(s)  DROP - Completely removes a table from the database 14
  • 15. CREATE Statement  The formal syntax CREATE TABLE table_name(column [ , column] …)  For example CREATE TABLE Books(ISBN varchar(5) not null PRIMATY KEY, title varchar(50) not null, author varchar(50), price float); 15
  • 16. INSERT Statement  The formal syntax INSERT INTO table_name (column [ , column] …) VALUES (value [, value] …)  For example INSERT INTO Books VALUES('11111', 'J2ME on Symbian OS', 'Sam', 40); 16
  • 17. SELECT Statement  The formal syntax SELECT [table.]column [ , [table].column] … FROM table [ , table] … [WHERE [table.]column OPERATOR VALUE [AND] OR [table.]column OPERATOR VALUE … [ORDER BY [table.]column [DESC] [ ,[table.]column [DESC}]  For example SELECT * FROM Books WHERE ISBN = '11111'; 17
  • 18. DELETE Statement  The formal syntax DELETE FROM table_name WHERE column OPERATOR value [AND | OR column OPERATOR value ] …  For example DELETE FROM Book WHERE ISBN = '11111'; 18
  • 19. Steps of Using JDBC 1. Load DB-specific JDBC driver 2. Get a Connection object 3. Get a Statement object 4. Execute queries and/or updates 5. Read results 6. Read Meta-data (optional step) 7. Close Statement and Connection objects 19
  • 20. 1. Load DB-Specific Database Driver  To manually load the database driver and register it with the DriverManager, load its class file – Class.forName(<database-driver>) try { // This loads an instance of the Pointbase DB Driver. // The driver has to be in the classpath. Class.forName("com.mysql.jdbc.Driver"); }catch (ClassNotFoundException cnfe){ System.out.println("" + cnfe); } 20
  • 21. 2. Get a Connection Object  DriverManager class is responsible for selecting the database and and creating the database connection  Using DataSource is a prefered means of getting a conection object  Create the database connection as follows: try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); } catch(SQLException sqle) { System.out.println("" + sqle); } 21
  • 22. DriverManager & Connection  java.sql.DriverManager • getConnection(String url, String user, String password) throws SQLException  java.sql.Connection • Statement createStatement() throws SQLException • void close() throws SQLException • void setAutoCommit(boolean b) throws SQLException • void commit() throws SQLException • void rollback() throws SQLException 22
  • 23. Sub-Topics  DataSource interface and DataSource object  Properties of a DataSource object  JNDI registration of a DataSource object  DataSource object that implements Connection pooling 23
  • 24. javax.sql.DataSource Interface and DataSource Object  Driver vendor implements the interface  DataSource object is the factory for creating database connections 24
  • 25. Properties of DataSource Object  A DataSource object has properties that can be modified when necessary – these are defined in a container's configuration file  location of the database server  name of the database  network protocol to use to communicate with the server  The benefit is that because the data source's properties can be changed, any code accessing that data source does not need to be changed  In the GlassFish Application Server, a data source is called a JDBC resource 25
  • 26. JNDI Registration of a DataSource (JDBC Resource) Object  The JNDI name of a JDBC resource is expected in the java:comp/env/jdbc subcontext  For example, the JNDI name for the resource of a BookDB database could be java:comp/env/jdbc/BookDB  Because all resource JNDI names are in the java:comp/env subcontext, when you specify the JNDI name of a JDBC resource enter only jdbc/name. For example, for a payroll database, specify jdbc/BookDB 26
  • 27. Why Connection Pooling?  Database connection is an expensive and limited resource  Using connection pooling, a smaller number of connections are shared by a larger number of clients  Creating and destroying database connections are expensive operations  Using connection pooling, a set of connections are pre- created and are available as needed basis cutting down on the overhead of creating and destroying database connections 27
  • 28. Connection Pooling & DataSource  DataSource objects that implement connection pooling also produce a connection to the particular data source that the DataSource class represents  The connection object that the getConnection method returns is a handle to a PooledConnection object rather than being a physical connection  The application code works the same way 28
  • 29. 3. Get a Statement Object  Create a Statement Object from Connection object • java.sql.Statement – ResultSet executeQuery(string sql) – int executeUpdate(String sql) • Example: Statement statement = connection.createStatement();  The same Statement object can be used for many, unrelated queries 29
  • 30. 4. Executing Query or Update  From the Statement object, the 2 most used commands are – (a) QUERY (SELECT) • ResultSet rs = statement.executeQuery("select * from customer_tbl"); – (b) ACTION COMMAND (UPDATE/DELETE) • int iReturnValue = statement.executeUpdate("update manufacture_tbl set name = ‘IBM' where mfr_num = 19985678"); 30
  • 31. 5. Reading Results  Loop through ResultSet retrieving information  java.sql.ResultSet  boolean next()  xxx getXxx(int columnNumber)  xxx getXxx(String columnName)  void close()  The iterator is initialized to a position before the first row – You must call next() once to move it to the first row 31
  • 32. 5. Reading Results (cont.)  Once you have the ResultSet, you can easily retrieve the data by looping through it while (rs.next()){ // Wrong this will generate an error String value0 = rs.getString(0); // Correct! String value1 = rs.getString(1); int value2 = rs.getInt(2); int value3 = rs.getInt(“ADDR_LN1"); } 32
  • 33. 5. Reading Results (cont.)  When retrieving data from the ResultSet, use the appropriate getXXX() method • getString() • getInt() • getDouble() • getObject()  Thereis an appropriate getXXX method of each java.sql.Types datatype 33
  • 34. 6. Read ResultSet MetaData and DatabaseMetaData (Optional)  Once you have the ResultSet or Connection objects, you can obtain the Meta Data about the database or the query  This gives valuable information about the data that you are retrieving or the database that you are using – DatabaseMetaData dbmd = connection.getMetaData(); – ResultSetMetaData rsMeta = rs.getMetaData(); • There are approximately 150 methods in the DatabaseMetaData class. 34
  • 35. Example public void showDBInfo() {{ public void showDBInfo() try {{ try DatabaseMetaData dbmd == connection.getMetaData(); DatabaseMetaData dbmd connection.getMetaData(); System.out.println("Product: "" ++ dbmd.getDatabaseProductName()); System.out.println("Product: dbmd.getDatabaseProductName()); System.out.println("Version: "" ++ dbmd.getDatabaseProductVersion()); System.out.println("Version: dbmd.getDatabaseProductVersion()); System.out.println ("Stored Procedures: "" ++ System.out.println ("Stored Procedures: dbmd.supportsStoredProcedures()); dbmd.supportsStoredProcedures()); System.out.println("Transactions: "" ++ System.out.println("Transactions: dbmd.supportsTransactions()); dbmd.supportsTransactions()); }} catch (SQLException ex) {{ catch (SQLException ex) ex.getMessage(); ex.getMessage(); }} }} 35
  • 36. ResultSetMetaData Example ResultSetMetaData meta = rs.getMetaData(); //Return the column count int iColumnCount = meta.getColumnCount(); for (int i =1 ; i <= iColumnCount ; i++){ System.out.println(“Column Name: " + meta.getColumnName(i)); System.out.println(“Column Type" + meta.getColumnType(i)); System.out.println("Display Size: " + meta.getColumnDisplaySize(i) ); System.out.println("Precision: " + meta.getPrecision(i)); System.out.println(“Scale: " + meta.getScale(i) ); } 36
  • 37. What Are They?  PreparedStatement • SQL is sent to the database and compiled or prepared beforehand  CallableStatement • Executes SQL Stored Procedures 37
  • 38. PreparedStatement Interface  To call the same SQL statement multiple times, use a PrepareStatement object.  Extend PreparedStatement from Statement class.  public interface PreparedStatement extends Statement  Advantage  Using Statement needs to compile every times.  PreparedStatement will compile only once. 38
  • 39. Example public void insertData() {{ public void insertData() PreparedStatement pstmt; PreparedStatement pstmt; String insertCmd == "INSERT INTO Book VALUES(?,?,?,?)"; String insertCmd "INSERT INTO Book VALUES(?,?,?,?)"; try {{ try pstmt == connection.prepareStatement(insertCmd); pstmt connection.prepareStatement(insertCmd); pstmt.setString(1,"11111"); pstmt.setString(1,"11111"); pstmt.setString(2,"J2ME on Symbian OS"); pstmt.setString(2,"J2ME on Symbian OS"); pstmt.setString(3,"Sam"); pstmt.setString(3,"Sam"); pstmt.setDouble(4,40); pstmt.setDouble(4,40); pstmt.executeUpdate(); pstmt.executeUpdate(); }} catch (SQLException ex) {{ catch (SQLException ex) ex.getMessage(); ex.getMessage(); }} }} 39
  • 40. CallableStatement  The interface used to execute SQL stored procedures  A stored procedure is a group of SQL statements that form a logical unit and perform a particular task  A CallableStatement object contains a call to a stored procedure; it does not contain the stored procedure itself.  The part that is enclosed in curly braces is the escape syntax for stored procedures. CallableStatement cs = connection.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); 40
  • 43. Servlet & JDBC (cont.) 43
  • 44. Why Session Tracking?  Need a mechanism to maintain state across a series of requests from the same user (or originating from the same browser) over some period of time  Example: Online shopping cart  Yet, HTTP is stateless protocol  Each time, a client talks to a web server, it opens a new connection  Server does not automatically maintains “conversational state” of a user 44
  • 45. Session Tracking Use Cases  When clients at an on- line store add an item to their shopping cart, how does the server know what’s already in the cart?  When clients decide to proceed to checkout, how can the server determine which previously created shopping cart is theirs? 45
  • 46. A Session Maintains Client Identity and State across multiple HTTP requests Client 1 server Session 1 Session ID 1 Client 2 Session ID 2 Session 2 46
  • 47. Three “underlying” Session Tracking Mechanisms  Cookies  URL rewriting  Hidden form fields  Note that these are just underlying mechanisms of passing “session id”  do not provide high-level programming APIs  do not provide a framework for managing sessions  This is what Servlet Session Tracking feature provides 47
  • 48. What is HTTP Cookie?  Cookie is a small amount of information sent by a servlet to a Web browser  Saved by the browser, and later sent back to the server in subsequent requests  A cookie has a name, a single value, and optional attributes  A cookie's value can uniquely identify a client  Server uses cookie's value to extract information about the session from some location on the server 48
  • 50. Cookies as Session Tracking Mechanism  Advantages:  Very easy to implement  Highly customizable  Persist across browser shut-downs  Disadvantages:  Often: users turn off cookies for privacy or security reason  Not quite universal browser support 50
  • 51. URL Rewriting  URLs can be rewritten or encoded to include session information.  URL rewriting usually includes a session id  Example: http://localhost:8080/bookstore1/cashier;jsessionid =c0o7fszeb1 51
  • 52. URL Rewriting as Session Tracking Mechanism  Advantages:  Letuser remain anonymous  They are universally supported(most styles)  Disadvantages:  Tediousto rewrite all URLs  Only works for dynamically created documents 52
  • 53. If Cookie is turned off..  If your application makes use of session objects  you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies  by calling the response's encodeURL(URL) method on all URLs returned by a servlet  This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged 53
  • 54. Example: response.encodeURL() out.println("<strong><a href="" + response.encodeURL(request.getContextPath() + "/cashier") + ""></a></strong>");  If cookies are turned off  http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1  If cookies are turned on  http://localhost:8080/bookstore1/cashier 54
  • 55. Hidden Form Fields  Hidden form fields do not display in the browser, but can be sent back to the server by submit <INPUT TYPE=”HIDDEN” NAME=”session” VALUE=”...”>  Fields can have identification (session id) or just some thing to remember (occupation)  Servlet reads the fields using req.getParameter() 55
  • 56. Hidden Form Fields as Session Tracking Mechanism  Advantages:  Universally supported.  Allow anonymous users  Disadvantages:  Only works for a sequence of dynamically generated forms.  Breaks down with static documents, emailed documents, bookmarked documents.  No browser shutdowns. 56
  • 57. HttpSession  Toget a user's existing or new session object:  HttpSession session = request.getSession(true);  "true" means the server should create a new session object if necessary  HttpSession is Java interface  Container creates a object of HttpSession type 57
  • 58. Example: Getting HttpSession Object public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ... out = response.getWriter(); ... } } ... 58
  • 59. HttpSession Java Interface  Contains Methods to  View and manipulate information about a session, such as the session identifier, creation time, and last accessed time  Bind objects to sessions, allowing user information to persist across multiple user connections 59
  • 60. HttpSession Methods  getId()  Returns the unique identifier  isNew()  Determines if session is new to client (not page)  getCreationTime()  Returns time at which session was first created  getLastAccessedTime()  Returns time at which the session was last sent from the client  invalidate()  Invalidate the session and unbind all objects associated with it 60
  • 61. Store and Retrieve of Attribute  To stores values:  session.setAttribute("cart", cart);  To retrieves values:  session.getAttribute("cart"); 61
  • 62. Session Timeout  Used when an end-user can leave the browser without actively closing a session  Sessions usually timeout after 30 minutes of inactivity  Product specific  A different timeout may be set by server admin  getMaxInactiveInterval(), setMaxInactiveInterval() methods of HttpSession interface  Gets or sets the amount of time, session should go without access before being invalidated 62
  • 63. Issues with “Stale” Session Objects  The number of “stale” session objects that are in “to be timed out” could be rather large  Example  1000 users with average 2 minutes session time, thus 15000 users during the 30 minutes period  4K bytes of data per session  15000 sessions * 4K -= 60M bytes of session data  This is just for one Web application  Could have an performance impact  Use the data space in Session object with care 63
  • 64. Session Invalidation  Can be used by servlet programmer to end a session proactively  when a user at the browser clicks on “log out” button  when a business logic ends a session (“checkout” page in the example code in the following slide)  public void invalidate()  Expire the session and unbinds all objects with it  Caution  Remember that a session object is shared by multiple servlets/JSP- pages and invalidating it could destroy data that other servlet/JSP- pages are using 64
  • 65. Example: Invalidate a Session public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... scart = (ShoppingCart) session.getAttribute("examples.bookstore.cart"); ... // Clear out shopping cart by invalidating the session session.invalidate(); // set content type header before accessing the Writer response.setContentType("text/html"); out = response.getWriter(); ... } } 65
  • 66. Scope Objects  Enables sharing information among collaborating web components via attributes maintained in Scope objects  Attributes are name/object pairs  Attributes maintained in the Scope objects are accessed with  getAttribute() & setAttribute()  4 Scope objects are defined  Web context, session, request, page 66
  • 67. Four Scope Objects: Accessibility  Web context (ServletContext)  Accessible from Web components within a Web context  Session  Accessible from Web components handling a request that belongs to the session  Request  Accessible from Web components handling the request  Page  Accessible from JSP page that creates the object 67
  • 68. Four Scope Objects: Class  Web context  javax.servlet.ServletContext  Session  javax.servlet.http.HttpSession  Request  javax.servlet.http.HttpServletRequest  Page  javax.servlet.jsp.PageContext 68
  • 69. Session, Application Scope Client 1 server Session 1 Session ID 1 Client 2 Session ID 2 Session 2 Client 1 server application Client 2
  • 70. Session, Request, Page Scope client request response request response Page 1 forward Page 2 Page 3 Page 4 forward Page scope Page scope Page scope Page scope request scope request scope Session scope
  • 72. What is ServletContext For?  Used by servlets to  Set and get context-wide (application-wide) object- valued attributes  Get request dispatcher  To forward to or include web component  Access Web context-wide initialization parameters set in the web.xml file  Access Web resources associated with the Web context  Log  Access other misc. information 72
  • 73. Scope of ServletContext  Context-wide scope  Shared by all servlets and JSP pages within a "web application"  Why it is called “web application scope”  A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace and possibly installed via a *.war file  All servlets in BookStore web application share same ServletContext object  There is one ServletContext object per "web application" per Java Virtual Machine 73
  • 74. Example: Getting Attribute Value from ServletContext public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { // Get context-wide attribute value from // ServletContext object bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } } 74
  • 75. What is Servlet Request?  Contains data passed from client to servlet  All servlet requests implement ServletRequest interface which defines methods for accessing  Client sent parameters  Object-valued attributes  Locales  Client and server  Input stream  Protocol information  Content type  If request is made over secure channel (HTTPS) 75
  • 76. Requests data, client, server, header servlet itself Request Servlet 1 Servlet 2 Response Servlet 3 Web Server 76
  • 77. Servlet Lifecycle Events  Support event notifications for state changes in  ServletContext  Startup/shutdown  Attribute changes  HttpSession  Creationand invalidation  Changes in attributes 77
  • 78. Listener Interfaces  ServletContextListener  contextInitialized/Destroyed(ServletContextEvent)  ServletContextAttributeListener  attributeAdded/Removed/Replaced(ServletContextAttributeEvent)  HttpSessionListener  sessionCreated/Destroyed(HttpSessionEvent)  HttpSessionAttributeListener  attributedAdded/Removed/Replaced(HttpSessionBindingEvent)  HttpSessionActivationListener  Handles sessions migrate from one server to another  sessionWillPassivate(HttpSessionEvent)  sessionDidActivate(HttpSessionEvent) 78
  • 79. Listener Registration  Web container  creates an instance of each listener class  registers it for event notifications before processing first request by the application  Registers the listener instances according to  the interfaces they implement  the order in which they appear in the deployment descriptor web.xml  Listeners are invoked in the order of their registration during execution 79
  • 80. Steps for Implementing Servlet Lifecycle Event 1. Decide which scope object you want to receive an event notification 2. Implement appropriate interface 3. Override methods that need to respond to the events of interest 4. Obtain access to important Web application objects and use them 5. Configure web.xml accordingly 6. Provide any needed initialization parameters 80
  • 81. Example: Context Listener public final class ContextListener implements ServletContextListener { private ServletContext context = null; public void contextInitialized(ServletContextEvent event) { context = event.getServletContext(); try { BookDB bookDB = new BookDB(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { context.log("Couldn't create bookstore database bean: " + ex.getMessage()); } Counter counter = new Counter(); context.setAttribute("hitCounter", counter); counter = new Counter(); context.setAttribute("orderCounter", counter); } 81
  • 82. Example: Context Listener public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDB bookDB =(BookDB)context.getAttribute("bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); } } 82
  • 83. Listener Configuration <web-app> <display-name>Bookstore1</display-name> <description>no description</description> <filter>..</filter> <filter-mapping>..</filter-mapping> <listener> <listener-class>listeners.ContextListener</listener-class> </listener> <servlet>..</servlet> <servlet-mapping>..</servlet-mapping> <session-config>..</session-config> <error-page>..</error-page> ... </web-app> 83
  • 84. What are Java Servlet Filters?  New component framework for intercepting and modifying requests and responses  Filters can be chained and plugged in to the system during deployment time  Allows range of custom activities:  Marking access, blocking access  Caching, compression, logging  Authentication, access control, encryption  Introduced in Servlet 2.3 (Tomcat 4.0)  Content transformations 84
  • 85. What Can a Filter Do?  Examine the request headers  Customize the request object if it wishes to modify request headers or data  Customize the response object if it wishes to modify response headers or data  Invoke the next entity in the filter chain  Examine response headers after it has invoked the next filter in the chain  Throw an exception to indicate an error in processing 85
  • 86. How Servlet Filter Work? Servlet Servlet Container Filter Chain Filter 1 Filter 2 Filter N doFilter( User Servlet service( ServletRequest, implemented container ServletRequest, filters filter ServletResponse, FilterChain) ServletResponse) 86
  • 87. javax.servlet.Filter Interface  init(FilterConfig)  called only once when the filter is first initialized  get ServletContext object from FilterConfig object and save it somewhere so that doFilter() method can access it  read filter initialization parameters from FilterConfig object through getInitParameter() method  destroy()  called only once when container removes filter object  close files or database connections 87
  • 88. How Filter Chain Works  Multiple filters can be chained  order is dictated by the order of <filter> elements in the web.xml deployment descriptor  The first filter of the filter chain is invoked by the container  via doFilter(ServletRequest req, ServletResponse res, FilterChain chain)  the filter then perform whatever filter logic and then call the next filter in the chain by calling chain.doFilter(..) method  The last filter's call to chain.doFilter() ends up calling service() method of the Servlet 88
  • 89. Steps for Building a Servlet Filter  Decide what custom filtering behavior you want to implement for a web resource  Create a class that implements Filter interface  Implement filtering logic in the doFilter() method  Call the doFilter() method of FilterChain object  Configure the filter with Target servlets and JSP pages  use <filter> and <filter-mapping> elements 89
  • 90. Example: HitCounterFilter public final class HitCounterFilter implements Filter { private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy() { this.filterConfig = null; } // Continued in the next page... 90
  • 91. Example: HitCounterFilter public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Counter counter = (Counter) filterConfig.getServletContext().getAttribute("hitCounter"); writer.println("The number of hits is: " + counter.incCounter()); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); ... chain.doFilter(request, wrapper); ... } } 91
  • 92. HitCounterFilter Configuration <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'> <web-app> <display-name>Bookstore1</display-name> <description>no description</description> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>filters.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter-name>HitCounterFilter</filter-name> <url-pattern>/enter</url-pattern> </filter-mapping> ... 92
  • 93. Configuration in web.xml  <filter>  <filter-name>: assigns a name of your choosing to the filter  <filter-class>: used by the container to identify the filter class  </filter>  <filter-mapping>  <filter-name>: assigns a name of your choosing to the filter  <url-pattern>: declares a pattern URLs (Web resources) to which the filter applies  </filter-mapping> 93
  • 94. Concurrency Issues on a Servlet  The service() method of a servlet instance can be invoked by multiple clients (multiple threads)  Servlet programmer has to deal with concurrency issue  shared data needs to be protected  this is called “servlet synchronization”  use of synchronized block 94
  • 95. Many Threads, One Servlet Instance Web Server request thread request thread request thread Servlet thread request thread request Servlet container 95
  • 96. Use of synchronized block  Synchronized blocks are used to guarantee only one thread at a time can execute within a section of code synchronized(this) { myNumber = counter + 1; counter = myNumber; } ... synchronized(this) { counter = counter + 1 ; } 96
  • 97. Thank you thananum@gmail.com www.facebook.com/imcinstitute www.imcinstitute.com 97