adv_java1

download adv_java1

of 281

Transcript of adv_java1

  • 8/8/2019 adv_java1

    1/281

    Page 1Presentation Name HTC Confidential

    J2EE Training

  • 8/8/2019 adv_java1

    2/281

    Page 2Presentation Name HTC Confidential

    3.Advanced-Java Contents -1

    3.1.JDBC

    3.2.Servlets & JSP

    3.3.Tag Libraries

    3.4.Struts 3.5.Struts-Tag Libraries 3.6.JSTL

    3.7.XML

    3.8.Junit 3.9.Ant

  • 8/8/2019 adv_java1

    3/281

    Page 3Presentation Name HTC Confidential

    3.1.JDBC

    JDBC indicates Java Database Connectivity

    The java.sql package makes it possible to connect to arelational database, send SQL commands to the database,process the returned results and invoke stored procedures

    JDBC is database independent, so that the same codeworks with all databases vix. Sybase, Oracle, DB2,Informix...

  • 8/8/2019 adv_java1

    4/281

    Page 4Presentation Name HTC Confidential

    3.1.JDBC

    JDBC Drivers To Connect to any database, we need to load (register)

    programs called Drivers to interact with that particulardatabase :

    Class.forName( JDBCDriver );

    The following are types of JDBC drivers : Type 1 :- JDBC-ODBC Bridge

    Provides JDBC access via ODBC Drivers

    Type 2 :- Native API Driver

    This kind of driver converts JDBC calls into callson the client API for Oracle, Sybase, Informix,DB2, or other DBMS

  • 8/8/2019 adv_java1

    5/281

    Page 5Presentation Name HTC Confidential

    3.1.JDBC

    JDBC Drivers The following are types of JDBC drivers :

    Type 3 :- JDBC-Net Driver

    This driver translates JDBC calls into a DBMS-independent net protocol which is thentranslated to a DBMS protocol by a server. Thisnet server middleware is able to connect itspure Java clients to many different databases

    Type 4 :- Native protocol Driver

    This kind of driver converts JDBC calls into thenetwork protocol used by DBMSs directly. Thisallows a direct call from the client machine tothe DBMS server

  • 8/8/2019 adv_java1

    6/281

    Page 6Presentation Name HTC Confidential

    3.1.JDBC

    Connection A Connection object represents a connection with a

    database.

    A connection session includes the SQL statements that

    are executed and the results that are returned overthat connection.

    A single application can have one or more connectionswith a single database, or it can have connections withmany different databases.

  • 8/8/2019 adv_java1

    7/281

    Page 7Presentation Name HTC Confidential

    3.1.JDBC

    Connection The standard way to establish a connection with a

    database is to call :DriverManager.getConnection( JDBCURL

    [, ,]);

    This method takes a string containing a JDBC URL andan optional User ID/ Password (for those databaseswhich require them).

    A JDBC URL provides a way of identifying a databaseso that the appropriate driver will recognize it andestablish a connection

  • 8/8/2019 adv_java1

    8/281

    Page 8Presentation Name HTC Confidential

    3.1.JDBC

    Connection Since JDBC URLs are used with various kinds of

    drivers, the conventions are of necessity very flexible

    The JDBC URL may refer to a logical host or database

    name that is translated to the actual name by anetwork naming system

    The standard syntax for JDBC URLs is shown below. Ithas three parts, which are separated by colons:

    jdbc::

  • 8/8/2019 adv_java1

    9/281

    Page 9Presentation Name HTC Confidential

    3.1.JDBC

    Connection The JDBC URL is broken down as follows:

    jdbc

    The protocol. The protocol in a JDBC URL is jdbc.

    The name of the driver or the name of a databaseconnectivity mechanism

    A way to identify the database. The subname can vary,depending on the subprotocol, and it can have any syntaxthe driver writer chooses.

    jdbc:odbc:wombat (where wombat is the DSN)

    jdbc:oracle:thin:@taz:1521:ops001

  • 8/8/2019 adv_java1

    10/281

    Page 10Presentation Name HTC Confidential

    3.1.JDBC

    Connection The DriverManager class is referred to as the JDBC

    management layer

    The DriverManager class maintains a list of registeredDriver classes, and when the method getConnection is

    called, it checks with each driver in the list until it findsone that can connect to the database specified in theURL.

    The Driver method connect( ) uses this URL to actually

    establish the connection.

  • 8/8/2019 adv_java1

    11/281

    Page 11Presentation Name HTC Confidential

    3.1.JDBC

    Statements Once a connection is established, it is used to pass

    SQL statements to its underlying database.

    JDBC does not put any restrictions on the kinds of SQL

    statements that can be sent; this provides a great dealof flexibility

    JDBC provides three classes for sending SQLstatements to the database viz. Statement,PreparedStatement and CallableStatement.

  • 8/8/2019 adv_java1

    12/281

    Page 12Presentation Name HTC Confidential

    3.1.JDBC

    Statements :-- Statement

    A Statement object is used for sending simpleSQL statements.

    PreparedStatement A PreparedStatement object is used for SQL

    statements that take one or more parameters asinput arguments (IN parameters).

    CallableStatement A CallableStatement object is used to execute

    SQL stored procedures

  • 8/8/2019 adv_java1

    13/281

    Page 13Presentation Name HTC Confidential

    3.1.JDBC

    Statement Created by the method createStatement( ) of the

    Connection interface.Statement stm = con.createStatement( );

    Key Methods

    executeQuery( )

    Is used for statements that produce a singleresult set, such as SELECT statements

    executeUpdate( )

    Is used to execute INSERT, UPDATE, or DELETEstatements and also SQL DDL (Data DefinitionLanguage) statements like CREATE TABLE andDROP TABLE

  • 8/8/2019 adv_java1

    14/281

    Page 14Presentation Name HTC Confidential

    3.1.JDBC

    Statement Key Methods

    execute( )

    Is used to execute statements that return more than oneresult set, more than one update count, or a combination

    of the two close( )

    Releases this Statement object's database and JDBCresources immediately instead of waiting for this tohappen when it is automatically closed

    setMaxRows( )

    Sets the limit for the maximum number of rows that anyresult set can contain

  • 8/8/2019 adv_java1

    15/281

    Page 15Presentation Name HTC Confidential

    3.1.JDBC

    Transactions A transaction consists of SQL statement(s) that have

    been executed, completed, and then either committedor rolled back.

    The method commit( ) of the Connection interfacemakes permanent any changes an SQL statementmakes to a database. The method rollback( ) willdiscard those changes.

    When the method commit( ) or rollback( ) is called, thecurrent transaction ends.

  • 8/8/2019 adv_java1

    16/281

    Page 16Presentation Name HTC Confidential

    3.1.JDBC

    Transactions A new connection is in auto-commit mode by default,

    meaning that when a statement is completed, themethod commit( ) will be called on that statement

    automatically. In this case, since each statement is committedindividually, a transaction consists of only onestatement.

    If auto-commit mode has been disabled, a transactionwill not terminate until explicitly the commit( ) orrollback( ) is called.

  • 8/8/2019 adv_java1

    17/281

    Page 17Presentation Name HTC Confidential

    3.1.JDBC

    ResultSet A ResultSet contains all of the rows which satisfied the

    conditions in an SQL statement, and it provides accessto the data in those rows through a set of get methods

    that allow access to the various columns of the currentrow.

    The ResultSet.next( ) method is used to move to thenext row of the ResultSet, making the next rowbecome the current row.

  • 8/8/2019 adv_java1

    18/281

    Page 18Presentation Name HTC Confidential

    3.1.JDBC

    ResultSet The general form of a result set is a table with column

    headings and the corresponding values returned by aquery

    The getXXX( ) methods provide the means forretrieving column values from the current row in aResultSet

    Either the column name or the column number can beused to designate the column from which to retrievedata.

  • 8/8/2019 adv_java1

    19/281

    Page 19Presentation Name HTC Confidential

    3.1.JDBC

    ResultSet For example, if the second column of a ResultSet

    object is named title, to retrieve the value stored inthat column, use:

    String s = rs.getString("title"); (or)String s = rs.getString(2);

    Methods such as getString, getBigDecimal, getBytes,getDate, getTime, getTimestamp, getObject, getByte,getShort, getInt, getLong, getFloat, getDouble and

    getBoolean are available in the ResultSet to receive thedata in the appropriate type.

  • 8/8/2019 adv_java1

    20/281

    Page 20Presentation Name HTC Confidential

    3.1.JDBC

    ResultSet Information about the columns in a ResultSet is

    available by calling the method getMetaData( ).

    The ResultSetMetaData object returned gives the

    number, types, and properties of its ResultSet object'scolumns.

    To get the column names and type :ResultSetMetaData rsm = rs.getMetaData( );

    for (int I =1; I < rsm.getColumnCount( ); I++)

    System.out.println(Column : + rsm.getColumnName(I) +is of Type : + rsm.getColumnTypeName(I));

  • 8/8/2019 adv_java1

    21/281

    Page 21Presentation Name HTC Confidential

    3.1.JDBC

    Sample code to Select data :import java.sql.*;

    public class TestJDBC {

    public static void main(String args[ ]) {

    try {

    // Load the JDBC Driver

    Class.forName(oracle.jdbc.driver.OracleDriver);

    } catch(ClassNotFoundException e) {

    System.out.println(Error loading Driver : +e.toString( ));

    }

    Connection con = null;

    Statement stm = null;Resultset rs = null; // Contd...

  • 8/8/2019 adv_java1

    22/281

    Page 22Presentation Name HTC Confidential

    3.1.JDBC

    try {// Get a connection to the Database

    con = DriverManager.getConnection(jdbc:oracle:thin:@taz:1521:ops001, trng , trng);

    // Create a statement

    stm=con.createStatement( );

    // Execute an SQL Select statement

    rs = stm.executeQuery(select ENO, ENAME from EMP);

    if (rs == null)

    System.out.println(No Data Found);

    // Iterate through the Resultset to get Data

    while (rs.next( )) {

    System.out.println(Employee : + rs.getString(ENO) + - + rs.getString(ENAME));

    } // Contd...

  • 8/8/2019 adv_java1

    23/281

    Page 23Presentation Name HTC Confidential

    3.1.JDBC

    } catch(SQLException e) {System.out.println( JDBC Error : + e.getMessage( ));

    } finally { // Close Resultset, Statement and Connection

    try {

    if (rs != null) rs.close( );

    } catch(SQLException e) { }

    try {

    if (stm != null) stm.close( );

    } catch(SQLException e) { }

    try {

    if (con != null) con.close( );

    } catch(SQLException e) { }

    }

    }

    }

  • 8/8/2019 adv_java1

    24/281

    Page 24Presentation Name HTC Confidential

    3.1.JDBC

    Sample code to Insert data :import java.sql.*;

    public class TestJDBC {

    public static void main(String args[ ]) {

    try {

    // Load the JDBC Driver

    Class.forName(oracle.jdbc.driver.OracleDriver);

    } catch(ClassNotFoundException e) {

    System.out.println(Error loading Driver : +e.toString( ));

    }

    Connection con = null;

    Statement stm = null; // Contd...

  • 8/8/2019 adv_java1

    25/281

    Page 25Presentation Name HTC Confidential

    3.1.JDBC

    try {// Get a connection to the Database

    con = DriverManager.getConnection(jdbc:oracle:thin:@taz:1521:ops001, trng , trng);

    // Create a statement

    stm=con.createStatement( );

    // Execute an SQL DML Statement

    int returnStat = stm.executeUpdate(insert into EMP(ENO, ENAME ) values ( 1234, SHIVA ));

    System.out.println(Inserted with return status : + returnStat);

    // Contd...

  • 8/8/2019 adv_java1

    26/281

    Page 26Presentation Name HTC Confidential

    3.1.JDBC

    } catch(SQLException e) {System.out.println( JDBC Error : + e.getMessage( ));

    } finally { // Close Resultset, Statement and Connection

    try {

    if (rs != null) rs.close( );

    } catch(SQLException e) { }

    try {

    if (stm != null) stm.close( );

    } catch(SQLException e) { }

    try {

    if (con != null) con.close( );

    } catch(SQLException e) { }

    }

    }

    }

  • 8/8/2019 adv_java1

    27/281

    Page 27Presentation Name HTC Confidential

    3.1.JDBC

    PreparedStatement

    A PreparedStatement is more efficient than aStatement object because it has been pre-compiledand stored for future use.

    A PreparedStatement object is used for SQL

    statements that take one or more parameters as inputarguments (IN parameters) and those SQL statementsthat need to be executed repeatedly.

    Instances of PreparedStatement extend Statement and

    include Statement methods.

  • 8/8/2019 adv_java1

    28/281

    Page 28Presentation Name HTC Confidential

    3.1.JDBC

    PreparedS

    tatement Created by the prepareStatement( ) method of theConnection interface.

    PreparedStatement pstmt =con.prepareStatement (insert into EMP(ENO , ENAME) values ( ? , ? ));

    An IN parameter is the one whose value is notspecified when the SQL statement is created, insteadthe question mark ("?") acts as a placeholder for IN

    parameters. A value for each question mark must be supplied by

    the appropriate setXXX method before the statement isexecuted.

  • 8/8/2019 adv_java1

    29/281

    Page 29Presentation Name HTC Confidential

    3.1.JDBC

    PreparedStatement Once a parameter value has been set for a given statement, it can

    be used for multiple executions of that statement.

    For example, the following inserts 4 rows

    PreparedStatement pstmt = con.prepareStatement( insertinto EMP (ENO , ENAME) values ( ? , ? ));

    pstmt.setString(2, Shiva); //Constant parameter

    for (int i= 1; i < 5; i++) {

    pstmt.setInt(1, i); //Dynamic parameter

    int status = pstmt.executeUpdate( );

    }

  • 8/8/2019 adv_java1

    30/281

    Page 30Presentation Name HTC Confidential

    3.1.JDBC

    CallableStatement CallableStatement objects are used to execute SQL

    stored procedures

    A CallableStatement object inherits methods for

    handling IN parameters from PreparedStatement itadds methods for handling OUT and INOUTparameters.

    The syntax for invoking a stored procedure in JDBC isshown below :

    {call procedure_name(?, ?, ...)}

    CallableStatement cstmt = con.prepareCall({call getTestData(?, ?)} );

  • 8/8/2019 adv_java1

    31/281

    Page 31Presentation Name HTC Confidential

    3.1.JDBC

    CallableStatement Passing in any IN parameter values to a

    CallableStatement object is done using the setXXXmethods as in PreparedStatement.

    The JDBC type of each OUT parameter must beregistered before the CallableStatement object can beexecuted using the method registerOutParameter.

    After the statement has been executed,CallableStatement's getXXX methods are used toretrieve the parameter value

  • 8/8/2019 adv_java1

    32/281

    Page 32Presentation Name HTC Confidential

    3.1.JDBC

    CallableS

    tatement The following code executes a Stored Procedure,passes an IN parameter and retrieves two OUTparameters :

    CallableStatement cstmt = con.prepareCall(

    {call getTestData(?, ? , ?)});cstmt.setInt(1, 25);

    cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);

    cstmt.registerOutParameter(3, java.sql.Types.DECIMAL,3);

    cstmt.executeUpdate( );

    String s = cstmt.getString(2);

    java.math.BigDecimal n = cstmt.getBigDecimal(3, 3);

  • 8/8/2019 adv_java1

    33/281

    Page 33Presentation Name HTC Confidential

    3.1.JDBC

    In JDBC 2.0 we can get ResultSets that allowusers to scroll in both directions.

    This is achieved through using II nd or IV th typeof drivers like

    oracle.jdbc.driver.OracleDriver class object withurl jdbc:oracle:oci (oracle9 II nd type) orjdbc:oracle:thin:@hostname:1521:sid (oracle9 IVth) then using special createStatement() method

    This ResultSet has methods likeprevious(),last(),first(),beforFirst(),afterLast(),absolute(int),relative(int) for navigation

  • 8/8/2019 adv_java1

    34/281

    Page 34Presentation Name HTC Confidential

    3.Advanced-Java Contents -1

    3.1.JDBC

    3.2.Servlets & JSP

    3.3.Tag Libraries

    3.4.Struts 3.5.Struts-Tag Libraries 3.6.JSTL

    3.7.XML

    3.8.Junit 3.9.Ant

  • 8/8/2019 adv_java1

    35/281

    Page 35Presentation Name HTC Confidential

    3.2.Servlets

    -3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy

    3.2.5.HTTP Servlet- Session Management

    3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access

    3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    36/281

    Page 36Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    Servlets are server-side Java programs

    extend the functionality of WEB Servers

    are to WEB Servers what Applets are to WEB Browsers

    are Request/Response oriented are Platform / WEB Server independent

  • 8/8/2019 adv_java1

    37/281

    Page 37Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    Servlets are initialized and loaded only once

    are Multi-Threaded to handle multiple concurrent clientrequests

    are not tied any particular protocol, but, are most

    commonly used with HTTP manage state information on top of the stateless HTTP

    are run by a Servlet Engine in a restrictiveSandbox(servlet container) for hacker prevention

  • 8/8/2019 adv_java1

    38/281

    Page 38Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    Servlets are used in the following cases processing the data captured in a HTML Form and

    updating a database

    retrieving data from a database and dynamically

    generating HTML pages applications that requires state management like

    shopping carts...

    on-line conferencing and Chat applications

    communicating with other Servers accessing existing Business systems

    In MVC2 architecture,they are visualized as controllercomponents

  • 8/8/2019 adv_java1

    39/281

    Page 39Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    Why Servlets ? servlets are light-weight i.e. can run in the same

    server process as the WEB server

    servlets support a higher user load with less machine

    resources servlets can be loaded from anywhere i.e.Local File

    system / Remote Web site

    servlets deliver faster on-line response as dont fork anew process for each request

    Servlets can easily acess java api like JDBC, EJB, JMS,JavaMail, JavaIDL, RMI, or third-party Java technology

    These are easily compatiable with most of web-servers

  • 8/8/2019 adv_java1

    40/281

    Page 40Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    WEB Servers supporting Servlets: Apache

    Netscape Enterprise Server

    IBM WebSphere

    Lotus Domino GO Tandem iTP

    Weblogic

    Paralogic WebCore

    And MORE

  • 8/8/2019 adv_java1

    41/281

    Page 41Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    Engines for Existing Servers: ServletExec

    for IIS, Netscape, all Mac OS Servers

    Jrun

    for IIS, Netscape, Apache, WebSite Pro, WebSTAR WAICoolRunner

    for Netscape

  • 8/8/2019 adv_java1

    42/281

    Page 42Presentation Name HTC Confidential

    3.2.1.Introduction to Servlets

    All Servlets implement the interfacejavax.servlet.Servlet

    Most Servlets extend one of the following 2standard implementations:

    javax.servlet.GenericServlet

    javax.servlet.http.HttpServlet

    WEB applications use HTTP Servlets

    HTTP Servlets extend Generic Servlet

  • 8/8/2019 adv_java1

    43/281

    Page 43Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy 3.2.5.HTTP Servlet- Session Management

    3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file 3.2.9.servlet resource-access

    3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    44/281

    Page 44Presentation Name HTC Confidential

    3.2.2.Life Cycle of Servlets

    Servlets are initialized via an init( ) method at thetime of Instantiation

    The init( ) method is called only once during thelifecycle of the Servlet, so, it need not be written

    as Thread-Safe The init( ) method is used for

    Storing its Configuration parameters

    Initializing the values of Servlet members

    Loading JDBC Database Drivers

  • 8/8/2019 adv_java1

    45/281

    Page 45Presentation Name HTC Confidential

    3.2.2.Life Cycle of Servlets

    After initialization, its service( ) method is calledfor every request to the Servlet

    The service( ) method is called concurrently (i.e.multiple threads may call this method at the

    same time) The service( ) method should be implemented in

    a Thread-safe manner

    The service( ) method usually contains the bulkof the business logic

  • 8/8/2019 adv_java1

    46/281

    Page 46Presentation Name HTC Confidential

    3.2.2.Life Cycle of Servlets

    Servlets run until they are removed from theservice (Un-loading / Shutting down)

    The destroy( ) method is invoked for performingclean up activities

    The destroy( ) method is called only once, but,since other threads might be running service( )methods when destroy( ) is invoked, it needs to

    be implemented in a Thread-

    Safe manner

  • 8/8/2019 adv_java1

    47/281

    Page 47Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy 3.2.5.HTTP Servlet- Session Management

    3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet Cookies

    3.2.8.servlet-info in web configuration file 3.2.9.servlet resource-access

    3.2.9.1.filter,filter-mappings

    3 2 3 S l S l

  • 8/8/2019 adv_java1

    48/281

    Page 48Presentation Name HTC Confidential

    3.2.3.A Sample HTTP Servlet

    A client makes a Request to a server The request is resolved to a HTTP Servlet by the

    Servlet Engine

    The HTTP Servlet receive relevant inputs fromthe WEB Browser (all the HTML Form elementsand their values)

    HTTP Servlets responds a HTML Page back to the

    Browser

    3 2 3 A S l HTTP S l

  • 8/8/2019 adv_java1

    49/281

    Page 49Presentation Name HTC Confidential

    3.2.3.A Sample HTTP Servlet

    The following HTML Page accepts your Nameand submits a request to a Servlet named

    HelloWorldServlet present in your PC:

    Enter Your Name :

    3 2 3 A S l HTTP S l t

  • 8/8/2019 adv_java1

    50/281

    Page 50Presentation Name HTC Confidential

    3.2.3.A Sample HTTP Servlet

    The code for HelloWorldServlet.java looks like this:import java.io.*;import javax.servlet.*;

    import javax.servlet.http.*;

    public class HelloWorldServlet extends HttpServlet {

    String companyName;

    public void init( ServletConfig config ) throws ServletException {

    super.init( config );

    companyName = getInitParameter( company );

    if ( companyName == null ) {

    throw new UnavailableException( this,Un-Authorized );

    }

    } //End of init( ) method

    public void destroy( ) {

    companyName = null;

    } //End of Destroy( ) method

    3 2 3 A S l HTTP S l t

  • 8/8/2019 adv_java1

    51/281

    Page 51Presentation Name HTC Confidential

    3.2.3.A Sample HTTP Servlet

    protected void doGet( HttpServletRequest req,HttpServletResponse res )

    throws ServletException, IOException {

    res.setContentType( text/html );

    PrintWriter out = res.getWriter( );

    out.println( Hello World!! +By + req.getParameter( USER ) +

    of + companyName +

    );

    out.close( );

    } //End of service( ) method

    } // End of Hello World Servlet

    3 2 S l t

  • 8/8/2019 adv_java1

    52/281

    Page 52Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet - Anatomy

    3.2.5.HTTP Servlet- Session Management 3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access 3.2.9.1.filter,filter-mappings

    3 2 4 HTTP S l t A t

  • 8/8/2019 adv_java1

    53/281

    Page 53Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- Import Lines 1 to 3 import packages which contain classes

    that are used by the Servlet

    import java.io.*;

    import javax.servlet.*;import javax.servlet.http.*;

    javax is an extended Java packages library

    javax.servlet.http contains all classes used by HTTP

    Servlets

    3 2 4 HTTP S l t A t

  • 8/8/2019 adv_java1

    54/281

    Page 54Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- Declaration The Servlet class is declared as extends

    javax.servlet.http.HttpServlet

    public class HelloWorldServlet

    extends HttpServlet This declaration is necessary for Request / Response

    interaction with the WEB Browser using HTTP Protocol

    The HttpServlet is an abstract class which extends

    the GenericServlet class

    3 2 4 HTTP S l t A t

  • 8/8/2019 adv_java1

    55/281

    Page 55Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- init( ) The init( ) method is overridden for the purpose of

    initializing the Servlet

    public void init( ServletConfig config )

    throws ServletException {super.init( config );

    ...

    }

    3 2 4 HTTP Se let Anatom

  • 8/8/2019 adv_java1

    56/281

    Page 56Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- init( ) In init( ) we first call super.init( config ) to leave the

    ServletConfig management to the superclass(HttpServlet)

    If the servlet's required resources can not be madeavailable (a required network connection can not beestablished), or some other initialization error occurs,an UnavailableException is thrown

    The UnavailableException extends ServletException

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    57/281

    Page 57Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- init( ) In this init( ) method, we are getting an Initialization

    parameter called company from the Servletsconfiguration file(web.xml) and assigning its value to a

    member called companyName Version 2.1 of the Servlet API offers an no-args init( )

    method which is called by GenericServlet'sinit(ServletConfig) method

    It is not mandatory to include the init( ), but, is goodpractice to do so

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    58/281

    Page 58Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- destroy( ) The destroy( ) method is overridden for clean-up

    during unloading of Servlets

    public void destroy( ) {

    companyName = null;}

    In this destroy( ) we are marking the Servlet membercalled companyName for garbage collection

    It is not mandatory to include the destroy( ), but isgood practice to do so

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    59/281

    Page 59Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- service( ) The service( ) method is overridden for Request /

    Response interaction with the client browser

    protected void service( HttpServletRequest req,

    HttpServletResponse res )throws ServletException, IOException {

    .

    }

    The service( ) method is invoked by the Servlet Enginefor each client request

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    60/281

    Page 60Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet-

    service( ) A separate Thread is spawned by the Servlet Engine toservice each request

    The service( ) method is invoked implicitly by thecontainer to call either call doGet/doPost that issuitable for the given request

    The doGet( ) and the doPost( ) methods should only tobe used in place of service( ) method wheneversubclasses of HttpServlet are designed

    There 6 methods likedoPut(),doDelete(),doTrace(),doOptions(),doPost(),doGet() matching to the type of http requests,all ofwhich are called service methods

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    61/281

    Page 61Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- service( )

    The service methods have following parameters:

    HttpServletRequest

    for abstracting the request from the client

    provides access to HTTP header data, such as any cookies

    found in the request provides access to all request parameters,attributes as

    name/value pairs

    HttpServletResponse

    for responding HTML pages back to the client

    Contains Handle of the Output Stream / Writer to theClient Browser

    For redirecting to an another URL

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    62/281

    Page 62Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet- service( )

    We are getting the value of a Request parametercalled USER using the getParameter( ) method of the

    HttpServletRequest object

    We are using the above value and thecompanyName obtained from the init( ) method to

    form the Dynamic HTML page as a response

    3 2 4 HTTP Servlet Anatomy

  • 8/8/2019 adv_java1

    63/281

    Page 63Presentation Name HTC Confidential

    3.2.4.HTTP Servlet-Anatomy

    Hello World Servlet doGet() method We are accessing the HTTP Header to set the content

    type of the Response, using the setContentType( )method of the HttpServletResponse object

    For HTTP response, We are getting a PrintWriterObject using the getWriter( ) method of theHttpServletResponse object

    We are using the println( ) method of the PrintWriter

    Object to write HTML information on to the ClientBrowser

    3 2 Servlets

  • 8/8/2019 adv_java1

    64/281

    Page 64Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1

    .Introduction to Servlets 3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy

    3.2.5.HTTP Servlet - Session Management 3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access 3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    65/281

    Page 65Presentation Name HTC Confidential

    3.2.5.HTTP Servlet-Session Management

    Session Management is the process ofmaintaining persistence and State Information

    Session Management is required because HTTP isby default, stateless

    Session Management is easily used for UserAuthentication across requests within the samesession

    Session Management is used for Caching re-usable information

  • 8/8/2019 adv_java1

    66/281

    Page 66Presentation Name HTC Confidential

    3.2.5.HTTP Servlet- Session Management

    A Session consists of An unique Session ID which travels back and forth between the

    Client and the Server. The Session ID is used to map a request toa particular Client Session

    A Session Context area in the Server for storing general and

    application information pertaining to the Client Session In HTTP Servlets, the Session can be maintained and

    tracked by four methods

    cookies

    URL-rewriting Hidden fields

    Session-tracking

  • 8/8/2019 adv_java1

    67/281

    Page 67Presentation Name HTC Confidential

    3.2.5.HTTP Servlet- Session Management

    In session tracking,HttpSession defines methodswhich can extract the following types of data:

    Standard session properties, such as an identifier forthe session, authenticity of the session and the context

    for the session Application layer data stored using a dictionary-like

    interface

    Using getAttribute(),setAttribute() clients specific data

    can be stored or retrieved

  • 8/8/2019 adv_java1

    68/281

    Page 68Presentation Name HTC Confidential

    3.2.5.HTTP Servlet- Session Management

    The following code snippets describeSession authentication and Caching:

    Session Creation (after User Login):HttpSession session = req.getSession( true );

    session.setAttribute( USER , req.getParameter( USER )* );* any value as an object

    Session Authentication (each request):HttpSession session = req.getSession( false );

    if ( ( session == null ) || ( session.isNew( ) ) ) {

    res.sendRedirect( loginURL );

    }

    String userId = session.getAttribute( USER );

    3 2 Servlets

  • 8/8/2019 adv_java1

    69/281

    Page 69Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1

    .Introduction to Servlets 3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy

    3.2.5.HTTP Servlet- Session Management 3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access 3.2.9.1.filter,filter-mappings

    3 2 6 ServletContext and ServletConfig

  • 8/8/2019 adv_java1

    70/281

    Page 70Presentation Name HTC Confidential

    3.2.6.ServletContext and ServletConfig

    The ServletContext and the ServletConfiginterfaces of javax.servlet package are used for

    getting the server environment information

    getting servlets initialization parameters

    passing configuration information to the servlet engine

    logging Events

    accessing a other servlet deployed in the samecontainer

    3 2 6 ServletContext and ServletConfig

  • 8/8/2019 adv_java1

    71/281

    Page 71Presentation Name HTC Confidential

    3.2.6.ServletContext and ServletConfig

    The following code snippet describe externalAccess of a Servlets members:RequestDispatcher rd = this.getServletContext().getRequestDispatcher(/servlet/other );

    rd.forward(request,response);

    first, the ServletContext is obtained from theservlet itself and then a handle to the externalServlet is obtained from this ServletContext asan Object of RequestDispatcher

    3 2 Servlets

  • 8/8/2019 adv_java1

    72/281

    Page 72Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1

    .Introduction to Servlets 3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy

    3.2.5.HTTP Servlet- Session Management 3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet - Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access 3.2.9.1.filter,filter-mappings

    3 2 7 HTTP Servlet - Cookies

  • 8/8/2019 adv_java1

    73/281

    Page 73Presentation Name HTC Confidential

    3.2.7.HTTP Servlet Cookies

    Cookies are very useful in maintaining statevariables on the WEB

    A cookie is simply a text-file that consists of atext-only string which gets stored and maintained

    by the browser Cookies are unique named, and have a singlevalue with settable life(with optional attributes,including comment, path and domain qualifiersfor the hosts which see the cookie, a maximumage, and a version)

    3 2 7 HTTP Servlet - Cookies

  • 8/8/2019 adv_java1

    74/281

    Page 74Presentation Name HTC Confidential

    3.2.7.HTTP Servlet Cookies

    Cookies can be passed back and forth between

    the browser and the server Cookies are created on the instruction of a web-

    server

    After a cookie is transmitted through the HTTPheader, it is kept at the browser for fast retrievalso that any request that goes to the sameserver,the browser will attach all live coockies of

    that server along with the request Cookies are by default have a life spanning to

    clients session

    3.2.7.HTTP Servlet - Cookies

  • 8/8/2019 adv_java1

    75/281

    Page 75Presentation Name HTC Confidential

    3.2.7.HTTP Servlet Cookies

    Browser settings allow rejection of Cookies, so,the programmer needs to be careful in the usageof Cookies

    Applications that use cookies include:

    Storing user preferences

    Personalization

    Automating low security user sign-on

    Collecting data used for "shopping cart" styleapplications

    3.2.7.HTTP Servlet - Cookies

  • 8/8/2019 adv_java1

    76/281

    Page 76Presentation Name HTC Confidential

    3.2.7.HTTP Servlet Cookies

    Cookies can be set and retrieved at Client-sideusing JavaScript / VBScript

    HTTP Servlets support setting, retrieval andmanipulation of Cookies as follows :

    The addCookie( ) method of the HttpServletResponse -for setting Cookies

    The getCookies( ) method of the HttpServletRequest-for retrieving Cookies

    The javax.servlet.http.Cookie class - for creating andmanipulating Cookies

    3.2.7.HTTP Servlet - Cookies

  • 8/8/2019 adv_java1

    77/281

    Page 77Presentation Name HTC Confidential

    3.2.7.HTTP Servlet Cookies

    The following code snippets describe theusage of Cookies in HTTP Servlets: Cookie Creation:

    Cookie toClient1 = new Cookie( USER,SHIVA );

    res.addCookie( toClient1

    );Cookie toClient2 = new Cookie( COMP,HTC );res.addCookie( toClient2 );

    Cookie Retrieval:Cookie[ ] fromClient = req.getCookies( );

    for ( int i = 0; i < fromClient.length; i++ ) {System.out.println( Cookie + fromClient[ i ].getName( ) + Has Value : + fromClient[ i ].getValue( ) );

    }

    3.2.Servlets

  • 8/8/2019 adv_java1

    78/281

    Page 78Presentation Name HTC Confidential

    3.2.Servlets

    3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy

    3.2.5.HTTP Servlet-

    Session Management 3.2.6.ServletContext and ServletConfig

    3.2.7.HTTP Servlet Cookies

    3.2.8.Servlet -info in web configuration file

    3.2.9.servlet resource-access 3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    79/281

    Page 79Presentation Name HTC Confidential

    3.2.8.Sevlet Configuration file

    Servlets all deployment information is made available tothe container in the web configuration file web.xml.thefollowing are the important elements in this regard

    ..

    ..

  • 8/8/2019 adv_java1

    80/281

    Page 80Presentation Name HTC Confidential

    3.2.8.Sevlet Configuration file

    ..

    /

    ..

  • 8/8/2019 adv_java1

    81/281

    Page 81Presentation Name HTC Confidential

    3.2.8.Sevlet Configuration file

    1800

    ..

    ..

    3.2.Servlets

  • 8/8/2019 adv_java1

    82/281

    Page 82Presentation Name HTC Confidential

    - 3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy 3.2.5.HTTP Servlet- Session Management

    3.2.6.ServletContext and ServletConfig 3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access

    3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    83/281

    Page 83Presentation Name HTC Confidential

    3.2.9.servlet resource access

    Any other resources that are there on the applicationserver can easily be accessed by the servlet through ENC(Environment Naming Context)in similar way as EJBs

    resource is defined in web.xml file as

    *

    .

    .

  • 8/8/2019 adv_java1

    84/281

    Page 84Presentation Name HTC Confidential

    3.2.9.servlet resource access

    This is referred and accessed in servlet code fromthe jndi InitialContext object as

    InitialContext ctx=new InitialContext();resource-type-classobj=ctx.lookup(java:comp/env/*);

    3.2.Servlets

  • 8/8/2019 adv_java1

    85/281

    Page 85Presentation Name HTC Confidential

    - 3.2.1.Introduction to Servlets

    3.2.2.Life Cycle of Servlets

    3.2.3.A Sample HTTP Servlet

    3.2.4.HTTP Servlet-Anatomy 3.2.5.HTTP Servlet- Session Management

    3.2.6.ServletContext and ServletConfig 3.2.7.HTTP Servlet- Cookies

    3.2.8.Servlet-info in web configuration file

    3.2.9.servlet resource-access

    3.2.9.1.filter,filter-mappings

  • 8/8/2019 adv_java1

    86/281

    Page 86Presentation Name HTC Confidential

    3.2.9.1.filter,filter-mappings

    A Filter can perform filtering on clients request for aresource like a servlet/static content or on a response thatgoes from a resource.they are majorly used forauthentiction,logging,auditing,xml based

    transformations,to fire events.. Any class that implement Filter interface have to give codefor the following methods

    init(FilterConfig ..) destroy()

    doFilter(ServletRequest req,ServletResponse res,FilterChain ..) It is in the doFilter() method ,the filter will be doing its

    aimed task.The filterchain object can be used chainedfilters

  • 8/8/2019 adv_java1

    87/281

    Page 87Presentation Name HTC Confidential

    3.2.9.1.filter,filter-mappings

    The FilterConfig object allows the Filter class toaccess any of the configured initial parametersthat can be given in web.xml within tag

    The associated methods are getInitParameterNames() getInitParameter()

    getServletContext()

    filter-

    mappings are given in web.xml file to tellthe container what filters are there for therequested uri and in what order

    3 2 JSP

  • 8/8/2019 adv_java1

    88/281

    Page 88Presentation Name HTC Confidential

    3.2.JSPWhat do JSPs contain?

    Java Server Pages are text files that combine standardHTML/XML and new scripting tags

    JSPs look like HTML/XML ,but they got compiled into Javaservlets the first time they are invoked

    The resulting servlet is a combination of the HTML fromthe JSP file and embedded dynamic content specified bythe new tags

    Everything in a JSP page can be broken into 2 categories:

    Elements that are processed on the server

    Template data ,or everything other than elements,that the engine processing the JSP ignores

    3.2.JSP

  • 8/8/2019 adv_java1

    89/281

    Page 89Presentation Name HTC Confidential

    JSP Life Cycle:-

    Intialize

    public void jspInit()

    |

    handle client request s and generate responses

    void_jspService(ServletRequest,ServletResponse)throwsIOException,ServletException

    |

    Destory

    public void jspDestory()

    3 2 JSP

  • 8/8/2019 adv_java1

    90/281

    Page 90Presentation Name HTC Confidential

    3.2.JSP

    Directives Declarations

    Scriptlets

    Expressions

    Standard actions

    3 2 JSP -Directive

  • 8/8/2019 adv_java1

    91/281

    Page 91Presentation Name HTC Confidential

    3.2.JSP -Directive

    The three directives are:- page directive

    include directive

    taglib directive

    page directive:- defines a number of important attributes that

    affect the whole page A single JSP can contain multiple page directives,

    and during translation all the page ditectives are

    assimilated (integrated) and applied to the samepage together

    3.2.JSP - Directive

  • 8/8/2019 adv_java1

    92/281

    Page 92Presentation Name HTC Confidential

    various attributes of page directive are:- language

    extends

    import session

    buffer autoFlush

    isThreadSafe

    info

    isErrorPage errorPage contentType

    3.2.JSP - Directives

  • 8/8/2019 adv_java1

    93/281

    Page 93Presentation Name HTC Confidential

    3.2.JSP Directives

    include directive It notifies the container to include the content of the resource in

    the current JSP ,inline, at the specified place.

    The content of the included file is parsed by the JSP and thishappens only at translation time.

    The included file should not be another dynamic page.

    Most JSP containers usually keep track of the included file andrecompile the JSP if it changes

    Atttibute:-

    file (the static filename to include)

    3.2.JSP - Directives

  • 8/8/2019 adv_java1

    94/281

    Page 94Presentation Name HTC Confidential

    taglib directive allows the page to use custom user defined tags

    it also names the tag library that they are defined in

    The engine uses this tag library to find out what to do when itcomes across the custom tags in the JSP

    Attributes are:-

    uri

    prefix

    3.2.JSP Scripting Elements

  • 8/8/2019 adv_java1

    95/281

    Page 95Presentation Name HTC Confidential

    Scripting elements are used to include scripting

    code(usually java code) within the JSP.

    They allow you to declare variables and methods

    The three types of scripting elements are: Declarations

    Scriptlets

    Expressions

    3.2.JSP - Declarations

  • 8/8/2019 adv_java1

    96/281

    Page 96Presentation Name HTC Confidential

    A declaration is a block of java code in a JSP that is

    used to define class-wide variables and methods They are initialized when the JSP page is initialized Can not produce output to client

    Ex:-

    3.2.JSP - Scriptlets

  • 8/8/2019 adv_java1

    97/281

    Page 97Presentation Name HTC Confidential

    A Scriptlet is a block of java code that isexecuted at request-processing time

    Can produce output to the client

    ex:-

    3 2 JSP - Expressions

  • 8/8/2019 adv_java1

    98/281

    Page 98Presentation Name HTC Confidential

    3.2.JSP Expressions

    Expressions are to display any user output or a

    manipulated value When the expression is evaluated ,the result is

    converted to a string and displayed

    Ex:-

    3.2.JSP Standard Actions

  • 8/8/2019 adv_java1

    99/281

    Page 99Presentation Name HTC Confidential

    Actions are specific tags that affect the runtime

    behaviour of the JSP and affect the response sent backto the client Standard Action types are:-

    Use Bean Set Property

    Get Property

    Param Params

    Include

    Forward Plug-in

    3.2.JSP Standard actions

  • 8/8/2019 adv_java1

    100/281

    Page 100Presentation Name HTC Confidential

    3.2.JSP Standard actions

    Jsp:useBean

    Is used to associate a javaBean with the JSP

    JSP:setProperty

    Is used in conjunction with the useBean action

    To set the value of the properties of a bean Jsp:getProperty

    Is used in conjunction with the useBean action

    Complementary to the JSP:setProperty

    To access the properties of a bean

    3 2 JSP Standard actions

  • 8/8/2019 adv_java1

    101/281

    Page 101Presentation Name HTC Confidential

    3.2.JSP Standard actions

    jsp:param used to provide other tags with additional information in the

    form of name value pairs

    used in conjunction with jsp:include,jsp:forward and jsp:pluginactions

    Jsp:include Allows a static or dynamic resource to be included in the currentJSP at request time

    Jsp:forward Allows the request to be forwarded to another JSP,a servlet

    Jsp:plugin Meant to dynamically load the browsers plugin jdk software

    either to run an applet or gui-bean

    3.2.JSP Implicit objects

  • 8/8/2019 adv_java1

    102/281

    Page 102Presentation Name HTC Confidential

    These objects do not be declared or instantiated by the JSPauthor, but are provided by the container in the implementationclass

    All the implicit objects are available only to scriptlets ordeclarations , and are not available in declarations

    Different implicit objects are:- request object

    response object

    pageContext object

    session object

    application object

    Out object

    config object

    page object

    exception object

    3.2.JSP 2.0 EL

  • 8/8/2019 adv_java1

    103/281

    Page 103Presentation Name HTC Confidential

    Expressions appear between ${ and }. Note that${ and } may contain whole expressions,

    not just variable names, as in the Bourne shell (and itsdozen derivatives.)

    E.g., ${myExpression + 2}

    Expressions default targets are scopedattributes (page, request, session,application)

    ${duck} pageContext.findAttribute(duck)

    3.2.JSP 2.0 EL

  • 8/8/2019 adv_java1

    104/281

    Page 104Presentation Name HTC Confidential

    J

    The . and [] operators refer to JavaBean-style

    properties and Map elements: ${duck.beakColor} can resolve to

    ((Duck)

    pageContext.getAttribute(duck)).getBeakColor()

    Note the automatic type-cast. This is one of the great features of the EL: users do not need to concernthemselves with types in most cases (even though the underlying typesof data objects are preserved.)

    3.2.JSP 2.0 EL

  • 8/8/2019 adv_java1

    105/281

    Page 105Presentation Name HTC Confidential

    J 0

    Expressions may also refer to cookies, requestparameters, and other data: ${cookie.crumb}

    ${param.password}

    ${header[User-Agent]}

    ${pageContext.request.remoteUser}

    3.2.JSP 2.0 EL

  • 8/8/2019 adv_java1

    106/281

    Page 106Presentation Name HTC Confidential

    J

    The EL supports Arithmetic ${age + 3}

    Comparisons ${age > 21}

    Equality checks ${age = 55}

    Logical operations ${young or beautiful} Emptiness detection ${empty a}

    a is empty String (), empty List, null, etc. Usefulfor ${empty param.x}

    3.Advanced-Java Contents -1

  • 8/8/2019 adv_java1

    107/281

    Page 107Presentation Name HTC Confidential

    J

    3.1.JDBC

    3.2.Servlets & JSP

    3.3.Tag Libraries 3.4.Struts

    3.5.Struts-Tag Libraries 3.6.JSTL

    3.7.XML

    3.8.Junit

    3.9.Ant

    3.3.Tag Libraries Introduction

  • 8/8/2019 adv_java1

    108/281

    Page 108Presentation Name HTC Confidential

    g

    Tag (often referred as custom tags) look like

    HTML/XML tags embedded in a JSP page They have a special meaning to a JSP engine at

    translation time, and enable applicationfunctionality to be invoked without the need towrite the java code in JSP scriptlets

    It is used to encapsulate java functionality thatcan be used from a JSP page

    Well-designed tag libraries can enable applicationfunctionality to be invoked without theappearance of programming

    3.3.Tag Libraries

  • 8/8/2019 adv_java1

    109/281

    Page 109Presentation Name HTC Confidential

    Types of tag Predefined Tag

    Customized Tag

    Predefined Tag

    Functionality provided implicitly by container. Example

    3.3.Tag Libraries

  • 8/8/2019 adv_java1

    110/281

    Page 110Presentation Name HTC Confidential

    Customized Tag Functionality provided by the programer.

    Example

    The above codes connects to a database and get theproduct list.

    Advantage The web page developer can concentrate on the

    content rather than business logic. Access to implicit object.(details later)

    3.3.Tag Libraries

  • 8/8/2019 adv_java1

    111/281

    Page 111Presentation Name HTC Confidential

    Any valid custom tag should contain : A reference in Tag Library Descriptor

    A Tag Handler Class

    Tag Handler

    Its the class which provides the javafunctionality for that particular tag.

    Tag Library Descriptor

    Contains various Tags

    Links Tags with Handler Classes

    3.3.Tag Libraries

  • 8/8/2019 adv_java1

    112/281

    Page 112Presentation Name HTC Confidential

    What is a TLD (Tag Library Descriptor) ? A XML file which contains list of tags and information

    about them.

    Information contains

    Name of Handler class

    About the nature of tag (details later)

    can contain many tag

    (no 1 to 1 mapping between tag and TLD)

    Saved with .tld extension

    Contains also information about attributes

    3.3.Tag Libraries

  • 8/8/2019 adv_java1

    113/281

    Page 113Presentation Name HTC Confidential

    Types of Tag:-- Simple Tag (No Body,No Attribute).

    Simple Tag With Attributes.

    Tag With Body.

    Nested Tag.

    3.3.Tag Libraries-Simple tag

  • 8/8/2019 adv_java1

    114/281

    Page 114Presentation Name HTC Confidential

    g p g

    A simple tag is without attributes or tag bodies

    They are of the form

    Example:- HelloWorld.jsp

    3.3.Tag Libraries- Simple tag

  • 8/8/2019 adv_java1

    115/281

    Page 115Presentation Name HTC Confidential

    g p g

    Tag Handler Classpublic class HelloWorld extends SimpleTagSupport

    {

    public void doTag() throws JspTagException

    { // this method is called when the start is encounteredpageContext.getOut.write("Hello World");

    // pageContext is object provided by container through

    // implicit objects can be created and used.

    }

    }

    HelloWorld.java

    3.3.Tag Libraries- Simple tag

  • 8/8/2019 adv_java1

    116/281

    Page 116Presentation Name HTC Confidential

    Tag Library Descriptor :---

    sayHello // Name of the Tag used in JspHelloWorld // Name of Tag Handler Clempty

    TagCollection.tld

    3.3.Tag Libraries-Tags with attribute

  • 8/8/2019 adv_java1

    117/281

    Page 117Presentation Name HTC Confidential

    Adds flexibility to your tag library

    Allowing tags like

    Example:--

    AttribTag.jsp

    3.3.Tag Libraries- Tags with attribute

  • 8/8/2019 adv_java1

    118/281

    Page 118Presentation Name HTC Confidential

    import javax.servlet.http.*;

    import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;

    import java.io.*;public class TagAttrib extends SimpleTagSupport {

    private String name;public setName(String name) {

    this.name=name;

    }public void doTag()throws JspTagException {

    pageContext.getOut.write("Hello "+ name);}

    }

    TagAttrib.java

    3.3.Tag Libraries- Tags with attribute

  • 8/8/2019 adv_java1

    119/281

    Page 119Presentation Name HTC Confidential

    inputTagAttrib

    nametruetrue

    empty

    TagCollections.tld

    3.3.Tag Libraries -Tag with Body

  • 8/8/2019 adv_java1

    120/281

    Page 120Presentation Name HTC Confidential

    This tag is used in the following manner

    body

    Example:--

    This is a Body Tag // Content can be

    Jsp,HTML. The Handler class implement BodyTag

    interface.Support class is BodyTagSupport. You have additional methods

    doAfterBody(),doInitBody() in Tag class

    3.3.Tag Libraries-Tag with Body

  • 8/8/2019 adv_java1

    121/281

    Page 121Presentation Name HTC Confidential

    Example:--Hello.jsp

    Untitled

  • 8/8/2019 adv_java1

    122/281

    Page 122Presentation Name HTC Confidential

    The TagHandler class extends BodyTagSupport {setPageContext(){} // container sets thepagecontextsetParent()// sets the parent in case of nested tag

    set the attributes using setMethodsdoStartTag()// Executed when the starting tag is

    encountered should return EVAL_BODY_TAGsetBodyContent()// to set the current BodyContentfor it to use (if there is at least one evaluation of thebody of the BodyTag).

    doInitBody() // This is where we will normally put anyinstructions that should be taken care of before thebody of the BodyTag is evaluated for the first time.

    3.3.Tag Libraries-Tag with Body

  • 8/8/2019 adv_java1

    123/281

    Page 123Presentation Name HTC Confidential

    doAfterBody() // called after each evaluation of thebody.If this method returns EVAL_BODY_TAG, thismethod should be called again. If this methodreturns SKIP_BODY, continue below.

    doEndTag()//called when the ending tag isencountered.

    release()

    }

    3.3.Tag Libraries-Tag with Body

  • 8/8/2019 adv_java1

    124/281

    Page 124Presentation Name HTC Confidential

    Tag Handler classpackage htc;

    import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.*;

    public class HelloWithBody extends BodyTagSupport{

    public int count;int i;public void setCount(int count)

    {this.count = count;

    }

    3.3.Tag Libraries-Tag with Body

  • 8/8/2019 adv_java1

    125/281

    Page 125Presentation Name HTC Confidential

    public int doAfterBody() throws JspTagException{

    i++;String msg = getBodyContent().getString();try{getBodyContent().getEnclosingWriter().write(msg);}

    catch(Exception e) { }getBodyContent().clearBody();if(i>=count)

    return SKIP_BODY;else

    return EVAL_BODY_TAG;}

    }

    3.3.Tag Libraries-Tag with Body

  • 8/8/2019 adv_java1

    126/281

    Page 126Presentation Name HTC Confidential

    Tag Library Descriptor File

    HelloWithBodyhtc.HelloWithBodyJSP

    counttruefalse

    3.3.Tag Libraries-Nested Tags

  • 8/8/2019 adv_java1

    127/281

    Page 127Presentation Name HTC Confidential

    Nested tags are nothing but a tag used inside

    another tag Where the behaviour of certain tags depends on

    values supplied by earlier tags ,we go for nestedtags

    To define a tag that depend on a particularnesting order For ex:-in standard HTML, the TD and TH elements

    can only appear within TR, which in turn can only

    appear within TABLE

    3.3.Tag Libraries-Nested Tags

  • 8/8/2019 adv_java1

    128/281

    Page 128Presentation Name HTC Confidential

    Tag Handler Classes

    Can be extended from either TagSupport orBodyTagSupport, depending on whether they need tomanipulate their body content(these extendBodyTagSupport ) or just ignore it(these extend

    TagSupport ) There are two new approaches for nested tags

    First, nested tags can use findAncestorWithClass to findthe instance of a given class type that is closest to a

    given instance.

    3.3.Tag Libraries-Nested Tags

  • 8/8/2019 adv_java1

    129/281

    Page 129Presentation Name HTC Confidential

    First (continued):--

    this method takes a reference to the current class(e.g.this) and the Class object of the enclosing class(e.g.EnclosingTag.class) as arguments

    If no enclosing class is found , the method in the nestedclass can throw a JspTagException that reports theproblem

    Second :-- if one tag wants to store data that a later tag will use,

    it can place that data in the instance of the enclosing tag

    The definition of the enclosing tag should providemethods for storing and accessing this data

    3.3.Tag Libraries-Iteration Tags

  • 8/8/2019 adv_java1

    130/281

    Page 130Presentation Name HTC Confidential

    The IterationTag interface extends Tag by defining oneadditional method that controls the reevaluation of its body.

    A tag handler that implements IterationTag is treated as onethat implements Tag regarding the doStartTag() anddoEndTag() methods. IterationTag provides a new method:doAfterBody().

    The doAfterBody() method is invoked after every bodyevaluation to control whether the body will be reevaluated ornot.

    If doAfterBody() returns IterationTag.EVAL_BODY_AGAIN,

    then the body will be reevaluated. If doAfterBody() returnsTag.SKIP_BODY, then the body will be skipped anddoEndTag() will be evaluated instead.

    3.3.Tag Libraries-Tag Extra Info Classes

  • 8/8/2019 adv_java1

    131/281

    Page 131Presentation Name HTC Confidential

    Optional class provided by the tag library author todescribe additional translation-time information notdescribed in the TLD

    This class can be used: to indicate that the tag defines scripting variables

    to perform translation-time validation of the tag attributes

    To extend from Tag Extra Info class ,you have to overridetwo methods VariableInfo[ ] getVariableInfo(TagData data)

    Used to return information on scripting variables that the tagmakesavailable to JSPs using it

    Returns an array ofVariableInfo objects, which contain informationabout the name of each scripting variable and its fully qualifiedclass name

    3.3.Tag Libraries-Tag Validation

  • 8/8/2019 adv_java1

    132/281

    Page 132Presentation Name HTC Confidential

    3.3.Tag Libraries-Tag Extra Info Classes

  • 8/8/2019 adv_java1

    133/281

    Page 133Presentation Name HTC Confidential

    boolean isValid(TagData data)

    used for Translation-time validation of theattributes.

    Request-time attributes are indicated as such inthe TagData parameter.

    3.Advanced-Java Contents -1

  • 8/8/2019 adv_java1

    134/281

    Page 134Presentation Name HTC Confidential

    3.1.JDBC 3.2.Servlets & JSP

    3.3.Tag Libraries 3.4.Struts

    3.5.Struts-Tag Libraries 3.6.JSTL

    3.7.XML

    3.8.Junit

    3.9.Ant

    3.4.Struts

  • 8/8/2019 adv_java1

    135/281

    Page 135Presentation Name HTC Confidential

    Framework

    set of multiple classes,interfaces,components aimed at solvingspecific problem/application

    reusable

    utilizes J2EE patterns while building the components in particular

    Struts is such a framework mainly created by Craig R.

    McClanahan and donated to ASF in 2000. Struts match to MVC2 patterns where the controller will

    mostly forward to different urls based on the clientsrequest w/o sending any response which is totally

    handled by view component i.e jsps

    3.4.Struts

  • 8/8/2019 adv_java1

    136/281

    Page 136Presentation Name HTC Confidential

    Struts is made up of approximately 300 java classesdivided into 8 core packages like actions contain Action Classes action contain controller classes like ActionForm,ActionMessages util contain general-purpose utility classes taglib contain tag handler libraries

    upload contain classes that help uploading and downloading files

    through a browser tiles contain classes meant for tiles framework config contain configuration classes whose objects gets initialized

    from the struts-config.xml contents validator contain Struts specific extension classes meant for of

    validator.actual validator classes are available in the commonspackage,separate from struts

    3.4.Struts

  • 8/8/2019 adv_java1

    137/281

    Page 137Presentation Name HTC Confidential

    In struts framework the Controller component functionalityis divided by more than one component,one of which isorg.apache.struts.action.ActionServlet class whose mainfunction is to receive the clients request and process itthrough a handler class i.e RequestProcessor class in 1.1version,meant for flexibility to subclass.after this itdelegates the handling of the request to a helper class

    which is a subclass of org.apache.struts.action.Action sothat decoupling client-request & business-logic takes place.

    Subclasses of Action class should give code forpublic ActionForwardexecute(ActionMapping,ActionForm,HttpServletRequest,HttpServletResponse) as the framework creates a singleton ofthis and invoke its execute method since the super classthe method returns null.

    3.4.Struts

  • 8/8/2019 adv_java1

    138/281

    Page 138Presentation Name HTC Confidential

    the ActionServlet class will be configured in

    web.xml which is the single one that will invokesuitable action Objects as per the input form theimportant initial parameters for this servlet are configlocation of struts-config.xml file

    config/sub to specify additional configuration files

    debugcontrols how much info is to be logged detaildetail level for Digestor,which logs info as it

    parses the configuration files convertHacka boolean variable whether any Wrapper

    class variables are to be initialized to null(if true defaultis false) or default value of their type

    3.4.Struts

    h i l ill b fi d i

  • 8/8/2019 adv_java1

    139/281

    Page 139Presentation Name HTC Confidential

    the Action class will be configured in

    struts-

    config.xml within blocksas action element with following importantattributes attributename of session-scope attribute under which

    form-bean can be accessed

    classNamethe implementation class,by defaultActionMapping

    forwardthe application-relative path to a resource towhich further navigation occur.the attributesforward/include/type are mutually exclusive

    Input application-relative path of the input form towhich control should go if a validation error occur

    3.4.Struts

    th f th f b i t d ith thi

  • 8/8/2019 adv_java1

    140/281

    Page 140Presentation Name HTC Confidential

    namethe name of the form-bean associated with thisaction.this value should one of name attribute of theform-bean elements defined already

    paththe application-relative path to the submittedrequest,starting with / character

    parameter to take care of any extra information that is

    required so that action class can use getParameter()method scope request or session to identify the scope of the

    associated form-bean typefully qualified javaclass name

    validatedetermines whether validate() method isinvoked by the form-bean or not default is true

    3.4.Struts

  • 8/8/2019 adv_java1

    141/281

    Page 141Presentation Name HTC Confidential

    Types of Action classes

    Dispatch Actions mean for abstracting multiple actionsin a single class instead of scattering over multipleaction classes useful particularly when actions arerelated and focussed on an entity like sale ofproduct,updation of its price,viewing the details of it

    typical implementation as many named methods thatreturn suitable ActionForward object.the configurationcontains parameter attribute with method and methodname is used in the url like

    http://localhost:8080/myappl/sales?method=sellProduct

    3.4.Struts

    T f A ti l

  • 8/8/2019 adv_java1

    142/281

    Page 142Presentation Name HTC Confidential

    Types of Action classes

    Forard Actions

    useful where the controller will simplyforward from one jsp page to another jsp page withoutspecific processing by Action class no specifical Actionclass writing is necessary.the type attribute will beorg.apache.struts.actions.ForwardAction and the

    forwarding target url is given by the parameter attribute Include Actions originally planned to integrate servlet-based components into struts-based webapplications.type attribute will haveorg.apache.struts.actions.IncludeAction and the url is

    given by the parameter attribute

    3.4.Struts

  • 8/8/2019 adv_java1

    143/281

    Page 143Presentation Name HTC Confidential

    Types of Action classes

    Switch Actions this is intended to support switchingfrom one application-module to another particularlywhen you can configure more than one configuration filerequires a prefix request parameter that gives the

    application prefix.if wanted to switch to the default ,youcan use zero-length string as .the page requestparameter should be there that gives the relative path.Only required if you have more than one module.Thetype is org.apache.struts.actions.SwitchAction

    3.4.Struts

  • 8/8/2019 adv_java1

    144/281

    Page 144Presentation Name HTC Confidential

    Form-Beans

    these are meant to take care of storing the users giveninput data and transfer them to the Action/subclasses(inexecute method)validating the input and display errors incase of validation failure.these are written as extending

    ActionForm class.

    These can have two levels of scope requestform-bean is available till the response is returned

    to the client

    sessionnecessary if application captures data across

    multiple pages and will be there till the session is timed out

    3.4.Struts

  • 8/8/2019 adv_java1

    145/281

    Page 145Presentation Name HTC Confidential

    these are created as subclasses of ActionForm(which isabstract) to capture an application-specific form-data.withinthe class you should define a property for each field that isgoing to be received through the html form with accessor &mutator methods.it may contain a validate() method whichRequestProcessor class calls as well as reset() method,sincethe reset method is called for every new request particularyif default scope ie session is in effect,so that the bean fieldsare set back to their defaults.

    These are configured under form-bean element underform-beans element,contains two required attributesa)name should match to that of action elementsb)type should have full packaged path of form class

    3.4.Struts

  • 8/8/2019 adv_java1

    146/281

    Page 146Presentation Name HTC Confidential

    Dynamic ActionForms will avoid exclusive writing of

    subclasses as you can configure the simple properties inconfiguration file itself for ex

    But if validate method is to be implementation,another classhas to be written only for that,since by default reset(0method is taken well care of

    3.4.Struts

    Struts Validator

  • 8/8/2019 adv_java1

    147/281

    Page 147Presentation Name HTC Confidential

    Struts Validatorstruts framework allows to skip validation in actionforms

    and done through David winterfeldts validatorframework.this will allow to configure.the framework rulesare available in validator-rules.xml the other file isvalidation.xml which is application-specific as it describeswhich validation rules from the above xml file are beingused by the application for ex:

    .

    3.4.Struts

    Struts Validator

  • 8/8/2019 adv_java1

    148/281

    Page 148Presentation Name HTC Confidential

    Struts Validator

    all the above ,we can call as server-sidevalidation.for client-side validation you can usecustomTag called JavascriptValidator based onthe javascript code available in validator-rules.xml

    when the JavascriptValidator is used in the jsp filethe text from the javascript element is madeavailable to the jsp page allowing client-sidevalidation there should be in the jsp

    3.Advanced-Java Contents-1

  • 8/8/2019 adv_java1

    149/281

    Page 149Presentation Name HTC Confidential

    3.1.JDBC 3.2.Servlets & JSP

    3.3.Tag Libraries

    3.4.Struts

    3.5.Struts-Tag Libraries 3.6.JSTL

    3.7.XML

    3.8.Junit

    3.9.Ant

    3.5.Struts-Tag Libraries

    >The struts framework provides a fairly rich set of

  • 8/8/2019 adv_java1

    150/281

    Page 150Presentation Name HTC Confidential

    ->The struts framework provides a fairly rich set of

    framework components->It also includes a set of tag libraries that aredesigned to interact intimately with the rest of theframework

    -

    >The custom tags provided by struts are groupedinto:-HTML TagsBean Tags

    Logic Tags

    Nested TagsTiles Tags

    3.5.Struts-Tag Libs-HTML tag

    C t i t g d t t HTML i t f

  • 8/8/2019 adv_java1

    151/281

    Page 151Presentation Name HTC Confidential

    Contains tags used to create HTML input forms

    For ex:-instead of using a regular HTML text-input field ,you can use the text tag from thislibrary

    These tags are designed to work with the other

    components of the Struts framework,includingActionForms

    Most of the tags within this library must benested inside of a Struts form tag

    3.5.Struts-Tag Libs-HTML tag

    Custom tags within the Struts HTML tag

  • 8/8/2019 adv_java1

    152/281

    Page 152Presentation Name HTC Confidential

    g gLibrary are:-

    < html:button/>

    < html:checkbox/>

    < html:file/>

    < html:hidden/>

    < html:image/>

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    153/281

    Page 153Presentation Name HTC Confidential

    Custom tags within the Struts HTML tag Library

    are (continued):- < html:link/> < html:option/>

    < html:password/> < html:reset/>

    < html:submit/> < html:textarea/>

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    154/281

    Page 154Presentation Name HTC Confidential

    Used to insert an HTML element ,including an

    href pointing to the absolute location of the hostingJSP page

    Has no body and supports two attributes(optional)

    Used to render an HTML element with an

    input type of button

    Has a body type of JSP

    Required attribute are: property,title

    3.5.Struts-Tag Libs-HTML tag

    ht l l /

  • 8/8/2019 adv_java1

    155/281

    Page 155Presentation Name HTC Confidential

    Used to render an HTML element with an inputtype of cancel

    Has a body type of JSP and supports 25 attributes

    Required attributes are:- title

    Used to render an HTML element with an input

    type of checkbox

    Has a body type of JSP and supports 27 attributes

    Required attributes are:- property,title Must be nested inside the body of an tag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    156/281

    Page 156Presentation Name HTC Confidential

    Used to display the ActionError objects stored in anActionErrors collection

    Has a body type of JSP and supports fourattributes(optional)

    Used to create an HTML element Allows you to upload files

    Has a body tag of JSP and supports 30 attributes

    Required attributes are:- property,title Must be nested inside the body of an tag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    157/281

    Page 157Presentation Name HTC Confidential

    Used to create an HTML form has a body type of JSP and supports 13 attributes

    Required attributes are :- action

    Used to render an HTML element with an input typeof hidden

    Has a body of JSP and supports 25 attributes

    Required attributes are :- property,title

    Must be nested inside the body of antag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    158/281

    Page 158Presentation Name HTC Confidential

    Used to insert an custom JavaScript validation methods

    has no body and supports 8 attributes

    No required attributes are there

    Used to generate an HTML hyperlink Has a body type of JSP and supports 37 attributes

    Required attributes are :- title

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    159/281

    Page 159Presentation Name HTC Confidential

    Used to display a general-

    purpose messages to theuser stored in ActionMessages,ActionErrors etc

    has a body type of JSP and supports 8 attributes

    Required attributes are :- id

    Used to generate an HTML element of

    type, which represents a single optionelement nested inside a parent element

    Has a body type of JSP and supports 8 attributes Required attributes are :- value

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    160/281

    Page 160Presentation Name HTC Confidential

    p / Used to generate a list of HTMLelements

    Child of the tag

    has no body and supports 8 attributes

    Required attributes are :- action

    Must be nested inside antag

    Can also be used n-

    number of times within an html:select/>element

    Used to render an HTML element with an input type ofpassword

    Has a body type of JSP and supports 31 attributes

    Required attributes are :- property,title Must be nested inside the body of antag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    161/281

    Page 161Presentation Name HTC Confidential

    Used to render an HTMLelement with an inputtype of radio

    has a body of type JSP and supports 28 attributes

    No required attributes are :-property, value, title

    Must be nested inside antag

    Used to render an HTML element with an input

    type of reset

    Has a body type of JSP and supports 25 attributes No required attributes are there

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    162/281

    Page 162Presentation Name HTC Confidential

    Used to render an HTMLelement with an input

    type of select

    has a body type of JSP and supports 28 attributes

    No Required attributes are there

    Used to render an HTML element with an input

    type of image

    Has a body of JSP and supports 34 attributes

    Required attributes are :- title

    Must be nested inside the body of antag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    163/281

    Page 163Presentation Name HTC Confidential

    Used to render the top-levelelement

    has a body type of JSP and supports 2 attributes

    Required attributes are :- property, title

    Must be nested inside the body of antag

    Used to render an HTML element with an input

    type of submit, which results in a Submit button

    Has a body of JSP and supports 26 attributes

    No Required attributes are there Must be nested inside the body of antag

    3.5.Struts-Tag Libs-HTML tag

  • 8/8/2019 adv_java1

    164/281

    Page 164Presentation Name HTC Confidential

    Used to render an HTML element with an inputtype of text

    has a body type of JSP and supports 30 attributes

    Required attributes are :- property, title

    Must be nested inside the body of antag

    Used to render an HTML element with an input

    type of textarea

    Has a body of type JSP and supports 30 attributes Required attributes are :- property, title

    Must be nested inside the body of antag

    3.5.Struts Tag Libs-Bean tag

    Bean Tag library provides a group of tags that

  • 8/8/2019 adv_java1

    165/281

    Page 165Presentation Name HTC Confidential

    g b y p s g p gsencapsulates the logic necessary to access andmanipulate JavaBeans,HTTP cookies and HTTPheaders using scripting variables

    There are currently 11 custom tags in the Bean

    tag library Custom tags are:-

    3.5.Struts Tag Libs-Bean tag

  • 8/8/2019 adv_java1

    166/281

    Page 166Presentation Name HTC Confidential

    Custom tags are:- (continued)

    < bean:message/>

    3.5.Struts Tag Libs-Bean tag

  • 8/8/2019 adv_java1

    167/281

    Page 167Presentation Name HTC Confidential

    Used to retrieve the value of an HTTP cookie

    Can be used to retrieve single or multiple cookie values It has no body and supports 4 attributes Required attributes are :- id , name

    Used to retrieve the value of a named bean property anddefine it as a scripting variable,which will be stored in thescope specified by the toScope attribute

    It has a body type of JSP and supports 7 attributes

    Required attributes are :-

    id

    3.5.Struts Tag Libs-Bean tag

  • 8/8/2019 adv_java1

    168/281

    Page 168Presentation Name HTC Confidential

    It functions exactly like except that itretrieves its values from the named request header

    It has a body type of JSP and supports 4 attributes

    Required attributes are:- id, name

    Used to evaluate and retrieve the results of a Web

    application resource

    The tag functions much like the

    standard action, except that the response is stored ina page scoped object attribute, as opposed to beingwritten to the output stream

    3.5.Struts Tag Libs -Bean tag

    b

  • 8/8/2019 adv_java1

    169/281

    Page 169Presentation Name HTC Confidential

    Used to retrieve the value of an identified implicit

    JSP object, which it stores in the page context ofthe current JSP

    The retrieved object will be stored in the page

    scoped scripting variable named by the id attribute Has no body and supports 2 attributes

    Required attributes are :- id, property

    For ex:-

    We are retrieving the implicit session object and storing

    this reference in the scripting variable sessionVar

    3.5.Struts Tag Libs -Bean tag

    b /

  • 8/8/2019 adv_java1

    170/281

    Page 170Presentation Name HTC Confidential

    Used to retrieve the value of a request parameter

    identified by the name attribute

    The retrieved value will be used to define a pagescoped attribute of type String or String[], if the

    multiple value is not null Has no body and supports 4 attributes

    Required attributes are :- id, name

    For ex:-

    3.5.Struts Tag Libs -Bean tag

  • 8/8/2019 adv_java1

    171/281

    Page 171Presentation Name HTC Confidential

    Used to retrieve the value of Web applicationresource identified by the name attribute

    Has no body and supports 3 attributes

    Required attributes are :- id, name

    Used to retrieve the number of elements containedin a reference to an array, collection,or map

    Has no body and supports 5 attributes

    Required attributes are:-

    id

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    172/281

    Page 172Presentation Name HTC Confidential

    Contains tags that are useful for managingconditional genaration of output text, looping overobject collections for repetitive generation ofouput text, and application flow management

    So the focus of the logic tag library is on decisionmaking and object evaluation

    Logic tag library contains:-

    3.5.Struts Tag Libs -Logic tag Logic tag library contains (coninued)

    l i f d /

  • 8/8/2019 adv_java1

    173/281

    Page 173Presentation Name

    HTC Confidential

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    174/281

    Page 174Presentation Name

    HTC Confidential

    Evaluates its body if either the scripting variable identifiedby the name attribute or a property of the named scriptingvariable is equal to null or an empty string

    Has a body type of JSP and supports 3 attributes

    Required attributes are:- name

    Ex:--

    We test the scripting variable user .if this variable is null oran empty string , then the body will be evaluated, which

    will result in the user being forwarded to the globalforward login

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    175/281

    Page 175Presentation Name

    HTC Confidential

    g p y it is just opposite of tag

    Evaluates its body if either the variable specified by any one

    of the attributes cookie, name, parameter, or propertyequals the constant value specified by the value attribute

    Has a body type of JSP and supports 7 attributes

    Required attributes are:- value Ex:-- You are exactly the right age.

    We test the age data member of the scripting variable

    user.If this data member equals the value stored in therequiredAge variable, then the tags body will be evaluated

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    176/281

    Page 176Presentation Name

    HTC Confidential

    it is just opposite of tag

    Used to forward control of the current request to a

    previously identified global forward element

    Has no body and supports a single attribute name, which

    identifies the name of the global element that will receivecontrol of the request

    Ex:-

    We forward the current request to the global forwardlogin

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    177/281

    Page 177Presentation Name

    HTC Confidential

    uses the HttpServletResponse.sendRedirect()method to redirect the cuttent request to aresource identified by either the forward,href ,orpage attributes

    Has no body and supports 12 attributes (optional)

    Evaluates its body if the variable specified by any

    one of the attributes cookie, name,parameter, orproperty is greater than or equal to the constant

    value specified by the value attribute Has a body type of JSP and supports 7 attributes

    Required attributes are :- value, name

    3.5.Struts Tag Libs -Logic tag

    l i t Th /

  • 8/8/2019 adv_java1

    178/281

    Page 178Presentation Name

    HTC Confidential

    Simmilar to tag

    Used to iterate over a named collection and evaluatesits body for each Object in the collection

    Has a body type of JSP and supports 9 attributes

    Requred attributes are:-

    id

    3.5.Struts Tag Libs -Logic tag

  • 8/8/2019 adv_java1

    179/281

    Page 179Presentation Name

    HTC Confidential

    Evaluates its body if the variable contains thespecified constant value

    Has a body type of JSP and supports 8 attributes

    Required attributes are :- value

    tag is just opposite of match

    tag

    Evaluates its body if the variable specified ispresent in the application scope

    Has a body type of JSP and supports 8 attributes(optional) tag is just opposite of present

    tag

    3.5.Struts Tag Libs -Nested tag

    In nested tags you can use one tag inside

  • 8/8/2019 adv_java1

    180/281

    Page 180Presentation Name

    HTC Confidential

    In nested tags you can use one tag inside

    another tag that belong to thehtml,bean,logic groups with little confusionwith the necessity of making the child elementaware of the parent element

    3.5.Struts Tag Libs -Tiles tag

    The tiles tag library give page designers a