You are on page 1of 281

J2EE Training

Presentation Name –<Author Initial><Date> Page 1 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

Presentation Name –<Author Initial><Date> Page 2 HTC Confidential


3.1.JDBC

• JDBC indicates Java Database Connectivity


• The “java.sql” package makes it possible to connect to a
relational database, send SQL commands to the database,
process the returned results and invoke stored
procedures
• JDBC is database independent, so that the same code
works with all databases vix. Sybase, Oracle, DB2,
Informix...

Presentation Name –<Author Initial><Date> Page 3 HTC Confidential


3.1.JDBC
• JDBC Drivers
– To Connect to any database, we need to load (register)
programs called “Drivers” to interact with that particular
database :
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 calls
on the client API for Oracle, Sybase, Informix,
DB2, or other DBMS

Presentation Name –<Author Initial><Date> Page 4 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 then
translated to a DBMS protocol by a server. This
net server middleware is able to connect it’s
pure Java clients to many different databases
• Type 4 :- Native protocol Driver
– This kind of driver converts JDBC calls into the
network protocol used by DBMSs directly. This
allows a direct call from the client machine to
the DBMS server

Presentation Name –<Author Initial><Date> Page 5 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 over
that connection.
– A single application can have one or more connections
with a single database, or it can have connections with
many different databases.

Presentation Name –<Author Initial><Date> Page 6 HTC Confidential


3.1.JDBC

• Connection
– The standard way to establish a connection with a
database is to call :
DriverManager.getConnection( JDBCURL
[, <userID> ,<password>]);
– This method takes a string containing a JDBC URL and
an optional User ID/ Password (for those databases
which require them).
– A JDBC URL provides a way of identifying a database
so that the appropriate driver will recognize it and
establish a connection

Presentation Name –<Author Initial><Date> Page 7 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 a
network naming system
– The standard syntax for JDBC URLs is shown below. It
has three parts, which are separated by colons:

jdbc:<subprotocol>:<subname>

Presentation Name –<Author Initial><Date> Page 8 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”.
• <subprotocol>
– The name of the driver or the name of a database
connectivity mechanism
• <subname>
– A way to identify the database. The subname can vary,
depending on the subprotocol, and it can have any syntax
the driver writer chooses.
jdbc:odbc:wombat (where “wombat” is the DSN)
jdbc:oracle:thin:@taz:1521:ops001

Presentation Name –<Author Initial><Date> Page 9 HTC Confidential


3.1.JDBC
• Connection
– The DriverManager class is referred to as the JDBC
management layer
– The DriverManager class maintains a list of registered
Driver classes, and when the method getConnection is
called, it checks with each driver in the list until it finds
one that can connect to the database specified in the
URL.
– The Driver method connect( ) uses this URL to actually
establish the connection.

Presentation Name –<Author Initial><Date> Page 10 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 deal
of flexibility
– JDBC provides three classes for sending SQL
statements to the database viz. Statement,
PreparedStatement and CallableStatement.

Presentation Name –<Author Initial><Date> Page 11 HTC Confidential


3.1.JDBC

• Statements :--
– Statement
– A Statement object is used for sending simple
SQL statements.
– PreparedStatement
– A PreparedStatement object is used for SQL
statements that take one or more parameters as
input arguments (IN parameters).
– CallableStatement
– A CallableStatement object is used to execute
SQL stored procedures

Presentation Name –<Author Initial><Date> Page 12 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 single
result set, such as SELECT statements
• executeUpdate( )
– Is used to execute INSERT, UPDATE, or DELETE
statements and also SQL DDL (Data Definition
Language) statements like CREATE TABLE and
DROP TABLE

Presentation Name –<Author Initial><Date> Page 13 HTC Confidential


3.1.JDBC

• Statement
– Key Methods
• execute( )
– Is used to execute statements that return more than one
result set, more than one update count, or a combination
of the two
• close( )
– Releases this Statement object's database and JDBC
resources immediately instead of waiting for this to
happen when it is automatically closed
• setMaxRows( )
– Sets the limit for the maximum number of rows that any
result set can contain

Presentation Name –<Author Initial><Date> Page 14 HTC Confidential


3.1.JDBC

• Transactions
– A transaction consists of SQL statement(s) that have
been executed, completed, and then either committed
or rolled back.
– The method commit( ) of the Connection interface
makes permanent any changes an SQL statement
makes to a database. The method rollback( ) will
discard those changes.
– When the method commit( ) or rollback( ) is called,
the current transaction ends.

Presentation Name –<Author Initial><Date> Page 15 HTC Confidential


3.1.JDBC

• Transactions
– A new connection is in auto-commit mode by default,
meaning that when a statement is completed, the
method commit( ) will be called on that statement
automatically.
– In this case, since each statement is committed
individually, a transaction consists of only one
statement.
– If auto-commit mode has been disabled, a transaction
will not terminate until explicitly the commit( ) or
rollback( ) is called.

Presentation Name –<Author Initial><Date> Page 16 HTC Confidential


3.1.JDBC

• ResultSet
– A ResultSet contains all of the rows which satisfied the
conditions in an SQL statement, and it provides access
to the data in those rows through a set of get methods
that allow access to the various columns of the current
row.
– The ResultSet.next( ) method is used to move to the
next row of the ResultSet, making the next row
become the current row.

Presentation Name –<Author Initial><Date> Page 17 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 a
query
– The getXXX( ) methods provide the means for
retrieving column values from the current row in a
ResultSet
– Either the column name or the column number can be
used to designate the column from which to retrieve
data.

Presentation Name –<Author Initial><Date> Page 18 HTC Confidential


3.1.JDBC

• ResultSet
– For example, if the second column of a ResultSet
object is named “title”, to retrieve the value stored in
that 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
the data in the appropriate type.

Presentation Name –<Author Initial><Date> Page 19 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's
columns.
– 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));

Presentation Name –<Author Initial><Date> Page 20 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...

Presentation Name –<Author Initial><Date> Page 21 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...

Presentation Name –<Author Initial><Date> Page 22 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) { }
}
}
}

Presentation Name –<Author Initial><Date> Page 23 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...

Presentation Name –<Author Initial><Date> Page 24 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...

Presentation Name –<Author Initial><Date> Page 25 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) { }
}
}
}

Presentation Name –<Author Initial><Date> Page 26 HTC Confidential


3.1.JDBC
• PreparedStatement
– A PreparedStatement is more efficient than a
Statement object because it has been pre-compiled
and stored for future use.
– A PreparedStatement object is used for SQL
statements that take one or more parameters as input
arguments (IN parameters) and those SQL statements
that need to be executed repeatedly.
– Instances of PreparedStatement extend Statement and
include Statement methods.

Presentation Name –<Author Initial><Date> Page 27 HTC Confidential


3.1.JDBC
• PreparedStatement
– Created by the prepareStatement( ) method of the
Connection interface.
PreparedStatement pstmt =
con.prepareStatement (“insert into EMP
(ENO , ENAME) values ( ? , ? )”);
– An IN parameter is the one whose value is not
specified when the SQL statement is created, instead
the 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 is
executed.

Presentation Name –<Author Initial><Date> Page 28 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( “insert
into 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( );
}

Presentation Name –<Author Initial><Date> Page 29 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 it
adds methods for handling OUT and INOUT
parameters.
– The syntax for invoking a stored procedure in JDBC is
shown below :
{call procedure_name(?, ?, ...)}
CallableStatement cstmt = con.prepareCall(
“{call getTestData(?, ?)}” );

Presentation Name –<Author Initial><Date> Page 30 HTC Confidential


3.1.JDBC

• CallableStatement
– Passing in any IN parameter values to a
CallableStatement object is done using the setXXX
methods as in PreparedStatement.
– The JDBC type of each OUT parameter must be
registered before the CallableStatement object can be
executed using the method registerOutParameter.
– After the statement has been executed,
CallableStatement's getXXX methods are used to
retrieve the parameter value

Presentation Name –<Author Initial><Date> Page 31 HTC Confidential


3.1.JDBC
• CallableStatement
– The following code executes a Stored Procedure,
passes an IN parameter and retrieves two OUT
parameters :
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);

Presentation Name –<Author Initial><Date> Page 32 HTC Confidential


3.1.JDBC
• In JDBC 2.0 we can get ResultSets that allow
users to scroll in both directions.
• This is achieved through using II nd or IV th type
of drivers like
oracle.jdbc.driver.OracleDriver class object with
url jdbc:oracle:oci (oracle9 II nd type) or
jdbc:oracle:thin:@hostname:1521:sid (oracle9 IV
th) then using special createStatement() method
This ResultSet has methods like
previous(),last(),first(),beforFirst(),afterLast(),abs
olute(int),relative(int) for navigation

Presentation Name –<Author Initial><Date> Page 33 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

Presentation Name –<Author Initial><Date> Page 34 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

Presentation Name –<Author Initial><Date> Page 35 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

Presentation Name –<Author Initial><Date> Page 36 HTC Confidential


3.2.1.Introduction to Servlets

• Servlets
– are initialized and loaded only once
– are Multi-Threaded to handle multiple concurrent client
requests
– 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 restrictive
Sandbox(servlet container) for hacker prevention

Presentation Name –<Author Initial><Date> Page 37 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 controller
components

Presentation Name –<Author Initial><Date> Page 38 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 don’t fork a
new 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

Presentation Name –<Author Initial><Date> Page 39 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

Presentation Name –<Author Initial><Date> Page 40 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

Presentation Name –<Author Initial><Date> Page 41 HTC Confidential


3.2.1.Introduction to Servlets

• All Servlets implement the interface


javax.servlet.Servlet
• Most Servlets extend one of the following 2
standard implementations:
• javax.servlet.GenericServlet
• javax.servlet.http.HttpServlet
• WEB applications use HTTP Servlets
• HTTP Servlets extend Generic Servlet

Presentation Name –<Author Initial><Date> Page 42 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

Presentation Name –<Author Initial><Date> Page 43 HTC Confidential


3.2.2.Life Cycle of Servlets

• Servlets are initialized via an init( ) method at the


time of Instantiation
• The init( ) method is called only once during the
lifecycle of the Servlet, so, it need not be written
as Thread-Safe
• The init( ) method is used for
– Storing it’s Configuration parameters
– Initializing the values of Servlet members
– Loading JDBC Database Drivers

Presentation Name –<Author Initial><Date> Page 44 HTC Confidential


3.2.2.Life Cycle of Servlets

• After initialization, it’s service( ) method is called


for 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 bulk
of the business logic

Presentation Name –<Author Initial><Date> Page 45 HTC Confidential


3.2.2.Life Cycle of Servlets

• Servlets run until they are removed from the


service (Un-loading / Shutting down)
• The destroy( ) method is invoked for performing
clean 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

Presentation Name –<Author Initial><Date> Page 46 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

Presentation Name –<Author Initial><Date> Page 47 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 from
the WEB Browser (all the HTML Form elements
and their values)
• HTTP Servlets responds a HTML Page back to the
Browser

Presentation Name –<Author Initial><Date> Page 48 HTC Confidential


3.2.3.A Sample HTTP Servlet

• The following HTML Page accepts your Name


and submits a request to a Servlet named
“HelloWorldServlet” present in your PC:
<HTML>
<BODY>
<FORM action=“/HelloWorldServlet”>
Enter Your Name : <INPUT type=“TEXT” name=“USER” value=“”>
<INPUT type=“SUBMIT” value=“GO”>
</FORM>
</BODY>
</HTML>

Presentation Name –<Author Initial><Date> Page 49 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

Presentation Name –<Author Initial><Date> Page 50 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( “<HTML><BODY><H1>Hello World!!</H1>” +
“<H2>By ” + req.getParameter( “USER” ) +
“ of ” + companyName +
“</H2></BODY></HTML>” );
out.close( );
} //End of service( ) method
} // End of Hello World Servlet

Presentation Name –<Author Initial><Date> Page 51 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

Presentation Name –<Author Initial><Date> Page 52 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

Presentation Name –<Author Initial><Date> Page 53 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

Presentation Name –<Author Initial><Date> Page 54 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 );
…...
}

Presentation Name –<Author Initial><Date> Page 55 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 made
available (a required network connection can not be
established), or some other initialization error occurs,
an “UnavailableException” is thrown
– The “UnavailableException extends “ServletException”

Presentation Name –<Author Initial><Date> Page 56 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 Servlet’s
configuration file(web.xml) and assigning it’s value to a
member called “companyName”
– Version 2.1 of the Servlet API offers an no-args init( )
method which is called by GenericServlet's
init(ServletConfig) method
– It is not mandatory to include the init( ), but, is good
practice to do so

Presentation Name –<Author Initial><Date> Page 57 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 member
called “companyName” for garbage collection
– It is not mandatory to include the destroy( ), but is
good practice to do so

Presentation Name –<Author Initial><Date> Page 58 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 Engine
for each client request

Presentation Name –<Author Initial><Date> Page 59 HTC Confidential


3.2.4.HTTP Servlet - Anatomy

• Hello World Servlet - service( )


– A separate Thread is spawned by the Servlet Engine to
service each request
– The service( ) method is invoked implicitly by the
container to call either call doGet/doPost that is
suitable for the given request
– The doGet( ) and the doPost( ) methods should only to
be used in place of service( ) method whenever
subclasses of HttpServlet are designed
– There 6 methods like
doPut(),doDelete(),doTrace(),doOptions(),doPost(),
doGet() matching to the type of http requests,all of
which are called service methods

Presentation Name –<Author Initial><Date> Page 60 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 the
Client Browser
– For redirecting to an another URL

Presentation Name –<Author Initial><Date> Page 61 HTC Confidential


3.2.4.HTTP Servlet - Anatomy

• Hello World Servlet - service( )

– We are getting the value of a Request parameter


called “USER” using the getParameter( ) method of the
HttpServletRequest object

– We are using the above value and the


“companyName” obtained from the init( ) method to
form the Dynamic HTML page as a response

Presentation Name –<Author Initial><Date> Page 62 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 PrintWriter
Object using the getWriter( ) method of the
HttpServletResponse object
– We are using the println( ) method of the PrintWriter
Object to write HTML information on to the Client
Browser

Presentation Name –<Author Initial><Date> Page 63 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

Presentation Name –<Author Initial><Date> Page 64 HTC Confidential


3.2.5.HTTP Servlet-Session Management
• Session Management is the process of
maintaining persistence and State Information
• Session Management is required because HTTP is
by default, stateless
• Session Management is easily used for User
Authentication across requests within the same
session
• Session Management is used for Caching re-
usable information

Presentation Name –<Author Initial><Date> Page 65 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 to
a 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

Presentation Name –<Author Initial><Date> Page 66 HTC Confidential


3.2.5.HTTP Servlet - Session Management
• In session tracking,HttpSession defines methods
which can extract the following types of data:
– Standard session properties, such as an identifier for
the session, authenticity of the session and the context
for the session
– Application layer data stored using a dictionary-like
interface
– Using getAttribute(),setAttribute() client’s specific data
can be stored or retrieved

Presentation Name –<Author Initial><Date> Page 67 HTC Confidential


3.2.5.HTTP Servlet - Session Management
• The following code snippets describe
Session 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” );

Presentation Name –<Author Initial><Date> Page 68 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

Presentation Name –<Author Initial><Date> Page 69 HTC Confidential


3.2.6.ServletContext and ServletConfig

• The “ServletContext” and the “ServletConfig”


interfaces of javax.servlet package are used for
– getting the server environment information
– getting servlet’s initialization parameters
– passing configuration information to the servlet engine
– logging Events
– accessing a other servlet deployed in the same
container

Presentation Name –<Author Initial><Date> Page 70 HTC Confidential


3.2.6.ServletContext and ServletConfig

• The following code snippet describe external


Access of a Servlet’s members:
RequestDispatcher rd =
this.getServletContext( ).getRequestDispatcher(/servlet/other” );
rd.forward(request,response);

• first, the “ServletContext” is obtained from the


servlet itself and then a handle to the external
Servlet is obtained from this “ServletContext” as
an Object of RequestDispatcher

Presentation Name –<Author Initial><Date> Page 71 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

Presentation Name –<Author Initial><Date> Page 72 HTC Confidential


3.2.7.HTTP Servlet - Cookies

• Cookies are very useful in maintaining state


variables on the WEB
• A cookie is simply a text-file that consists of a
text-only string which gets stored and maintained
by the browser
• Cookies are unique named, and have a single
value with settable life(with optional attributes,
including comment, path and domain qualifiers
for the hosts which see the cookie, a maximum
age, and a version)

Presentation Name –<Author Initial><Date> Page 73 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 HTTP
header, it is kept at the browser for fast retrieval
so that any request that goes to the same
server,the browser will attach all live coockies of
that server along with the request
• Cookies are by default have a life spanning to
client’s session

Presentation Name –<Author Initial><Date> Page 74 HTC Confidential


3.2.7.HTTP Servlet - Cookies

• Browser settings allow rejection of Cookies, so,


the programmer needs to be careful in the usage
of Cookies
• Applications that use cookies include:
• Storing user preferences
• Personalization
• Automating low security user sign-on
• Collecting data used for "shopping cart" style
applications

Presentation Name –<Author Initial><Date> Page 75 HTC Confidential


3.2.7.HTTP Servlet - Cookies

• Cookies can be set and retrieved at Client-side


using JavaScript / VBScript
• HTTP Servlets support setting, retrieval and
manipulation 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 and
manipulating Cookies

Presentation Name –<Author Initial><Date> Page 76 HTC Confidential


3.2.7.HTTP Servlet - Cookies

• The following code snippets describe the


usage 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( ) );
}

Presentation Name –<Author Initial><Date> Page 77 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

Presentation Name –<Author Initial><Date> Page 78 HTC Confidential


3.2.8.Sevlet Configuration file
• Servlet’s all deployment information is made available to
the container in the web configuration file web.xml.the
following are the important elements in this regard
<servlet>
<servlet-name>…..</servlet-name>
<servlet-class>……</servlet-class>
<init-param>
<param-name>……..</param-name>
<param-value>………</param-value>
</init-param>
</servlet>

Presentation Name –<Author Initial><Date> Page 79 HTC Confidential


3.2.8.Sevlet Configuration file
• <servlet-mapping>
<servlet-name>…..</servlet-name>
<url-pattern>/……</url-pattern>
</servlet-mapping>
• <context-param>
<param-name>…..</param-name>
<param-value>……</param-value>
</context-param>

Presentation Name –<Author Initial><Date> Page 80 HTC Confidential


3.2.8.Sevlet Configuration file
• <session-config>
<session-timeout>1800</session-timeout>
</session-config>
• <filter>
<filter-name>…….</filter-name>
<filter-class>…….</filter-class>
</filter>
• <filter-mapping>
<filter-name>…….</filter-name>
<servlet-name>…….</servlet-name>
</filter-mapping>

Presentation Name –<Author Initial><Date> Page 81 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

Presentation Name –<Author Initial><Date> Page 82 HTC Confidential


3.2.9.servlet resource access
• Any other resources that are there on the application
server 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
• <resource-ref>
<res-ref-name>*</res-ref-name>
<res-type>….</res-type>
<res-auth>….<res-auth>
</resource-ref>

Presentation Name –<Author Initial><Date> Page 83 HTC Confidential


3.2.9.servlet resource access
• This is referred and accessed in servlet code from
the jndi InitialContext object as

InitialContext ctx=new InitialContext();


resource-type-class
obj=ctx.lookup(“java:comp/env/*”);

Presentation Name –<Author Initial><Date> Page 84 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

Presentation Name –<Author Initial><Date> Page 85 HTC Confidential


3.2.9.1.filter,filter-mappings

• A “ Filter ” can perform filtering on client’s request for a


resource like a servlet/static content or on a response that
goes from a resource.they are majorly used for
authentiction,logging,auditing,xml based
transformations,to fire events…..
• Any class that implement Filter interface have to give code
for 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 chained
filters

Presentation Name –<Author Initial><Date> Page 86 HTC Confidential


3.2.9.1.filter,filter-mappings

• The FilterConfig object allows the Filter class to


access any of the configured initial parameters
that can be given in web.xml within <filter> tag
• The associated methods are
• getInitParameterNames()
• getInitParameter()
• getServletContext()
• filter-mappings are given in web.xml file to tell
the container what filters are there for the
requested uri and in what order

Presentation Name –<Author Initial><Date> Page 87 HTC Confidential


3.2.JSP
What do JSPs contain?
• Java Server Pages are text files that combine standard
HTML/XML and new scripting tags
• JSPs look like HTML/XML ,but they got compiled into Java
servlets the first time they are invoked
• The resulting servlet is a combination of the HTML from
the JSP file and embedded dynamic content specified by
the 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

Presentation Name –<Author Initial><Date> Page 88 HTC Confidential


3.2.JSP

• JSP Life Cycle:-


Intialize
public void jspInit()
|
handle client request s and generate responses
void_jspService(ServletRequest,ServletResponse)throws
IOException,ServletException
|
Destory
public void jspDestory()

Presentation Name –<Author Initial><Date> Page 89 HTC Confidential


3.2.JSP

• Directives
• Declarations
• Scriptlets
• Expressions
• Standard actions

Presentation Name –<Author Initial><Date> Page 90 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 same
page together
– <%@ page attributes %>

Presentation Name –<Author Initial><Date> Page 91 HTC Confidential


3.2.JSP - Directive

• various attributes of page directive are:-


• language
• extends
• import
• session
• buffer
• autoFlush
• isThreadSafe
• info
• isErrorPage
• errorPage
• contentType

Presentation Name –<Author Initial><Date> Page 92 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 this
happens only at translation time.
– The included file should not be another dynamic page.
– Most JSP containers usually keep track of the included file and
recompile the JSP if it changes
– <%@ include file=“Filename” %>
– Atttibute:-
• file (the static filename to include)

Presentation Name –<Author Initial><Date> Page 93 HTC Confidential


3.2.JSP - Directives

• 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 it
comes across the custom tags in the JSP
– <%@ taglib uri=“tagLibraryURI” prefix==“tagPrefix” %>

– Attributes are:-
– uri
– prefix

Presentation Name –<Author Initial><Date> Page 94 HTC Confidential


3.2.JSP – Scripting Elements

• 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

Presentation Name –<Author Initial><Date> Page 95 HTC Confidential


3.2.JSP - Declarations

• 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
• <%! Java variables and method declaration(s)….%>
• Ex:-
<%! double radius =90;
double area ()
{
return (3.14 * radius * radius);
}
%>

Presentation Name –<Author Initial><Date> Page 96 HTC Confidential


3.2.JSP - Scriptlets

• A Scriptlet is a block of java code that is


executed at request-processing time

• Can produce output to the client

• <% java code statements ……… %>


• ex:-
<% out.println(“Welcome to JSP”); %>

Presentation Name –<Author Initial><Date> Page 97 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
• <%= java expression to be evaluated %>
• Ex:-
<%! int i=0 ; %>
<%
i++
%>
<%= “JSP page has been accesssed”+ i +”times” %>

Presentation Name –<Author Initial><Date> Page 98 HTC Confidential


3.2.JSP – Standard Actions

• Actions are specific tags that affect the runtime


behaviour of the JSP and affect the response sent back
to the client
• Standard Action types are:-
• Use Bean
• Set Property
• Get Property
• Param
• Params
• Include
• Forward
• Plug-in

Presentation Name –<Author Initial><Date> Page 99 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

Presentation Name –<Author Initial><Date> Page 100 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:plugin
actions
• Jsp:include
– Allows a static or dynamic resource to be included in the current
JSP at request time
• Jsp:forward
– Allows the request to be forwarded to another JSP,a servlet
• Jsp:plugin
– Meant to dynamically load the browser’s plugin jdk software
either to run an applet or gui-bean

Presentation Name –<Author Initial><Date> Page 101 HTC Confidential


3.2.JSP – Implicit objects
• These objects do not be declared or instantiated by the JSP
author, but are provided by the container in the implementation
class
• All the implicit objects are available only to scriptlets or
declarations , 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

Presentation Name –<Author Initial><Date> Page 102 HTC Confidential


3.2.JSP 2.0 EL

• Expressions appear between ${ and }.


– Note that ${ and } may contain whole expressions,
not just variable names, as in the Bourne shell (and its
dozen derivatives.)
– E.g., ${myExpression + 2}
• Expressions’ default targets are scoped
attributes (page, request, session,
application)
– ${duck} ≡ pageContext.findAttribute(“duck”)

Presentation Name –<Author Initial><Date> Page 103 HTC Confidential


3.2.JSP 2.0 EL
• 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 concern
themselves with types in most cases (even though the underlying types
of data objects are preserved.)

Presentation Name –<Author Initial><Date> Page 104 HTC Confidential


3.2.JSP 2.0 EL

• Expressions may also refer to cookies, request


parameters, and other data:
– ${cookie.crumb}
– ${param.password}
– ${header[“User-Agent”]}
– ${pageContext.request.remoteUser}

Presentation Name –<Author Initial><Date> Page 105 HTC Confidential


3.2.JSP 2.0 EL

• 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. Useful
for ${empty param.x}

Presentation Name –<Author Initial><Date> Page 106 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

Presentation Name –<Author Initial><Date> Page 107 HTC Confidential


3.3.Tag Libraries – Introduction
• 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 application
functionality to be invoked without the need to
write the java code in JSP scriptlets
• It is used to encapsulate java functionality that
can be used from a JSP page
• Well-designed tag libraries can enable application
functionality to be invoked without the
appearance of programming

Presentation Name –<Author Initial><Date> Page 108 HTC Confidential


3.3.Tag Libraries

• Types of tag
• Predefined Tag
• Customized Tag
– Predefined Tag
– Functionality provided implicitly by container.
– Example
» <jsp:useBean/>
» <jsp:setProperty/>

Presentation Name –<Author Initial><Date> Page 109 HTC Confidential


3.3.Tag Libraries

• Customized Tag
– Functionality provided by the programer.
– Example
• <connection:getProducts/>
• The above codes connects to a database and get the
product list.
– Advantage
• The web page developer can concentrate on the
content rather than business logic.
• Access to implicit object.(details later)

Presentation Name –<Author Initial><Date> Page 110 HTC Confidential


3.3.Tag Libraries

• Any valid custom tag should contain :


– A reference in Tag Library Descriptor
– A Tag Handler Class
– Tag Handler
– Its the class which provides the java
functionality for that particular tag.
– Tag Library Descriptor
– Contains various Tags
– Links Tags with Handler Classes

Presentation Name –<Author Initial><Date> Page 111 HTC Confidential


3.3.Tag Libraries

• 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

Presentation Name –<Author Initial><Date> Page 112 HTC Confidential


3.3.Tag Libraries

• Types of Tag:--
• Simple Tag (No Body,No Attribute).
• Simple Tag With Attributes.
• Tag With Body.
• Nested Tag.

Presentation Name –<Author Initial><Date> Page 113 HTC Confidential


3.3.Tag Libraries-Simple tag
• A simple tag is without attributes or tag bodies
• They are of the form <prefix:tagname />
• Example:- HelloWorld.jsp
<%@ taglib uri="/TagCollection.tld" prefix="greet"/>
<html>
<body>
<greet:sayHello/>
</body>
</html>

Presentation Name –<Author Initial><Date> Page 114 HTC Confidential


3.3.Tag Libraries- Simple tag
HelloWorld.java
• Tag Handler Class
public class HelloWorld extends SimpleTagSupport
{
public void doTag() throws JspTagException
{ // this method is called when the start is encountered
pageContext.getOut.write("Hello World");
// pageContext is object provided by container through
// implicit objects can be created and used.
}
}

Presentation Name –<Author Initial><Date> Page 115 HTC Confidential


3.3.Tag Libraries- Simple tag

TagCollection.tld

Tag Library Descriptor :---

<tag>
<name>sayHello</name> // Name of the Tag used in Jsp
<tagclass>HelloWorld</tagclass> // Name of Tag Handler Cl
<bodycontent>empty</bodycontent>
</tag>

Presentation Name –<Author Initial><Date> Page 116 HTC Confidential


3.3.Tag Libraries-Tags with attribute

• Adds flexibility to your tag library


• Allowing tags like
<prefix:name attribute1=“value1” attribute2=“value2” …./>
Example:--
AttribTag.jsp prefix="Hello"/>
<%@ taglib uri="/TagCollection.tld"
<html>
<body>
<Hello:input name="Gokul"/>
</body>
</html>

Presentation Name –<Author Initial><Date> Page 117 HTC Confidential


3.3.Tag Libraries- Tags with attribute

import javax.servlet.http.*; TagAttrib.java


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);
}
}

Presentation Name –<Author Initial><Date> Page 118 HTC Confidential


3.3.Tag Libraries- Tags with attribute
TagCollections.tld
<tag>
<name>input</name>
<tagclass>TagAttrib</tagclass>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<bodycontent>empty</bodycontent>
</tag>

Presentation Name –<Author Initial><Date> Page 119 HTC Confidential


3.3.Tag Libraries -Tag with Body

• This tag is used in the following manner


<prefix:tagname>body</ prefix:tagname>
• Example:--
<greet:sayHello>
<B> This is a Body Tag // Content can be
</greet:sayHello> Jsp,HTML.
• The Handler class implement BodyTag
interface.Support class is BodyTagSupport.
• You have additional methods
doAfterBody(),doInitBody() in Tag class

Presentation Name –<Author Initial><Date> Page 120 HTC Confidential


3.3.Tag Libraries-Tag with Body

Example:--Hello.jsp
<html>
<head>
<title>Untitled</title>
</head>
<body>
<%@ taglib uri="\web-inf\HelloTag.tld“ prefix="Greet"%>
<Greet:HelloWithBody count=”5”>
Amazing Body
</Greet:HelloWithBody>
</body>
</html>

Presentation Name –<Author Initial><Date> Page 121 HTC Confidential


3.3.Tag Libraries-Tag with Body
The TagHandler class extends BodyTagSupport {
setPageContext(){} // container sets the
pagecontext
setParent() // sets the parent in case of nested tag
set the attributes using setMethods
doStartTag() // Executed when the starting tag is
encountered should return EVAL_BODY_TAG
setBodyContent() // to set the current BodyContent
for it to use (if there is at least one evaluation of the
body of the BodyTag).
doInitBody() // This is where we will normally put any
instructions that should be taken care of before the
body of the BodyTag is evaluated for the first time.

Presentation Name –<Author Initial><Date> Page 122 HTC Confidential


3.3.Tag Libraries-Tag with Body

doAfterBody() // called after each evaluation of the


body.If this method returns EVAL_BODY_TAG, this
method should be called again. If this method
returns SKIP_BODY, continue below.
doEndTag() //called when the ending tag is
encountered.
release()
}

Presentation Name –<Author Initial><Date> Page 123 HTC Confidential


3.3.Tag Libraries-Tag with Body
Tag Handler class
package 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;
}

Presentation Name –<Author Initial><Date> Page 124 HTC Confidential


3.3.Tag Libraries-Tag with Body
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;
}
}

Presentation Name –<Author Initial><Date> Page 125 HTC Confidential


3.3.Tag Libraries-Tag with Body
Tag Library Descriptor File
<tag>
<name>HelloWithBody</name>
<tagclass>htc.HelloWithBody</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>

Presentation Name –<Author Initial><Date> Page 126 HTC Confidential


3.3.Tag Libraries-Nested Tags

• 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 nested
tags
• To define a tag that depend on a particular
nesting order
– For ex:-in standard HTML, the TD and TH elements
can only appear within TR, which in turn can only
appear within TABLE

Presentation Name –<Author Initial><Date> Page 127 HTC Confidential


3.3.Tag Libraries-Nested Tags
• Tag Handler Classes
– Can be extended from either TagSupport or
BodyTagSupport, depending on whether they need to
manipulate their body content(these extend
BodyTagSupport ) or just ignore it(these extend
TagSupport )
• There are two new approaches for nested tags
– First, nested tags can use findAncestorWithClass to find
the instance of a given class type that is closest to a
given instance.

Presentation Name –<Author Initial><Date> Page 128 HTC Confidential


3.3.Tag Libraries-Nested Tags
• 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 nested
class can throw a JspTagException that reports the
problem
• 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 provide
methods for storing and accessing this data

Presentation Name –<Author Initial><Date> Page 129 HTC Confidential


3.3.Tag Libraries-Iteration Tags
• The IterationTag interface extends Tag by defining one
additional method that controls the reevaluation of its body.
• A tag handler that implements IterationTag is treated as one
that implements Tag regarding the doStartTag() and
doEndTag() methods. IterationTag provides a new method:
doAfterBody().
• The doAfterBody() method is invoked after every body
evaluation to control whether the body will be reevaluated or
not.
• If doAfterBody() returns IterationTag.EVAL_BODY_AGAIN,
then the body will be reevaluated. If doAfterBody() returns
Tag.SKIP_BODY, then the body will be skipped and
doEndTag() will be evaluated instead.

Presentation Name –<Author Initial><Date> Page 130 HTC Confidential


3.3.Tag Libraries-Tag Extra Info Classes
• Optional class provided by the tag library author to
describe additional translation-time information not
described 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 override
two methods
– VariableInfo[ ] getVariableInfo(TagData data)
– Used to return information on scripting variables that the tag makes
available to JSPs using it
– Returns an array of VariableInfo objects, which contain information
about the name of each scripting variable and its fully qualified class
name

Presentation Name –<Author Initial><Date> Page 131 HTC Confidential


3.3.Tag Libraries-Tag Validation

Presentation Name –<Author Initial><Date> Page 132 HTC Confidential


3.3.Tag Libraries-Tag Extra Info Classes

boolean isValid(TagData data)
 used for Translation-time validation of the
attributes.
Request-time attributes are indicated as such in
the TagData parameter.

Presentation Name –<Author Initial><Date> Page 133 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

Presentation Name –<Author Initial><Date> Page 134 HTC Confidential


3.4.Struts

• Framework
– set of multiple classes,interfaces,components aimed at solving
specific 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 client’s
request w/o sending any response which is totally
handled by view component i.e jsps

Presentation Name –<Author Initial><Date> Page 135 HTC Confidential


3.4.Struts
• Struts is made up of approximately 300 java classes
divided 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 commons
package,separate from struts

Presentation Name –<Author Initial><Date> Page 136 HTC Confidential


3.4.Struts
• In struts framework the Controller component functionality is
divided by more than one component,one of which is
org.apache.struts.action.ActionServlet class whose main
function is to receive the client’s request and process it
through a handler class i.e RequestProcessor class in 1.1
version,meant for flexibility to subclass.after this it delegates
the handling of the request to a helper class which is a
subclass of org.apache.struts.action.Action so that
decoupling client-request & business-logic takes place.
• Subclasses of Action class should give code for
public ActionForward
execute(ActionMapping,ActionForm,HttpServletRequest,Http
ServletResponse) as the framework creates a singleton of
this and invoke its execute method since the super class the
method returns null.

Presentation Name –<Author Initial><Date> Page 137 HTC Confidential


3.4.Struts

• the ActionServlet class will be configured in


web.xml which is the single one that will invoke
suitable action Objects as per the input form the
important initial parameters for this servlet are
– configlocation of struts-config.xml file
– config/sub to specify additional configuration files
– debugcontrols how much info is to be logged
– detaildetail level for Digestor,which logs info as it
parses the configuration files
– convertHacka boolean variable whether any Wrapper
class variables are to be initialized to null(if true default
is false) or default value of their type

Presentation Name –<Author Initial><Date> Page 138 HTC Confidential


3.4.Struts

• the Action class will be configured in


struts-config.xml within <action-mappings> blocks
as action element with following important
attributes
– attributename of session-scope attribute under which
form-bean can be accessed
– classNamethe implementation class,by default
ActionMapping
– forwardthe application-relative path to a resource to
which further navigation occur.the attributes
forward/include/type are mutually exclusive
– Input application-relative path of the input form to
which control should go if a validation error occur

Presentation Name –<Author Initial><Date> Page 139 HTC Confidential


3.4.Struts
– namethe name of the form-bean associated with this
action.this value should one of name attribute of the
form-bean elements defined already
– paththe application-relative path to the submitted
request,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
– typefully qualified javaclass name
– validatedetermines whether validate() method is
invoked by the form-bean or not default is true

Presentation Name –<Author Initial><Date> Page 140 HTC Confidential


3.4.Struts

• Types of Action classes


– Dispatch Actions mean for abstracting multiple actions
in a single class instead of scattering over multiple
action classes useful particularly when actions are
related and focussed on an entity like sale of
product,updation of its price,viewing the details of it
typical implementation as many named methods that
return suitable ActionForward object.the configuration
contains parameter attribute with method and method
name is used in the url like
http://localhost:8080/myappl/sales?method=sellProduct

Presentation Name –<Author Initial><Date> Page 141 HTC Confidential


3.4.Struts

• Types of Action classes


– Forard Actions useful where the controller will simply
forward from one jsp page to another jsp page without
specific processing by Action class no specifical Action
class writing is necessary.the type attribute will be
org.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 web
applications.type attribute will have
org.apache.struts.actions.IncludeAction and the url is
given by the parameter attribute

Presentation Name –<Author Initial><Date> Page 142 HTC Confidential


3.4.Struts

• Types of Action classes


– Switch Actions this is intended to support switching
from one application-module to another particularly
when you can configure more than one configuration file
requires a prefix request parameter that gives the
application prefix.if wanted to switch to the default ,you
can use zero-length string as “”.the page request
parameter should be there that gives the relative path.
Only required if you have more than one module.The
type is org.apache.struts.actions.SwitchAction

Presentation Name –<Author Initial><Date> Page 143 HTC Confidential


3.4.Struts

• Form-Beans
these are meant to take care of storing the user’s given
input data and transfer them to the Action/subclasses(in
execute method)validating the input and display errors in
case of validation failure.these are written as extending
ActionForm class.
• These can have two levels of scope
– requestform-bean is available till the response is returned
to the client
– sessionnecessary if application captures data across
multiple pages and will be there till the session is timed out

Presentation Name –<Author Initial><Date> Page 144 HTC Confidential


3.4.Struts

• these are created as subclasses of ActionForm(which is


abstract) to capture an application-specific form-data.within
the class you should define a property for each field that is
going to be received through the html form with accessor &
mutator methods.it may contain a validate() method which
RequestProcessor class calls as well as reset() method,since
the reset method is called for every new request particulary
if default scope ie session is in effect,so that the bean fields
are set back to their defaults.
• These are configured under form-bean element under form-
beans element,contains two required attributes a)name
should match to that of action element’s b)type should
have full packaged path of form class

Presentation Name –<Author Initial><Date> Page 145 HTC Confidential


3.4.Struts

• Dynamic ActionForms will avoid exclusive writing of


subclasses as you can configure the simple properties in
configuration file itself for ex
<form-beans><form-bean name=“loginForm”
type=“org.apache.struts.action.DynaActionForm”><form-
property name=“uname” type=“java.lang.String”
initial=“Mr.X” /> … </form-bean></form-beans>
But if validate method is to be implementation,another class
has to be written only for that,since by default reset(0
method is taken well care of

Presentation Name –<Author Initial><Date> Page 146 HTC Confidential


3.4.Struts
• Struts Validator
struts framework allows to skip validation in actionforms
and done through David winterfeldt’s validator
framework.this will allow to configure.the framework rules
are available in validator-rules.xml the other file is
validation.xml which is application-specific as it describes
which validation rules from the above xml file are being
used by the application for ex:<form-validation>
<formset>
<form name=“loginForm”><field property=“uname”
depends=“required,mask”>…………….
</field>
</form>
</formset></form-validation>

Presentation Name –<Author Initial><Date> Page 147 HTC Confidential


3.4.Struts

• Struts Validator
all the above ,we can call as server-side
validation.for client-side validation you can use
customTag called JavascriptValidator based on
the javascript code available in validator-rules.xml
when the JavascriptValidator is used in the jsp file
the text from the javascript element is made
available to the jsp page allowing client-side
validation there should be in the jsp
<html:javascript formName=“myForm*” />
<html:form action=“checkin”
onSubmit=“return validateMyForm(this)” >

Presentation Name –<Author Initial><Date> Page 148 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

Presentation Name –<Author Initial><Date> Page 149 HTC Confidential


3.5.Struts-Tag Libraries
->The struts framework provides a fairly rich set of
framework components
->It also includes a set of tag libraries that are
designed to interact intimately with the rest of the
framework
->The custom tags provided by struts are grouped
into:-
HTML Tags
Bean Tags
Logic Tags
Nested Tags
Tiles Tags

Presentation Name –<Author Initial><Date> Page 150 HTC Confidential


3.5.Struts-Tag Libs-HTML tag

• 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 this
library
• These tags are designed to work with the other
components of the Struts framework,including
ActionForms
• Most of the tags within this library must be
nested inside of a Struts form tag

Presentation Name –<Author Initial><Date> Page 151 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• Custom tags within the Struts HTML tag
Library are:-
• <html:base/>
• < html:button/>
• <html:cancel/>
• < html:checkbox/>
• <html:errors/>
• < html:file/>
• <html:form/>
• < html:hidden/>
• <html:html/>
• < html:image/>

Presentation Name –<Author Initial><Date> Page 152 HTC Confidential


3.5.Struts-Tag Libs-HTML tag

• Custom tags within the Struts HTML tag Library


are (continued):-
• <html:javascript/>
• < html:link/>
• <html:messages/>
• < html:option/>
• <html:options/>
• < html:password/>
• <html:radio/>
• < html:reset/>
• <html:select/>
• < html:submit/>
• <html:text/>
• < html:textarea/>

Presentation Name –<Author Initial><Date> Page 153 HTC Confidential


3.5.Struts-Tag Libs-HTML tag

• <html:base />
– Used to insert an HTML <base> element ,including an
href pointing to the absolute location of the hosting
JSP page
– Has no body and supports two attributes(optional)
• <html:button />
– Used to render an HTML <input> element with an
input type of button
– Has a body type of JSP
– Required attribute are: property,title

Presentation Name –<Author Initial><Date> Page 154 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:cancel />
– Used to render an HTML <input> element with an input
type of cancel
– Has a body type of JSP and supports 25 attributes
– Required attributes are:- title
• <html:checkbox />
– Used to render an HTML <input> 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 <html:form />tag

Presentation Name –<Author Initial><Date> Page 155 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:errors />
– Used to display the ActionError objects stored in an
ActionErrors collection
– Has a body type of JSP and supports four
attributes(optional)
• <html:file />
– Used to create an HTML <file> 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 <html:form />tag

Presentation Name –<Author Initial><Date> Page 156 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:form/>
– Used to create an HTML form
– has a body type of JSP and supports 13 attributes
– Required attributes are :- action
• <html:hidden/>
– Used to render an HTML<input> element with an input type
of hidden
– Has a body of JSP and supports 25 attributes
– Required attributes are :- property,title
– Must be nested inside the body of an<html:form/>tag

Presentation Name –<Author Initial><Date> Page 157 HTC Confidential


3.5.Struts-Tag Libs-HTML tag

• <html:javascript/>
– Used to insert an custom JavaScript validation
methods
– has no body and supports 8 attributes
– No required attributes are there
• <html:link/>
– Used to generate an HTML hyperlink
– Has a body type of JSP and supports 37 attributes
– Required attributes are :- title

Presentation Name –<Author Initial><Date> Page 158 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:messages/>
– Used to display a general-purpose messages to the
user stored in ActionMessages,ActionErrors etc
– has a body type of JSP and supports 8 attributes
– Required attributes are :- id
• <html:option/>
– Used to generate an HTML<input> element of
type<option>, which represents a single option
element nested inside a parent <select> element
– Has a body type of JSP and supports 8 attributes
– Required attributes are :- value

Presentation Name –<Author Initial><Date> Page 159 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:options/>
– Used to generate a list of HTML<option>elements
– Child of the <html:select />tag
– has no body and supports 8 attributes
– Required attributes are :- action
– Must be nested inside an<html:select/>tag
– Can also be used n-number of times within an html:select/>element
• <html:password/>
– Used to render an HTML<input> element with an input type of
password
– Has a body type of JSP and supports 31 attributes
– Required attributes are :- property,title
– Must be nested inside the body of an<html:form/>tag

Presentation Name –<Author Initial><Date> Page 160 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:radio/>
– Used to render an HTML<option>element with an input
type of radio
– has a body of type JSP and supports 28 attributes
– No required attributes are :-property, value, title
– Must be nested inside an<html:form />tag
• <html:reset/>
– Used to render an HTML<input> element with an input
type of reset
– Has a body type of JSP and supports 25 attributes
– No required attributes are there

Presentation Name –<Author Initial><Date> Page 161 HTC Confidential


3.5.Struts-Tag Libs-HTML tag

• <html:select/>
– Used to render an HTML<input>element with an input
type of select
– has a body type of JSP and supports 28 attributes
– No Required attributes are there
• <html:image/>
– Used to render an HTML<input> 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 an<html:form/>tag

Presentation Name –<Author Initial><Date> Page 162 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:html/>
– Used to render the top-level<html>element
– has a body type of JSP and supports 2 attributes
– Required attributes are :- property, title
– Must be nested inside the body of an<html:form/>tag
• <html:submit/>
– Used to render an HTML<input> 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 an<html:form/>tag

Presentation Name –<Author Initial><Date> Page 163 HTC Confidential


3.5.Struts-Tag Libs-HTML tag
• <html:text/>
– Used to render an HTML<input> element with an input
type of text
– has a body type of JSP and supports 30 attributes
– Required attributes are :- property, title
– Must be nested inside the body of an<html:form/>tag
• <html:textarea/>
– Used to render an HTML<input> 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 an<html:form/>tag

Presentation Name –<Author Initial><Date> Page 164 HTC Confidential


3.5.Struts Tag Libs-Bean tag

• Bean Tag library provides a group of tags that


encapsulates the logic necessary to access and
manipulate JavaBeans,HTTP cookies and HTTP
headers using scripting variables
• There are currently 11 custom tags in the Bean
tag library
• Custom tags are:-
• <bean:cookie/>
• <bean:define/>
• <bean:header/>
• <bean:include/>

Presentation Name –<Author Initial><Date> Page 165 HTC Confidential


3.5.Struts Tag Libs-Bean tag

Custom tags are:- (continued)


• < bean:message/>
• <bean:page/>
• <bean:parameter/>
• <bean:resource/>
• <bean:size/>
• <bean:struts/>
• <bean:write/>

Presentation Name –<Author Initial><Date> Page 166 HTC Confidential


3.5.Struts Tag Libs-Bean tag
• <bean:cookie />
– 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
• <bean:define />
– Used to retrieve the value of a named bean property and
define it as a scripting variable,which will be stored in the
scope specified by the toScope attribute
– It has a body type of JSP and supports 7 attributes
– Required attributes are :- id

Presentation Name –<Author Initial><Date> Page 167 HTC Confidential


3.5.Struts Tag Libs-Bean tag
<bean:header />
• It functions exactly like <bean:cookie/> except that it
retrieves its values from the named request header
• It has a body type of JSP and supports 4 attributes
• Required attributes are:- id, name
<bean:include/>
• Used to evaluate and retrieve the results of a Web
application resource
• The tag functions much like the <jsp:include>
standard action, except that the response is stored in
a page scoped object attribute, as opposed to being
written to the output stream

Presentation Name –<Author Initial><Date> Page 168 HTC Confidential


3.5.Struts Tag Libs -Bean tag

• <bean:page/>
• Used to retrieve the value of an identified implicit
JSP object, which it stores in the page context of
the 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:-
– <bean:page id=“sessionVar” property=“session”/>
– We are retrieving the implicit session object and storing
this reference in the scripting variable sessionVar

Presentation Name –<Author Initial><Date> Page 169 HTC Confidential


3.5.Struts Tag Libs -Bean tag

• <bean:parameter/>
• Used to retrieve the value of a request parameter
identified by the name attribute
• The retrieved value will be used to define a page
scoped 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:-
– <bean:parameter id=“userId”
name=“username” value=“User Not Found” />

Presentation Name –<Author Initial><Date> Page 170 HTC Confidential


3.5.Struts Tag Libs -Bean tag

• <bean:resource/>
• Used to retrieve the value of Web application
resource identified by the name attribute
• Has no body and supports 3 attributes
• Required attributes are :- id, name
• <bean:size/>
• Used to retrieve the number of elements contained
in a reference to an array, collection,or map
• Has no body and supports 5 attributes
• Required attributes are:- id

Presentation Name –<Author Initial><Date> Page 171 HTC Confidential


3.5.Struts Tag Libs -Logic tag

• Contains tags that are useful for managing


conditional genaration of output text, looping over
object collections for repetitive generation of
ouput text, and application flow management
• So the focus of the logic tag library is on decision
making and object evaluation
• Logic tag library contains:-
• <logic: empty/>
• <logic: notEmpty/>
• <logic: equal/>
• <logic: notEqual/>

Presentation Name –<Author Initial><Date> Page 172 HTC Confidential


3.5.Struts Tag Libs -Logic tag
• Logic tag library contains (coninued)
• <logic:forward />
• <logic: redirect/>
• <logic: greaterEqual/>
• <logic: greaterThan/>
• <logic: iterate />
• <logic: lessEqual />
• <logic: lessThan />
• <logic: match />
• <logic: notMatch />
• <logic: present />
• <logic: notPresent />

Presentation Name –<Author Initial><Date> Page 173 HTC Confidential


3.5.Struts Tag Libs -Logic tag

• <logic:empty/>
• Evaluates its body if either the scripting variable identified
by the name attribute or a property of the named
scripting variable is equal to null or an empty string
• Has a body type of JSP and supports 3 attributes
• Required attributes are:- name
• Ex:--
<logic:empty name=“user”>
<forward name=“login” /> </logic:empty>
We test the scripting variable user .if this variable is null or
an empty string , then the body will be evaluated, which
will result in the user being forwarded to the global
forward login

Presentation Name –<Author Initial><Date> Page 174 HTC Confidential


3.5.Struts Tag Libs -Logic tag

• <logic:notEmpty />
• it is just opposite of <logic:empty /> tag
• <logic:equal/>
• Evaluates its body if either the variable specified by any one
of the attributes cookie, name, parameter, or property
equals the constant value specified by the value attribute
• Has a body type of JSP and supports 7 attributes
• Required attributes are:- value
• Ex:-- <logic:equal name=“user” property =“age”
value=“<%= requiredAge %>”>
You are exactly the right age. </logic:equal>
We test the age data member of the scripting variable
user.If this data member equals the value stored in the
requiredAge variable, then the tag’s body will be evaluated

Presentation Name –<Author Initial><Date> Page 175 HTC Confidential


3.5.Struts Tag Libs -Logic tag
• <logic:notEqual />
• it is just opposite of <logic:notEqual /> tag
• <logic:forward/>
• 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 receive
control of the request
• Ex:-<logic:forward name=“login” />
– We forward the current request to the global forward
login
<global-forward>
<forward name=“login” path=“/login.jsp” />
</global-forward>

Presentation Name –<Author Initial><Date> Page 176 HTC Confidential


3.5.Struts Tag Libs -Logic tag

• <logic:redirect/>
• uses the HttpServletResponse.sendRedirect()
method to redirect the cuttent request to a
resource identified by either the forward,href ,or
page attributes
• Has no body and supports 12 attributes (optional)
• <logic:greaterEqual/>
• Evaluates its body if the variable specified by any
one of the attributes cookie, name,parameter, or
property 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

Presentation Name –<Author Initial><Date> Page 177 HTC Confidential


3.5.Struts Tag Libs -Logic tag

– <logic:greaterThan/>
– <logic:lessEqual/>
– <logic:lessThan/>
• Simmilar to <logic:greaterEqual/> tag
• <logic:iterate>
• Used to iterate over a named collection and evaluates
its body for each Object in the collection
• Has a body type of JSP and supports 9 attributes
• Requred attributes are:- id

Presentation Name –<Author Initial><Date> Page 178 HTC Confidential


3.5.Struts Tag Libs -Logic tag

• <logic:match/>
• Evaluates its body if the variable contains the
specified constant value
• Has a body type of JSP and supports 8 attributes
• Required attributes are :- value
• <logic:notMatch /> tag is just opposite of match
tag
• <logic:present/>
• Evaluates its body if the variable specified is present
in the application scope
• Has a body type of JSP and supports 8 attributes
(optional)
• <logic:notPresent /> tag is just opposite of present
tag

Presentation Name –<Author Initial><Date> Page 179 HTC Confidential


3.5.Struts Tag Libs -Nested tag
• In nested tags you can use one tag inside
another tag that belong to the
“html”,”bean”,”logic” groups with little confusion
with the necessity of making the child element
aware of the parent element

Presentation Name –<Author Initial><Date> Page 180 HTC Confidential


3.5.Struts Tag Libs -Tiles tag
• The tiles tag library give page designers a mechanism
that allows them to componentize and therefore reuse
existing JSP components
• To create reusable presentation components
• Custom tags are:-
• <tiles:insert />
• <tiles:definition/>
• <tiles:put/>
• <tiles:putList/>
• <tiles:add/>
• <tiles:get/>

Presentation Name –<Author Initial><Date> Page 181 HTC Confidential


3.5.Struts Tag Libs -Tiles tag
• Custom tags are (continued)
• <tiles:getAsString/>
• <tiles:useAttribute />
• <tiles:importAttribute/>
• <tiles:initComponentDefinitions/>
• <tiles:insert/>
• Used to insert a Tiles template into a JSP.
• You must use the<itles:put/>, tiles:putList/> tags to
substitute sub-components of the tile being inserted
• Has a body type of JSP and supports 14
attributes(optional)

Presentation Name –<Author Initial><Date> Page 182 HTC Confidential


3.5.Struts Tag Libs -Tiles tag
• <tiles:definition/>
• Used to create a JavaBean representation of a Tiles
template definition that is stored in the named scope
bound to the identifier named by the id attribute
• Has a body type of JSP and supports 6 attributes
• Required attributes are :- id
• <tiles:put/>
• Used to define the equivalent of a parameter ,
representing a sub-component of a template, that will be
passed to the Tiles object
• Has a body type of JSP and supports 8 attributes
• No required attributes are there

Presentation Name –<Author Initial><Date> Page 183 HTC Confidential


3.5.Struts Tag Libs -Tiles tag
• <tiles:putList/>
• Used to define a list of parameters that will be
passed as attributes to the Tiles object
• The list is created from a collection of
child<tiles:add/> tags
• Has a body type of JSP and supports a single
attribute
• Required attribute is:- name
• <tiles:add/>
• Used to add parameters to a parameter as defined
by a <tiles:putList/> tag
• Has a body type of JSP and supports 7 attributes
• No required attributes are there

Presentation Name –<Author Initial><Date> Page 184 HTC Confidential


3.5.Struts Tag Libs -Tiles tag
• <tiles:get/>
• Used to retrieve and insert parameters previously
defined from the Tiles context
• With the exception of the ignore attribute being
defaulted to true, this tag is functionally the same
as the <tiles:insert/> tag
• Has no body content and supports 4 attributes
• Required attributes are :- name

Presentation Name –<Author Initial><Date> Page 185 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

Presentation Name –<Author Initial><Date> Page 186 HTC Confidential


3.6.JSTL 1.0 features

• control flow
– Iteration, conditions
• URL management
– Retrieve data, add session IDs
• text formatting and internationalization
– Dates and numbers
– Localized messages
• xml manipulation
– XPath, XSLT
• database access
– Queries, updates

Presentation Name –<Author Initial><Date> Page 187 HTC Confidential


3.6.JSTL 1.0 libraries

Library features Recommended prefix

Core (control flow, URLs, c


variable access)
Text formatting fmt
XML manipulation x

Database access sql

Presentation Name –<Author Initial><Date> Page 188 HTC Confidential


3.6.JSTL features: managing variables
• Outputting values with EL
<c:out value=”${user.IQ}” />

• Storing data
<c:set var=”user”
scope=”session”>
// arbitrary text
</c:set>

Note the use of “var” and “scope”: a JSTL convention

Presentation Name –<Author Initial><Date> Page 189 HTC Confidential


3.6.JSTL features: iteration

• Iteration

<c:forEach items=”${list}”
begin=”5” end=”20” step=”4”
var=”item”>
<c:out value=”${item}”/>
</c:forEach>

• “paging”

Presentation Name –<Author Initial><Date> Page 190 HTC Confidential


3.6.JSTL features: conditional logic

• Conditional evaluation • Mutually exclusive conditionals


<c:choose>
<c:if test=”${a == b}”> <c:when test=”${a == b}”>
a equals b a equals b
</c:if> </c:when>
<c:when test=”${a == c}”>
a equals c
</c:when>
<c:otherwise>
I don’t know what ’a’ equals.
</c:otherwise>
</c:choose>

Presentation Name –<Author Initial><Date> Page 191 HTC Confidential


3.6.JSTL features:URL management

• Retrieving data
<c:import var=”cnn”
url=”http://www.cnn.com/cnn.rss”/>
– Data exposed as String or Reader
– All core URLs supported (HTTP, FTP, HTTPS with JSSE)
– Local, cross-context imports supported

• Printing URLs
<c:url value=”/foo.jsp”>
• Redirection
<c:redirect url=”/foo.jsp”>

Presentation Name –<Author Initial><Date> Page 192 HTC Confidential


3.6.JSTL features: text formatting

• Locale-sensitive formatting and parsing


– Numbers
– Dates
<fmt:formatNumber type=“currency”
• Internationalization value=“${salary}” />
– Message bundles
• Message argument substitution
<fmt:message
– “Hi {0}. I would like to {1} your moneykey=“welcome”
today. I will/>
use it to buy myself a big {2}.”

Presentation Name –<Author Initial><Date> Page 193 HTC Confidential


3.6.JSTL features: XML manipulation

• Use of XPath to access, display pieces of


XML documents
<c:import url=”http://www.cnn.com/cnn.rss” var=”cnn”/>
<x:parse xml=”${cnn}” var=“dom”>
<x:out value=”$dom//item[1]/title”/>

• Chaining XSLT transformations


<x:transform xslt=”${xsl2}” />
<x:transform xml=”${xml}” xslt=”${xsl}” />
</x:transform>

Presentation Name –<Author Initial><Date> Page 194 HTC Confidential


3.6.Advantages of JSTL XML/XPath
support

• Why not always use XSLT?


– JSTL integrates XPath with convenient,
standard access to Java/JSP code.
• E.g., parse an article URL out of a
document, then follow the URL and parse
its contents.
– JSP/JSTL may be more familiar and
convenient for simple tasks.
• Functional versus imperative
programming

Presentation Name –<Author Initial><Date> Page 195 HTC Confidential


3.6.JSTL features:database manipulation

• Queries (and ResultSet caching)


• Updates / inserts
• Transactions (<sql:transaction>)
• Parametric (PreparedStatement) argument
substitution (<sql:param>)
• DataSource-based connection management

Presentation Name –<Author Initial><Date> Page 196 HTC Confidential


3.6.SQL tags: the debate

Tag
library

Back-end
Java
JSP
Database
code page
Tag
library

Presentation Name –<Author Initial><Date> Page 197 HTC Confidential


3.6.SQL Tags: The expert group’s conclusion

• SQL tags are needed because…


– many nonstandard offerings exist
– it is not JSTL’s role to dictate a choice of framework
• As popular as MVC is, it’s not universal.
• Even in an MVC application, not all data is worth
handling carefully.
– prototyping is important
– users ask for it!
• The JSTL specification recommends avoidance
of SQL tags in large applications.

Presentation Name –<Author Initial><Date> Page 198 HTC Confidential


3.6.JSTL programmer support

• JSTL also supports Java developers


– Simplifies tag development
– IteratorTagSupport, ConditionalTagSupport
– Instead of writing whole tag handler (doStartTag(),
doEndTag()), simply override a few methods:
• protected boolean condition()
• protected Object next()
– Still, JSP 2.0 is probably easier.
• Ugly JSP 1.1 tag protocol  Ugly JSP 1.1 tag
protocol with assistance from JSTL 1.0  Nice JSP
2.0 tag protocol.

Presentation Name –<Author Initial><Date> Page 199 HTC Confidential


3.6.JSTL programmer support

• JSTL API allows registrations of defaults…


– DataSource
– Limit on size of results
– Localization context (Locale, etc.)
– Time zone

Presentation Name –<Author Initial><Date> Page 200 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

Presentation Name –<Author Initial><Date> Page 201 HTC Confidential


3.7.XML

• XML is extended markup language meant for


mainly for the following in B2B/B2C models
• data-submission
• data-exchange
• content transformations
• Xml is also being used for storing configuration
informations in the web-work
• Because of user-defined model,lot of it’s derived
languages are in the market like
wml,cml,mml,bml

Presentation Name –<Author Initial><Date> Page 202 HTC Confidential


3.7.XML

• following are the main features of xml


• unicode based
• contains well formed tags called as “elements”
• all elements are to start with alpha-numeric
characters and may contain only “ . “ and “ – “
among special characters
• files are to saved with “.xml extension
• the file should contain one root element
• all elements in are to be well-formed and there are
no empty tags as in html
• extremely case-sensitive & syntax-sensitive

Presentation Name –<Author Initial><Date> Page 203 HTC Confidential


3.7.XML

• xml files are to be well-formed meaning the


elements and their children are to properly closed
in the order in which they are opened. An
element element is defined as
opening-tag content closing-tag
<name> velan </name>
• attributes are added to define more particulars
about a particular element in its opening tag as
“ name=value “ pairs. any number of attributes
can be used in an element and all of them are to
be given in the opening tag of the element.

Presentation Name –<Author Initial><Date> Page 204 HTC Confidential


3.7.XML

• Entities: these are substituable content given in


xml files
– Internal entity: when want to insert special content
that has special characters like ‘ & ‘ or ‘ > ‘ you can
use syntax &….; for ex:
• to get ‘ & ’ use “ &amp; ”
• to get ‘ > ’ use “ &gt; ”
• to get ‘ < ‘ use “ &lt; “
• to get ‘ “ ‘ use “ &quot; “
• to get ‘ ` ‘ use “ &apos; “

Presentation Name –<Author Initial><Date> Page 205 HTC Confidential


3.7.XML

– External entity: when want to insert repeatabing and reusable


content you can use these.These are first are to be defined in the
dtd file like
<!ENTITY aaaa “……………………………” > or if the content is
available in an external file <!ENTITY aaaa SYSTEM
“c:\gen\….txt” > in the xml file content has to be given as “
&aaaa; “
– attribute entity: these are meant to simplefy the dtd writing when
multiple elements are going to have the same set of
attributes.these are defined in different way like using
<!ENTITY % attrs “color CDATA #IMPLIED
gender CDATA #IMPLIED “ > for the element you can attach
attributes <!ATTLIST zzzz %attrs; >
<!ATTLIST vvvv %attrs; >

Presentation Name –<Author Initial><Date> Page 206 HTC Confidential


3.7.XML

DTD
This is to validate an associated xml file in regard to what Elements
are to be there and in what order and how many times they are
to be,what list of attributes, an element can have,what entities
are to mean etc.These are linked to xml files through document
type descriptors
It will have general syntax indicating what is the parent and its
children like <!ELEMENT abcd
(a,b,c,d) > meaning abcd parent element can have elements
a,b,c,d in order one each by default .if it is a leaf element,you can
give <!ELEMENT d (#PCDATA) > .
if element is to be allowed either as a leaf or child elements under
it use then <!ELEMENT c ANY >
if element is not to have either content or child elements under it
use then <!ELEMENT c EMPTY >

Presentation Name –<Author Initial><Date> Page 207 HTC Confidential


3.7.XML

DTD
How many times an element can be there is indicated by
the occurrence indicator that can be given on right to
the element.they can be
!  once or none
*  none or more
+  once or more
Attributes
these are much better ones to control of their content in
xml than elements but disadvantage is that they are not
rendered or visible when rendering takes place on
application of a cascading stylesheets.they are given as
<!ATTLIST b “bAttr1 CDATA #IMPLIED ….” > here
CDATA means the character data is not going to parsed.

Presentation Name –<Author Initial><Date> Page 208 HTC Confidential


3.7.XML

DTD
After CDATA you can give the following that puts
adjectives to the attributes
. #REQUIRED  meaning that the attribute is to be there
. ID #REQUIRED  meaning that the attribute is to be
there and it should not have duplicates within the page.
. #IMPLIED  may be given or not
. #FIXED  always takes a constant value which should
also be given here only
attributes can also be provided permissible set of values
with a default value in the dtd itself like
<!ATTLIST a class (B.sc|B.A|B.com|BCA) “BCA” >
Entities are already discussed above

Presentation Name –<Author Initial><Date> Page 209 HTC Confidential


3.7.XML

Namespaces
in an xml file you can use elements of more than one
source dtd utilizing a prefix that points to uri, that is
defined in the root element.the usage of prefix in xml
for certain elements will be validated with that
corresponding dtd file.this are called namespaces as the
parser clearly distinguishes between elements that have
prefix and those that belong to the given dtd in the file
actually namespaces are used mainly to embed html in
xml which is called XHTML like
<student
xmlns:HTML="http://www.w3.org/TR/XHTML1/strict">
then html elements are used with <HTML:br/>

Presentation Name –<Author Initial><Date> Page 210 HTC Confidential


3.7.XML

XSD
is these are written in xml way and included in the main
Function is similar to DTD in that it validates an xml file
of its contents and developed and standardized
recently.the main deference xml file using namespaces
like
<pur20
xmlns:xsi="http://www.w3.org/2000.10.XMLSchema-
instance“
xsi:noNamespaceSchemaLocation="pur20.xsd">
similar to dtd files saved with “.dtd ” extension,these are
saved with “ .xsd ” extension

Presentation Name –<Author Initial><Date> Page 211 HTC Confidential


3.7.XML

XSD
in XSD files which will have a structure similar to xml files
a mention is to be given to the schema url the file is
referring and the (preferrably) prefix you are referring to
like
<xsd:schema
xmlns:xsd="http://www.w3.org/2000/10/XMLSchema">
the parent elements will be indicated as
<xsd:complexType name=“abcd”> under which the child
elements are referred as
<xsd:element name=“a”> if one or if multiple enclosed
within <xsd:sequence>…</xsd:sequence> elements

Presentation Name –<Author Initial><Date> Page 212 HTC Confidential


3.7.XML

XSD
The leaf elements are defined along with the type
of content they can hold like
<xsd:element name=“c” type=“xsd:integer” />
you can virtually declare any datatype that can
be like xsd:string/xsd:double/xsd:date…. Along
with no of times it can occur using the attributes
minOccurs and maxOccurs(which can have a
value of unlimited)
the attributes are to be given following the
element using <xsd:attribute with name and
type attributes

Presentation Name –<Author Initial><Date> Page 213 HTC Confidential


3.7.XML

Xml parsing
There are two types of parsers that are available
a). syntax validators:: these will ensure case,whitespace
and well-formedness of an xml file
b). dtd/schema validators::these will ensure whether a
particular xml file is as per their declared dtd/xsd files or
not
java is having powerful api by which an xml file can be
read/parsed resulting in derived values or manipulation
of the file this api is called jaxp and recent versions(>1.4
& above)hava amalgamated these with the main jdk.the
related packages are
rg.w3c.dom..,org.xml.sax…,javax.xml,javax.xml.parsers,j
avax.xml.namespaces,javax.xml.transform…,javax.xml.x
path etc
Presentation Name –<Author Initial><Date> Page 214 HTC Confidential
3.7.XML

xml parsing-DOM
when jaxp uses DocumentBuilder for parsing,the
entire file will be available in memory as an
elemental tree,to enable the programmer to
navigate and manipulate it like inserting a
node,replace a node,modify a node or deleting a
node using the methods available in the
org.w3c.dom.Node like
getChildNodes(),getAttributes(),getFirstChild(),
getLastChild(),getNodeName(),getNodeType(),
getNodeValue(),insertBefore(),removeChild(),rep
laceChild(),setNodeValue()
Presentation Name –<Author Initial><Date> Page 215 HTC Confidential
3.7.XML

xml parsing-DOM
in this type of parsing first an instance of
DocumentBuilderFactory is created like
DocumentBuilderFactory
docF=DocumentBuilderFactory.newInstance();
then an object of DocumentBuilder is created like
DocumentBuilder dBuilder=docF.newDocumentBuilder();
then given file is parsed after getting InputSource/File
object out of it
File f1=new File(args[0]);
Document doc=dBuilder.parse(f1);

Presentation Name –<Author Initial><Date> Page 216 HTC Confidential


3.7.XML

xml parsing-SAX
SAX means simple api for xml and it uses a SAXParser to
parse an xml file which will be event-driven to enable a
programmer to catch them and use the content.this
parser has to be set with a handler class object in which
the events are written to utilize the content this is
abstracted by the ContentHandler interface,other
handler interfaces are also there like
EntityResolver,ErrorHandler,DTDHandler which will
handle various elements you encounter in parsing an
xml file.There is a general class DefaultHandler which
implements all above interfaces which you can extend
and create an object of it and set the handler for the
SAXParser class Object

Presentation Name –<Author Initial><Date> Page 217 HTC Confidential


3.7.XML

xml parsing-SAX
Useful methods of these interfaces are
ContentHandler:: (),startPrefixMapping(),
startDocument(),startElement(),
characters(),endElement(),
processingInstruction(),endDocument()
ErrorHandler:: warning(),error(),fatalError()
EntityResolver::resolveEntity()
DTDHandler:: notationDecl(),unparsedEntityDecl()

Presentation Name –<Author Initial><Date> Page 218 HTC Confidential


3.7.XML

xml parsing-SAX
in this type of parsing, first an object of
SAXParserFactory is created like
SAXParserFactory
spf=SSAXParserFactory.newInstance();
SAXParser sParser=spf.newSAXParser();
InputSource source=new InputSource(new
FileInputStream(“test.xml”)
sParser.parse(source,handler object));

Presentation Name –<Author Initial><Date> Page 219 HTC Confidential


3.7.XML

JAXB-XML Beans
java architecture for xml-binding is meant to convert an xml
representation of info into java classes.the schema-
derived classes and the api allows you primarily allow you
ease of manipulation of content and again can marshall
the changed contents into an XML file.it is an advantage
for people who are more good with java and less with
xml.
you can do unmarshalling using the xjc compiler that
comes with java web development kit like
>xjc –p samp student.xsd
here “samp” is the package into which .java files are
placed.suppose “student” is the root element.Each class
that is generated will be similar as java-bean with similar
accessor and mutator methods
Presentation Name –<Author Initial><Date> Page 220 HTC Confidential
3.7.XML

JAXB-XML Beans
the above command will generate java classes which are
to compiled to be used in the program.any modications
can be done through a java program for unmarshalling
and marshalling back to a changed xml file by means of
the class “ javax.xml.bind.JAXBContext “ like
JAXBContext jxb=JAXBContext.newInstance(“samp”);
javax.xml.bind.Unmarshaller can be got through
Unmarshaller um=jxb.createUnmarshaller();
to get a tree of java content objects in memory under the
root element
Student stu=(Student)um.unmarshall(“students.xml”);

Presentation Name –<Author Initial><Date> Page 221 HTC Confidential


3.7.XML

JAXB-XML Beans
after making any changes to the objects that are
there in the tree ,which can be done by normal
invocation of class methods on the objects,you
can once again you can marshall the tree as a
different xml
javax.xml.bind.Marshaller can be got through
Marshaller m=jxb.createMarshaller();
You can marshall the xml file to any storage or to
the console output
m.marshall(stu,System.out);

Presentation Name –<Author Initial><Date> Page 222 HTC Confidential


3.7.XML

XSLT-XPATH
XSLT is a xml stylesheet transformation language
meant for converting xml documents into other
formats like xml of a different structure,html, wml
and predominanly used to convert xml into html.
an xsl file is to be written indicating how the
transformer has to read the elements and convert
them into html tags(any other based on the
target),having the root element like
<xsl:stylesheet
xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”
>
you can tell what output will be
<xml:output method=“xml” />

Presentation Name –<Author Initial><Date> Page 223 HTC Confidential


3.7.XML

XSLT-XPATH
XSl is a set of template rules.a template has two components a
pattern means xpath, a way to pickup elements or sub-elements
and a template that can instantiated to form part of the result
tree.
<xsl:template match=“/” > meaning to pickup the root element or
a sub element like
<xsl:template match=“students/student” or “//student”>
in the template tag ,you can mention how other templates given
separately can be applied using
<xsl:apply-templates select=“……” />
this ‘select’ attribute value should be matching the ‘match’ attribute
given at the top.you can use html/xml tags freely in these
templates

Presentation Name –<Author Initial><Date> Page 224 HTC Confidential


3.7.XML

XSLT-XPATH
for putting the content of leaf elements you can use
either for ex:name element
<xsl:apply-templates select=“name/text()” /> or
<xsl:value-of select=“.” /> the
following other important elements ,you can use
<xsl:for-each> meant for iteration over a large
number of same elements
<xsl:if match=“…..”> used to process on reaching a
condition,the ‘match’ attribute tells how the element’s
content is matched to a value
<xsl:choose><xsl:when match=“..”><xsl:otherwise>
is used like if..else if…in programming

Presentation Name –<Author Initial><Date> Page 225 HTC Confidential


3.7.XML

XSLT-XPATH
<xsl:sort select=“..” />used in association
with <xsl:for-each …> enable to sort group of
elemental output based on a particular child
element’s values
<xsl:copy> very useful in xml-xml
transformations to copy a bunch of elements
from one place to another.

Presentation Name –<Author Initial><Date> Page 226 HTC Confidential


3.7.XML

XSLT-XPATH
you can use jaxp to complete the transformation in the following
way.get an instance of
TransformerFactory TransformerFactory
tFactory=TransformerFactory.newInstance();
Get the transformer using the above xsl file say ‘students.xsl’ as
Transformer transformer=tFactory.newTransformer(new
StreamSource(new File(“students.xsl”)))
call transform method to get the converted html file
programmatically
Result res=new StreamResult(new FileWriter(“students.html”));
Source src=new StreamSource(new File(“students.xml”));
transformer.transform(src,res);

Presentation Name –<Author Initial><Date> Page 227 HTC Confidential


3.7.XML

XSLT-XPATH
Xpath is a language that consists path expressions.the
value of a path expression is a node set which is
mostly relevant in XSLT.other expressions like what is
used in ‘match’ attribute evaluate to boolean and
‘select’ attribute values used for leaf elements can
evaluate to numeric or string values.
location paths consists of
Axistells the direction like ancestor/ancestor-or-
self/attribute/child/descendant/descendant-or-
self/following/following-
sibling/namespace/parent/preceding/preceding-
sibling/self

Presentation Name –<Author Initial><Date> Page 228 HTC Confidential


3.7.XML

XSLT-XPATH
Node-testsa node test is mostly a element’s
name or attribute node for ex:
child::class picks up all class child elements of
the current context node.
if child::* is used all child elements of the
current context node.
node test text() is true only for leaf/text node
comment(), processing-instruction() for any
associated comment,processing instructions

Presentation Name –<Author Initial><Date> Page 229 HTC Confidential


3.7.XML

XSLT-XPATH
Abbreviationsthese can replace lengthy
expressions above.::child is the default axis
Abbreviation Meaning Example
@ ::attribute [@color=“blue”]
// ::descendant .//address
[number] [position()=nu student[5]
mber]
. self::node() ./student[5]

.. Parent::node() ../student[5]

Presentation Name –<Author Initial><Date> Page 230 HTC Confidential


3.7.XML

XSL-FO
It is extensible stylesheet language formatting
objects to provide an alternate way of
rendering xml file content in a similar way as
css/css2.this is a xml-based formatting
vocabulary meant for display on a range of
devices,it is more complex than css
XSL-FO output is produced from an XML source
document in two steps
a).an XSLT transformation to add FO markup
b).actual formatting step.

Presentation Name –<Author Initial><Date> Page 231 HTC Confidential


3.7.XML

XSL-FO
In this process first a set of formatting objects tree is
created after which a tree of areas is created.these
areas then get rendered may not be linearly
always.the generated files will hava “.fo” suffix and
the elements will have a “fo” prefix for its elements
important among the list of elements are
<fo:root
xmlns:fo=“http://www.w3.org/1999/XSL/Format” >
<fo:block>,<fo:simple-page-master>,<fo:page-
sequence-master><fo:region-after>, <fo:region-
before>, <fo:region-body>, <fo:region-end>,
<fo:region-start>, <fo:footnote><fo:list-
block>,<fo:list-item>,<fo:list-item-body>,<fo:list-
item-label>
Presentation Name –<Author Initial><Date> Page 232 HTC Confidential
3.7.XML

XSL-FO
<fo:table>,<fo:table-and-caption>,<fo:table-
body><fo:table-caption><fo:table-
cell><fo:table-column><fo:table-footer>
<fo:table:header><fo:table-row>
there is Antenna House XSL Formatter to view
the XSL-FO files
Apache is having a FOP that can convert xml
to pdf using XSL-FO

Presentation Name –<Author Initial><Date> Page 233 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

Presentation Name –<Author Initial><Date> Page 234 HTC Confidential


3.8.Junit – Introduction
What is JUnit?
JUnit is an open source Java testing framework
used to write and run repeatable tests.
 It is an instance of the xunit architecture for
unit testing frameworks.
JUnit features include:
• Assertions for testing expected results
• Test fixtures for sharing common test data
• Test suites for easily organizing and running tests
• Graphical and textual test runners
JUnit was originally written by Erich Gamma
and Kent Beck.

Presentation Name –<Author Initial><Date> Page 235 HTC Confidential


3.8.Junit- Installation.
• steps for installing JUnit:
1. unzip the junit.zip file
2. add junit.jar to the CLASSPATH. For example: set
classpath=%classpath
%;INSTALL_DIR\junit3\junit.jar (should have any
task-defined classes)
3. test the installation by using either the batch or
the graphical TestRunner tool to run the tests that
come with this release. All the tests should pass
OK.

Presentation Name –<Author Initial><Date> Page 236 HTC Confidential


3.8.Junit -
Installation(continued)
Notice: that the tests are not contained in the junit.jar
but in the installation directory directly. Therefore
make sure that the installation directory is on the
class path
• for the batch TestRunner type:
    java junit.textui.TestRunner junit.samples.AllTests
• for the graphical TestRunner type:
    java junit.awtui.TestRunner junit.samples.AllTests
• for the Swing based graphical TestRunner type:
    java junit.swingui.TestRunner junit.samples.AllTests
• Important: don't install the junit.jar into the
extension directory of your JDK installation. If you do
so the test class on the files system

Presentation Name –<Author Initial><Date> Page 237 HTC Confidential


3.8.Junit – test case

• A test case defines the fixture to run multiple


tests. To define a test case
1) implement a subclass of TestCase
2) define instance variables that store the state of
the fixture
3) initialize the fixture state by overriding setUp()
4) clean-up after a test by overriding tearDown().
Each test runs in its own fixture so there can be
no side effects among test runs

Presentation Name –<Author Initial><Date> Page 238 HTC Confidential


3.8.Junit – test case

How to write and run a simple test?


1.Create a subclass of TestCase: ---
package junitfaq;
import java.util.*;
import junit.framework.*;
public class SimpleTest extends TestCase {
public SimpleTest(String name) {
super(name);
}

Presentation Name –<Author Initial><Date> Page 239 HTC Confidential


3.8.Junit – test case
2. Write a test method to assert expected results on
the object under test: ---
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
3. Write a suite() method that uses reflection to
dynamically create a test suite containing all the
testXXX() methods: ---
public static Test suite() {
return new TestSuite(SimpleTest.class);
}

Presentation Name –<Author Initial><Date> Page 240 HTC Confidential


3.8.Junit - test case
4. Write a main() method to conveniently run the
test with the textual test runner: ---
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}

Presentation Name –<Author Initial><Date> Page 241 HTC Confidential


3.8.Junit - test case

5. Run the test: ---


– To run the test with the graphical test runner, type: --
java junit.swingui.TestRunner junitfaq.SimpleTest
– The passing test results in a green bar displayed in the
graphical UI.

Presentation Name –<Author Initial><Date> Page 242 HTC Confidential


3.8.Junit - TestSuite

• A TestSuite is a Composite of Tests. It runs a collection of


test cases
• Here is an example using the dynamic test definition.
– TestSuite suite= new TestSuite();
– suite.addTest(new MathTest("testAdd"));
– suite.addTest(new MathTest("testDivideByZero"));
• a TestSuite can extract the tests to be run automatically. To
do so you pass the class of your TestCase class to the
TestSuite constructor.
– TestSuite suite= new TestSuite(MathTest.class);
• This constructor creates a suite with all the methods
starting with "test" that take no arguments

Presentation Name –<Author Initial><Date> Page 243 HTC Confidential


3.Advanced java contents-1

– 3.1.Servlets
– 3.4.Struts
– 3.2.JSP
– 3.3.Tag Libraries
– 3.5.Struts-Tag Libraries
– 3.6.JSTL
– 3.7.XML
– 3.8.Junit
– 3.9.Ant

Presentation Name –<Author Initial><Date> Page 244 HTC Confidential


3.9.Ant – Introduction
• What is ant ?
– Ant is a Java based build tool. In theory it is
kind of like "make" without makes wrinkles
and with the full portability of pure Java code.
• Why do you call it Ant ?
– According to Ant's original author James Duncan
Davidson, the name is an acronym for "Another Neat
Tool".
– Later explanations go along the lines of "Ants are
doing an extremely good job at building things" or
"Ants are very small and can carry a weight a dozen
times of their own" - describing what Ant is intended
to be.

Presentation Name –<Author Initial><Date> Page 245 HTC Confidential


3.9.Ant - History
• Initially Ant was part of the Tomcat code base when it was
donated to the Apache Software Foundation - it has been
created by James Duncan Davidson, who also is the
original author of Tomcat. Ant was there to build Tomcat,
nothing else.
• Soon thereafter several open source Java projects realized
that Ant could solve the problems they had with makefiles.
Starting with the projects hosted at Jakarta and the old
Java Apache project, Ant spread like a virus and now is the
build tool of choice for a lot of projects.
• In January 2000 Ant was moved to a separate CVS module
and was promoted to a project of its own, independent of
Tomcat.

Presentation Name –<Author Initial><Date> Page 246 HTC Confidential


3.9.Ant - History(continued)
• The first version of Ant that was exposed a lager
audience was the one that shipped with Tomcat's 3.1
release on 19 April 2000. This version has later been
referenced to as Ant 0.3.1.
• The first official release of Ant as a stand alone
product was Ant 1.1 released on 19 July 2000.
• The complete release history:
• Ant Version Release Date
• 1.1 19 July 2000
• 1.2 24 October 2000
• 1.3 3 March 2001

Presentation Name –<Author Initial><Date> Page 247 HTC Confidential


3.9.Ant -Installing Ant

• The binary distribution of Ant consists of three


directories:
» bin
» docs
» lib
• Only the bin and lib directories are required to run
Ant.
• To install Ant, choose a directory and unzip the ant
distribution zip file .
• This directory will be known as ANT_HOME

Presentation Name –<Author Initial><Date> Page 248 HTC Confidential


3.9.Ant - Installing Ant

• Before you can run ant there is some additional set


up you will need to do:
– Add the bin directory to your path.
– Set the ANT_HOME environment variable to the
directory where you installed Ant.
– Optionally, set the JAVA_HOME environment variable .
This should be set to the directory where your JDK is
installed.Keep the tools.jar in the classpath
– Do not install Ant's ant.jar file into the lib/ext directory
of the JDK/JRE

Presentation Name –<Author Initial><Date> Page 249 HTC Confidential


3.9.Ant
• Windows
• Assume Ant is installed in c:\apache-ant\. The
following sets up the environment:
– set ANT_HOME=c:\ apache- ant
– set JAVA_HOME=c:\jdk1.4.2
– set PATH=%PATH%;%ANT_HOME%\bin

Presentation Name –<Author Initial><Date> Page 250 HTC Confidential


3.9.Ant - Running Ant
• Running Ant is simple, when you installed it as
described in the previous slides. Just type ant.
• When nothing is specified, Ant looks for a
build.xml file in the current directory. If found, it
uses that file as the buildfile. If you use the -find
option, Ant will search for a buildfile in the parent
directory, and so on, until the root of the
filesystem has been reached.
• To make Ant use another buildfile, use the
command-line option -buildfile file, where file is
the buildfile you want to use.

Presentation Name –<Author Initial><Date> Page 251 HTC Confidential


3.9.Ant - Running Ant
• Command-line option summary:---
ant [options] [target [target2 [target3] ...]]
• Options: -
-help print this message
-projecthelp print project help information
-version print the version information and exit
-quiet be extra quiet
-verbose be extra verbose
-debug print debugging information
-emacs produce logging information without adornments
-logfile file use given file for log output
-logger classname the class that is to perform logging
-listener classname add an instance of class as a project listener
-buildfile file use specified buildfile
-find file search for buildfile towards the root of the
filesystem and use the first one found
-Dproperty=value set property to value
Presentation Name –<Author Initial><Date> Page 252 HTC Confidential
3.9.Ant – Using Ant

Writing a Simple Buildfile


Ant's buildfiles are written in XML.
 Each buildfile contains one project.
Each task element of the buildfile can have
an id attribute and can later be referred to by the
value supplied to this. The value has to be unique

Presentation Name –<Author Initial><Date> Page 253 HTC Confidential


3.9.Ant – Using Ant
TASK
A task is a piece of code that can be executed.
A task can have multiple attributes.
Tasks have a common structure:---
<name attribute1="value1" attribute2="value2" ... />
name is the name of the task
attributeN is the attribute name
 valueN is the value for this attribute
Tasks can be assigned an id attribute:
<taskname id="taskID" ... />
taskname is the name of the task
taskID is a unique name for this task

Presentation Name –<Author Initial><Date> Page 254 HTC Confidential


3.9.Ant - Core Task

• Ant
– Runs Ant on a supplied buildfile. This can be used to
build subprojects.
– When the antfile attribute is omitted, the file
"build.xml" in the supplied directory (dir attribute) is
used.
– If no target attribute is supplied, the default target of
the new project is used
– No required attributes are there

Presentation Name –<Author Initial><Date> Page 255 HTC Confidential


3.9.Ant – core task

• Mkdir
– Creates a directory. Also non-existent parent directories
are created, when necessary.
– Parameters
• Required Attribute s are :- dir
» the directory to create.
– Examples
• <mkdir dir="${dist}"/>
– creates a directory ${dist}.
• <mkdir dir="${dist}/lib"/>
– creates a directory ${dist}/lib.

Presentation Name –<Author Initial><Date> Page 256 HTC Confidential


3.9.Ant – core task
• Copy
– Copies a file or Fileset to a new file or directory.
– Files are only copied if the source file is newer than the
destination file, or when the destination file does not
exist.
– However, you can explicitly overwrite files with the
overwrite attribute
– Examples:--
Copy a single file
<copy file="myfile.txt" tofile="mycopy.txt"/>
Copy a file to a directory
<copy file="myfile.txt" todir="../some/dir/tree"/>

Presentation Name –<Author Initial><Date> Page 257 HTC Confidential


3.9.Ant – core task
Examples:--
Copy a directory to another directory
<copy todir="../new/dir">
<fileset dir="src_dir"/>
</copy>
Copy a set of files to a directory
<copy todir="../dest/dir" >
<fileset dir="src_dir" >
<exclude name="**/*.java"/>
</fileset>
</copy>
<copy todir="../dest/dir" >
<fileset dir="src_dir" excludes="**/*.java"/>
</copy>

Presentation Name –<Author Initial><Date> Page 258 HTC Confidential


3.9.Ant – core task

• javac
– Compiles a Java source tree.
– The source and destination directory will be recursively
scanned for Java source files to compile.
– Only Java files that have no corresponding class file or
where the class file is older than the java file will be
compiled.
• Required attributes are :- srcdir
• location of the java files.

Presentation Name –<Author Initial><Date> Page 259 HTC Confidential


3.9.Ant – core task
Examples:--
<javac srcdir="${src}“
destdir="${build}"
classpath="xyz.jar“
debug="on"
/>
 compiles all .java files under the ${src} directory,
and stores the .class files in the ${build} directory.
The classpath used contains xyz.jar, and debug
information is on.

Presentation Name –<Author Initial><Date> Page 260 HTC Confidential


3.9.Ant – core task
• java
– Executes a Java class within the running (Ant) VM or
forks another VM if specified.
– Be careful that the executed class doesn't call
System.exit(), because it will terminate the VM and thus
Ant. In case this happens, it's highly suggested that you
set the fork attribute so that System.exit() stops the
other VM and not the one that is currently running
Ant.to avoid this you can use the attribute fork=“true” to
allow separate jvm process for your task

Presentation Name –<Author Initial><Date> Page 261 HTC Confidential


3.9.Ant – core task

• jar
– Jars a set of files.
– The basedir attribute is the reference directory from
where to jar.
– Note that file permissions will not be stored in the
resulting jarfile.
– Required Attributes are :- jarfile
» the jar-file to create.

Presentation Name –<Author Initial><Date> Page 262 HTC Confidential


3.9.Ant – core task
• Examples:--
• <jar jarfile="${dist}/lib/app.jar“ basedir="$
{build}/classes“ />
jars all files in the ${build}/classes directory into a file
called app.jar in the ${dist}/lib directory.
• <jar jarfile="${dist}/lib/app.jar" basedir="$
{build}/classes" excludes="**/Test.class" />
jars all files in the ${build}/classes directory into a
file called app.jar in the ${dist}/lib directory. Files
with the name Test.class are excluded

Presentation Name –<Author Initial><Date> Page 263 HTC Confidential


3.9.Ant – core task

• ear
– An extension of the jar task with special treatment for
files that should end up in an Enterprise Application
archive.
– (The Ear task is a shortcut for specifying the particular
layout of a EAR file.
– The same thing can be accomplished by using the
prefix and fullpath attributes of zipfilesets in a Zip or
Jar task.)
– Required attributes are :-

• earfile  the ear-file to create.


• appxml  location of application.xml file
• basedir location of files

Presentation Name –<Author Initial><Date> Page 264 HTC Confidential


3.9.Ant – core task

• War
– An extension of the jar task with special treatment for
files that should end up in the WEB-INF/lib, WEB-
INF/classes or WEB-INF directories of the Web
Application Archive.
– (The War task is a shortcut for specifying the particular
layout of a WAR file. The same thing can be
accomplished by using the prefix and fullpath attributes
of zipfilesets in a Zip or Jar task.)
– The extended zipfileset element from the zip task (with
attributes prefix, fullpath, and src) is available in the
War task

Presentation Name –<Author Initial><Date> Page 265 HTC Confidential


3.9.Ant – core task

• Required Attributes are:-


– Warfile
• the war-file to create.
– webxml
• The deployment descriptor to use (WEB-
INF/web.xml).

Presentation Name –<Author Initial><Date> Page 266 HTC Confidential


3.9.Ant – core task
• zip
– Creates a zipfile.
– The basedir attribute is the reference directory from
where to zip.
– file permissions will not be stored in the resulting
zipfile
– Required attributes are:- zipfile
» the zip-file to create.

Presentation Name –<Author Initial><Date> Page 267 HTC Confidential


3.9.Ant – core task
• Examples:--
1. <zip zipfile="${dist}/manual.zip“
basedir="htdocs/manual“
/>
zips all files in the htdocs/manual directory into a file
called manual.zip in the ${dist} directory.
2. <zip zipfile="${dist}/manual.zip"
basedir="htdocs/manual"
update="true"
/>
 zips all files in the htdocs/manual directory into a file
called manual.zip in the ${dist} directory. If manual.zip
doesn't exist, it is created; otherwise it is updated with the
new/changed files.

Presentation Name –<Author Initial><Date> Page 268 HTC Confidential


3.9.Ant – core task
3. <zip zipfile="${dist}/manual.zip"
basedir="htdocs/manual"
excludes="mydocs/**, **/todo.html“
/>
 zips all files in the htdocs/manual directory. Files in the
directory mydocs, or files with the name todo.html are
excluded.
4. <zip zipfile="${dist}/manual.zip“
basedir="htdocs/manual"
includes="api/**/*.html"
excludes="**/todo.html"
/>
zips all files in the htdocs/manual directory. Only html files
under the directory api are zipped, and files with the name
todo.html are excluded

Presentation Name –<Author Initial><Date> Page 269 HTC Confidential


3.9.Ant – core task
• Integrating Junit testing with Ant
• This will enable testing Junit framework tests from ant
environment.For this you have to put junit.jar and other
task related class files either in ANT_HOME/lib or in the
classpath or in the build file’s classpath element
• junit
– tests a testcase class.
Attributes (Optional) are
– showoutputtest’s output to Ant's logging system as well as to
the formatters(default only).
– tempdira place where ant can place temporarily generated files
– printsummaryif yes give summary of the results

Presentation Name –<Author Initial><Date> Page 270 HTC Confidential


3.9.Ant – core task
• Integrating Junit testing with Ant
there are other boolean type attributes like
‘haltonerror’ / ‘haltonfailure’/’fork’
• The following are the important nested elements
– <test name=classname outfile=……./>(required)
– <formatter type=plain/xml/brief classname=…./>
– <sysproperty key=….. value=…… />

Presentation Name –<Author Initial><Date> Page 271 HTC Confidential


3.9.Ant – core task
xdoclet:
XDoclet is an extended javadoc doclet engine. It's a
generic java tool that lets you create custom javadoc
@tags and based on those @tags generate source code
or other files (such as xml-ish deployment descriptors)
using a template engine it provides. XDoclet supports a
set of common standard tasks such as web.xml or ejb-
jar.xml generation, users and contributors can create
other templates and @tags and add support for other
technologies also.
for example weblogic created ‘javadoc’ class thar takes a
ejb-bean-class and creates all deployment descriptors
along with remote & home interfaces

Presentation Name –<Author Initial><Date> Page 272 HTC Confidential


3.9.Ant – core task
xdoclet:
examples of these are ‘ejbdoclet’ & ‘webdoclet’
which are main target tasks.the nested elements
to this task contain sub-tasks like ‘remoteinterface’
& ‘jsptaglib’ that are independently
configured.these sub-tasks create templates
having elements like<XDoclet:aaaa>.
when the component is written,lot of special
javadoc @tags are written to enable xdoclet to
generate associated xml files like ejb-jar.xml or
web.xml.for ex: (in an ejb bean class)

Presentation Name –<Author Initial><Date> Page 273 HTC Confidential


3.9.Ant – core task

xdoclet:
/** * This is an Item bean. It is an example of how to use the *
EJBDoclet tags. * * @see Items are used by multiple people to make
products
* * @ejb:bean name="bank/Account“
* type="CMP“
* jndi-name="ejb/bank/Account“
* primkey-field="id“
* @ejb:finder signature="Collection findAll()"
* unchecked="true“
* @ejb:interface remote-class="test.interfaces.Account" */
these will have generic syntax
@namespace:tag-name parameter-name="parameter value“
Tag values can be specified as ant properties. For example:
@jboss:create-table create="${jboss.create.table}"

Presentation Name –<Author Initial><Date> Page 274 HTC Confidential


3.9.Ant – core task

xdoclet:
typical ant task will appear as
<target name="ejbdoclet" depends="prepare">
<taskdef name="ejbdoclet"
classname="xdoclet.ejb.EjbDocletTask" classpath="$
{xdoclet.jar.path};${log4j.jar.path};${ant.jar.path}" />
<ejbdoclet sourcepath="$
{java.dir}" destdir="${generated.java.dir}"
classpathref="project.class.path"
excludedtags="@version,@author" ejbspec="2.0" force="$
{xdoclet.force}"> <fileset dir="$
{java.dir}"> <include
name="**/*Bean.java" />
</fileset>

Presentation Name –<Author Initial><Date> Page 275 HTC Confidential


3.9.Ant-Core Tasks
<dataobject/>
<remoteinterface/>
<localinterface/>
<homeinterface/>
<localhomeinterface/>
<entitypk/>
<entitycmp/>
<deploymentdescriptor destdir="${build.dir}/ejb/META-
INF"/> <jboss
version="2.4" xmlencoding="UTF-8"
typemapping="Hypersonic SQL"
datasource="java:/DefaultDS" destdir="$
{build.dir}/ejb/META-INF"/> </ejbdoclet>
</target>

Presentation Name –<Author Initial><Date> Page 276 HTC Confidential


3.9.Ant-Core Tasks
among the there are some mandatory tags
like<remoteinterface/> or <homeinterface/> and some
optional tags like <jboss> based on the application
server,you are using.

Presentation Name –<Author Initial><Date> Page 277 HTC Confidential


3.9.Ant-Core Tasks
External Applications & Resources
following are some of the useful external applications apart from
java-related tasks that can be done by ant.
.Net
NET tasks can be used to a limited extent. anyone who has a
cross-platform project can use these tasks to cover the .NET
side of the problem. Here, cross-platform can mean more than
just Java and .NET.useful ones are
Integrating with a Java based SOAP Service -generating C# code from the
server's WSDL and running it against the server.
Building and deploying a C#-based Web Service, then using the Apache
Axis tasks to create JUnit tests to call the endpoints.
Patching .NET type libraries to work with more complex IDL than the basic
<importtypelib> wrapper around tlbimport supports. Hence the disassembler
and the reassembler.

Presentation Name –<Author Initial><Date> Page 278 HTC Confidential


3.9.Ant-Core Tasks
the tasks are
Task-Name Usage
Csc compiles c# code
Vbc compiles vb,net code
jsharpc compiles j# code
ildasm disassembles .NET executables and
libraries
ilasm assembles .is files
WsdlToDotnet Generates .NET code (C# or VB)
from a WSDL file
ImportTypeLib Imports a COM type library into.NET

Presentation Name –<Author Initial><Date> Page 279 HTC Confidential


3.9.Ant-Core Tasks
Resource
This is a resource that is included in the build. Ant uses this for
dependency checking -if resources included this way have
changed, the executable or library will be rebuilt. Important
attributes are
 file—the resource to include (required)
 name—the name of the resource
 embed—flag to control to whether the resource is embedded
or linked to it
FTP
other useful external source for getting files
transferred.important attributes are
‘server’,’userid’,’password’,’action’(default is send,can use
get/del/list/)
Presentation Name –<Author Initial><Date> Page 280 HTC Confidential
Thank You

Presentation Name –<Author Initial><Date> Page 281 HTC Confidential

You might also like