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

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

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

JDBC Drivers
The following are types of JDBC drivers : Type 3 :- JDBC-Net Driver This driver translates JDBC calls into a DBMSindependent 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

1.3.JDBC Connection A Connection object represents a connection with a database. or it can have connections with many different databases. A connection session includes the SQL statements that are executed and the results that are returned over that connection. Presentation Name <Author Initial><Date> Page 6 HTC Confidential . A single application can have one or more connections with a single database.

This method takes a string containing a JDBC URL and an optional User ID/ Password (for those databases which require them).3.1.getConnection( JDBCURL [. <userID> .JDBC Connection The standard way to establish a connection with a database is to call : DriverManager. 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 .<password>]).

3. 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.1. It has three parts. which are separated by colons: jdbc:<subprotocol>:<subname> Presentation Name <Author Initial><Date> Page 8 HTC Confidential .JDBC Connection Since JDBC URLs are used with various kinds of drivers.

3. The protocol in a JDBC URL is jdbc . jdbc:odbc:wombat (where wombat is the DSN) jdbc:oracle:thin:@taz:1521:ops001 Presentation Name <Author Initial><Date> Page 9 HTC Confidential .JDBC Connection The JDBC URL is broken down as follows: jdbc The protocol. <subprotocol> The name of the driver or the name of a database connectivity mechanism <subname> A way to identify the database.1. The subname can vary. and it can have any syntax the driver writer chooses. depending on the subprotocol.

JDBC Connection The DriverManager class is referred to as the JDBC management layer The DriverManager class maintains a list of registered Driver classes.1. and when the method getConnection is called.3. 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 .

Statement. 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.JDBC Statements Once a connection is established. it is used to pass SQL statements to its underlying database.3. Presentation Name <Author Initial><Date> Page 11 HTC Confidential . PreparedStatement and CallableStatement.1.

3.1.JDBC Statements :-Statement A Statement object is used for sending simple SQL statements. CallableStatement A CallableStatement object is used to execute SQL stored procedures Presentation Name <Author Initial><Date> Page 12 HTC Confidential . PreparedStatement A PreparedStatement object is used for SQL statements that take one or more parameters as input arguments (IN parameters).

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.createStatement( ). Statement stm = con.1. such as SELECT statements executeUpdate( ) Is used to execute INSERT.JDBC Statement Created by the method createStatement( ) of the Connection interface. Key Methods executeQuery( ) Is used for statements that produce a single result set.

more than one update count.1. 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 .JDBC Statement Key Methods execute( ) Is used to execute statements that return more than one result set.3.

JDBC Transactions A transaction consists of SQL statement(s) that have been executed. completed. The method rollback( ) will discard those changes. and then either committed or rolled back.1. Presentation Name <Author Initial><Date> Page 15 HTC Confidential . The method commit( ) of the Connection interface makes permanent any changes an SQL statement makes to a database. the current transaction ends. When the method commit( ) or rollback( ) is called.3.

the method commit( ) will be called on that statement automatically. since each statement is committed individually.JDBC Transactions A new connection is in auto-commit mode by default. Presentation Name <Author Initial><Date> Page 16 HTC Confidential . If auto-commit mode has been disabled. a transaction consists of only one statement. a transaction will not terminate until explicitly the commit( ) or rollback( ) is called.3. In this case. meaning that when a statement is completed.1.

Presentation Name <Author Initial><Date> Page 17 HTC Confidential .1.next( ) method is used to move to the next row of the ResultSet. The ResultSet.3. making the next row become the current row.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.

3.1. Presentation Name <Author Initial><Date> Page 18 HTC Confidential .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.

getObject. to retrieve the value stored in that column. getDate. getTime. 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 .1. getBytes.JDBC ResultSet For example.getString(2). getFloat.3. getInt. getShort. getTimestamp.getString("title"). getLong. if the second column of a ResultSet object is named title . getBigDecimal. (or) String s = rs. Methods such as getString. use: String s = rs. getByte.

getMetaData( ). Presentation Name <Author Initial><Date> Page 20 HTC Confidential . The ResultSetMetaData object returned gives the number. I++) System.JDBC ResultSet Information about the columns in a ResultSet is available by calling the method getMetaData( ). and properties of its ResultSet object's columns.println( Column : + rsm.out. types. To get the column names and type : ResultSetMetaData rsm = rs.1.3. I < rsm.getColumnTypeName(I)).getColumnName(I) + is of Type : + rsm. for (int I =1.getColumnCount( ).

Presentation Name <Author Initial><Date> Page 21 HTC Confidential .jdbc.OracleDriver).sql. // Contd.JDBC Sample code to Select data : import java.*. Resultset rs = null.forName(oracle.1. } catch(ClassNotFoundException e) { System. public class TestJDBC { public static void main(String args[ ]) { try { // Load the JDBC Driver Class.toString( )).println( Error loading Driver : +e.out. } Connection con = null...driver. Statement stm = null.3.

out.+ rs.next( )) { System. trng ). // Create a statement stm=con.println( Employee : + rs.getString( ENO ) + .executeQuery( select ENO.. // Execute an SQL Select statement rs = stm. trng . ENAME from EMP ).out.1.println( No Data Found ).getString( ENAME )).JDBC try { // Get a connection to the Database con = DriverManager. Presentation Name <Author Initial><Date> Page 22 HTC Confidential . } // Contd.3.getConnection( jdbc:oracle:thin:@taz:1521:ops001 . if (rs == null) System.createStatement( ).. // Iterate through the Resultset to get Data while (rs.

} catch(SQLException e) { } try { if (stm != null) stm.3.1.close( ).println( JDBC Error : + e.getMessage( )). } catch(SQLException e) { } try { if (con != null) con.out. } finally { // Close Resultset. } catch(SQLException e) { } } } } Presentation Name <Author Initial><Date> Page 23 HTC Confidential . Statement and Connection try { if (rs != null) rs.JDBC } catch(SQLException e) { System.close( ).close( ).

forName(oracle.out.OracleDriver). Presentation Name <Author Initial><Date> Page 24 HTC Confidential .JDBC Sample code to Insert data : import java.driver. } Connection con = null.sql.println( Error loading Driver : +e.jdbc.*. } catch(ClassNotFoundException e) { System.1. public class TestJDBC { public static void main(String args[ ]) { try { // Load the JDBC Driver Class.3. Statement stm = null... // Contd.toString( )).

// Contd.JDBC try { // Get a connection to the Database con = DriverManager.3.getConnection( jdbc:oracle:thin:@taz:1521:ops001 . ENAME ) values ( 1234. trng . System.. Presentation Name <Author Initial><Date> Page 25 HTC Confidential .println( Inserted with return status : + returnStat). SHIVA ) ).executeUpdate( insert into EMP (ENO. trng ).out.1. // Create a statement stm=con.. // Execute an SQL DML Statement int returnStat = stm.createStatement( ).

close( ). } finally { // Close Resultset. Statement and Connection try { if (rs != null) rs. } catch(SQLException e) { } try { if (con != null) con.close( ). } catch(SQLException e) { } try { if (stm != null) stm.JDBC } catch(SQLException e) { System.out.println( JDBC Error : + e.getMessage( )).close( ).1.3. } catch(SQLException e) { } } } } Presentation Name <Author Initial><Date> Page 26 HTC Confidential .

JDBC PreparedStatement A PreparedStatement is more efficient than a Statement object because it has been pre-compiled and stored for future use. Presentation Name <Author Initial><Date> Page 27 HTC Confidential . Instances of PreparedStatement extend Statement and include Statement methods.1.3. 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.

PreparedStatement pstmt = con.3. ENAME) values ( ? . Presentation Name <Author Initial><Date> Page 28 HTC Confidential .prepareStatement ( insert into EMP (ENO . instead the question mark ("?") acts as a placeholder for IN parameters.JDBC PreparedStatement Created by the prepareStatement( ) method of the Connection interface. An IN parameter is the one whose value is not specified when the SQL statement is created. A value for each question mark must be supplied by the appropriate setXXX method before the statement is executed. ? ) ).1.

3. Shiva ).executeUpdate( ). //Dynamic parameter int status = pstmt. //Constant parameter for (int i= 1.JDBC PreparedStatement Once a parameter value has been set for a given statement. i < 5. ? ) ). pstmt. ENAME) values ( ? . the following inserts 4 rows PreparedStatement pstmt = con. it can be used for multiple executions of that statement.setString(2. i++) { pstmt. For example.1. } Presentation Name <Author Initial><Date> Page 29 HTC Confidential .setInt(1. i).prepareStatement( insert into EMP (ENO .

. . ?)} ).)} CallableStatement cstmt = con..3.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.prepareCall( {call getTestData(?. The syntax for invoking a stored procedure in JDBC is shown below : {call procedure_name(?. Presentation Name <Author Initial><Date> Page 30 HTC Confidential .1. ?.

CallableStatement's getXXX methods are used to retrieve the parameter value Presentation Name <Author Initial><Date> Page 31 HTC Confidential .1. After the statement has been executed.3.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.

?)} ).Types.Types. cstmt. passes an IN parameter and retrieves two OUT parameters : CallableStatement cstmt = con.setInt(1. 3). cstmt. java. String s = cstmt. Presentation Name <Author Initial><Date> Page 32 HTC Confidential . 25).DECIMAL.3).registerOutParameter(2.prepareCall( {call getTestData(?.sql.sql.BigDecimal n = cstmt. cstmt.registerOutParameter(3.3.math. ? .1.getString(2). java.JDBC CallableStatement The following code executes a Stored Procedure.getBigDecimal(3.executeUpdate( ). java.VARCHAR). cstmt.

first().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().afterLast().0 we can get ResultSets that allow users to scroll in both directions.JDBC In JDBC 2.driver. This is achieved through using II nd or IV th type of drivers like oracle.1.relative(int) for navigation Presentation Name <Author Initial><Date> Page 33 HTC Confidential .3.jdbc.beforFirst().abs olute(int).

3.6.4.Struts 3.Junit 3.JDBC 3.JSTL 3.7.Struts-Tag Libraries 3.Ant Presentation Name <Author Initial><Date> Page 34 HTC Confidential .9.Advanced-Java Contents -1 3.8.Tag Libraries 3.Servlets & JSP 3.

2.Life Cycle of Servlets 3.5.ServletContext and ServletConfig 3.2.1.A Sample HTTP Servlet 3.Session Management 3.Anatomy Servlet .9.8.HTTP Servlet .HTTP Servlet .servlet resource-access 3.3.2.Servlet-info in web configuration file 3.2.2.Cookies Presentation Name <Author Initial><Date> Page 35 HTC Confidential .Introduction to Servlets 3.filter.Servlets -3.1.2.

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.

3.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.1. 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 . but.2.

3.2..they are visualized as controller components Presentation Name <Author Initial><Date> Page 38 HTC Confidential .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.1. on-line conferencing and Chat applications communicating with other Servers accessing existing Business systems In MVC2 architecture..

RMI.1. JMS. JavaMail. JavaIDL. or third-party Java technology These are easily compatiable with most of web-servers Presentation Name <Author Initial><Date> Page 39 HTC Confidential .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.3. 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.Introduction to Servlets Why Servlets ? servlets are light-weight i.e.2. EJB.e.

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 .2.1.3.

all Mac OS Servers Jrun for IIS. Apache. Netscape.2.Introduction to Servlets Engines for Existing Servers: ServletExec for IIS. WebSTAR WAICoolRunner for Netscape Presentation Name <Author Initial><Date> Page 41 HTC Confidential . Netscape.3. WebSite Pro.1.

GenericServlet javax.HttpServlet WEB applications use HTTP Servlets HTTP Servlets extend Generic Servlet Presentation Name <Author Initial><Date> Page 42 HTC Confidential .3.http.1.servlet.Servlet Most Servlets extend one of the following 2 standard implementations: javax.2.Introduction to Servlets All Servlets implement the interface javax.servlet.servlet.

9.ServletContext and ServletConfig 3.7.Introduction to Servlets 3.Servlets 3.1.2.filter.3.2.A Sample HTTP Servlet 3.2.2.filter-mappings Presentation Name <Author Initial><Date> Page 43 HTC Confidential .Life Cycle of Servlets 3.2.Servlet-info in web configuration file 3.HTTP Servlet . Servlet .9.2.Session Management 3.HTTP Servlet .servlet resource-access 3.

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.2.2. so.3. 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. 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 .2.2.e.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.

3. since other threads might be running service( ) methods when destroy( ) is invoked.2. it needs to be implemented in a Thread-Safe manner Presentation Name <Author Initial><Date> Page 46 HTC Confidential . but.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.2.

Introduction to Servlets and ServletConfig in web configuration file 3.4.HTTP Servlet .9.Anatomy 3.2.HTTP Servlet Cookies 3.6.2.Life Cycle of Servlets 3.filter.2.3.filter-mappings Presentation Name <Author Initial><Date> Page 47 HTC Confidential .5.Servlets 3.2.Session Management 3.2.2.A Sample HTTP Servlet resource-access 3.HTTP Servlet .2.

3.2.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.

3.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 .2.

init( config ). } } //End of init( ) method public void destroy( ) { companyName = null. import javax.servlet.io.3. Un-Authorized ).servlet.java looks like this: import java.A Sample HTTP Servlet The code for HelloWorldServlet. companyName = getInitParameter( company ).*. if ( companyName == null ) { throw new UnavailableException( this.http.*. public void init( ServletConfig config ) throws ServletException { super.*. import javax.3. public class HelloWorldServlet extends HttpServlet { String companyName.2. } //End of Destroy( ) method Presentation Name <Author Initial><Date> Page 50 HTC Confidential .

setContentType( text/html ).3. HttpServletResponse res ) throws ServletException.close( ). IOException { res.getWriter( ).2. } //End of service( ) method // End of Hello World Servlet } Presentation Name <Author Initial><Date> Page 51 HTC Confidential .getParameter( USER ) + of + companyName + </H2></BODY></HTML> ). PrintWriter out = res.println( <HTML><BODY><H1>Hello World!!</H1> + <H2>By + req.A Sample HTTP Servlet protected void doGet( HttpServletRequest req. out. out.3.

6.8.Anatomy 3.HTTP Servlet .2.2.ServletContext and ServletConfig 3.7.2.Session Management 3.3.3.A Sample HTTP Servlet 3.2.2.filter.Servlet-info in web configuration file 3.HTTP Servlet .Cookies 3.2.HTTP Servlet .Life Cycle of Servlets 3.Introduction to Servlets resource-access 3.filter-mappings Presentation Name <Author Initial><Date> Page 52 HTC Confidential .9.2.

*.servlet.Anatomy Hello World Servlet .servlet. javax is an extended Java packages library javax.http contains all classes used by HTTP Servlets Presentation Name <Author Initial><Date> Page 53 HTC Confidential .http.*.HTTP Servlet .3. import javax.io. import javax.Import Lines 1 to 3 import packages which contain classes that are used by the Servlet import java.servlet.2.4.*.

http.4.2.Declaration The Servlet class is declared as extends javax.3.Anatomy Hello World Servlet .HTTP Servlet .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 .servlet.

init( config )..2.init( ) The init( ) method is overridden for the purpose of initializing the Servlet public void init( ServletConfig config ) throws ServletException { super. .4. } Presentation Name <Author Initial><Date> Page 55 HTC Confidential .3.Anatomy Hello World Servlet .HTTP Servlet ..

3.2.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).init( ) In init( ) we first call super.HTTP Servlet .Anatomy Hello World Servlet . or some other initialization error occurs.4. an UnavailableException is thrown The UnavailableException extends ServletException Presentation Name <Author Initial><Date> Page 56 HTC Confidential .

4.HTTP Servlet .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( ).2. we are getting an Initialization parameter called company from the Servlet s configuration file(web.Anatomy Hello World Servlet .init( ) In this init( ) method. but.3.xml) and assigning it s value to a member called companyName Version 2. is good practice to do so Presentation Name <Author Initial><Date> Page 57 HTC Confidential .

} In this destroy( ) we are marking the Servlet member called companyName for garbage collection It is not mandatory to include the destroy( ).4.destroy( ) The destroy( ) method is overridden for clean-up during unloading of Servlets public void destroy( ) { companyName = null.3.2. but is good practice to do so Presentation Name <Author Initial><Date> Page 58 HTC Confidential .Anatomy Hello World Servlet .HTTP Servlet .

HTTP Servlet .3.service( ) The service( ) method is overridden for Request / Response interaction with the client browser protected void service( HttpServletRequest req.Anatomy Hello World Servlet . 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 .4.2.

3.4.doDelete().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(). doGet() matching to the type of http requests.HTTP Servlet .doOptions().2.Anatomy Hello World Servlet .doTrace().doPost().all of which are called service methods Presentation Name <Author Initial><Date> Page 60 HTC Confidential .

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 .service( ) The service methods have following parameters: HttpServletRequest for abstracting the request from the client provides access to HTTP header data.HTTP Servlet .2.3. such as any cookies found in the request provides access to all request parameters.Anatomy Hello World Servlet .4.

2.3.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 .

2.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 .4.3.HTTP Servlet . resource-access 3.2.HTTP Servlet .Servlet-info in web configuration file 3.ServletContext and ServletConfig 3.2.Cookies 3.filter.Session Management 3.filter-mappings Presentation Name <Author Initial><Date> Page 64 HTC Confidential .1.A Sample HTTP Servlet 3.HTTP Servlet .5.Life Cycle of Servlets 3.2.HTTP Servlet .4.Introduction to Servlets

stateless Session Management is easily used for User Authentication across requests within the same session Session Management is used for Caching reusable information Presentation Name <Author Initial><Date> Page 65 HTC Confidential .HTTP Servlet-Session Management Session Management is the process of maintaining persistence and State Information Session Management is required because HTTP is by default.5.2.3.

5. 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 .2.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.3.

such as an identifier for the session.3. 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 .HTTP Servlet .Session Management In session tracking.HttpSession defines methods which can extract the following types of data: Standard session properties.2.5.

} String userId = session. Presentation Name <Author Initial><Date> Page 68 HTC Confidential .Session Management The following code snippets describe Session authentication and Caching: Session Creation (after User Login): HttpSession session = req.HTTP Servlet . session.isNew( ) ) ) { res.sendRedirect( loginURL ).3.setAttribute( USER .getAttribute( USER ).5. * any value as an object Session Authentication (each request): HttpSession session = req.getSession( true ).getParameter( USER )* ). req.2.getSession( false ). if ( ( session == null ) || ( session.

ServletContext and ServletConfig 3.Servlets 3.2.HTTP Servlet .2.2.Servlet-info in web configuration file 3.Anatomy 3.2.Session Management 3.Life Cycle of Servlets 3.2.servlet resource-access 3.2.Introduction to Servlets Presentation Name <Author Initial><Date> Page 69 HTC Confidential . Servlet .5.9.2.HTTP Servlet Cookies 3.7.A Sample HTTP Servlet 3.1.

2.ServletContext and ServletConfig The ServletContext and the ServletConfig interfaces of javax.3.6.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 .

rd. first.getRequestDispatcher(/servlet/other ).forward(request.3.response).ServletContext and ServletConfig The following code snippet describe external Access of a Servlet s members: RequestDispatcher rd = this.getServletContext( ).2. 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 .6.

HTTP Servlet .2.HTTP Servlet .2.Introduction to Servlets in web configuration file 3.Life Cycle of Servlets and ServletConfig 3.Anatomy 3.A Sample HTTP Servlet 3.1.Session Management 3.servlet resource-access 3.2.HTTP Servlet .filter-mappings Presentation Name <Author Initial><Date> Page 72 HTC Confidential .2.2.3.filter.1.2.

and a version) Presentation Name <Author Initial><Date> Page 73 HTC Confidential .HTTP Servlet . including comment. path and domain qualifiers for the hosts which see the cookie.2.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.3. and have a single value with settable life(with optional attributes. a maximum age.7.

HTTP Servlet .7. it is kept at the browser for fast retrieval so that any request that goes to the same server.3.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 .Cookies Cookies can be passed back and forth between the browser and the server Cookies are created on the instruction of a webserver After a cookie is transmitted through the HTTP header.2.

Cookies Browser settings allow rejection of Cookies.3.HTTP Servlet .2. 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 . so.7.

2.Cookies Cookies can be set and retrieved at Client-side using JavaScript / VBScript HTTP Servlets support setting.7.servlet.http.3.HTTP Servlet . 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.Cookie class .for creating and manipulating Cookies Presentation Name <Author Initial><Date> Page 76 HTC Confidential .

length.addCookie( toClient2 ). SHIVA ). i < fromClient.7.3.println( Cookie + fromClient[ i ]. HTC ). } Presentation Name <Author Initial><Date> Page 77 HTC Confidential .addCookie( toClient1 ).Cookies The following code snippets describe the usage of Cookies in HTTP Servlets: Cookie Creation: Cookie toClient1 = new Cookie( USER . Cookie toClient2 = new Cookie( COMP .getName( ) + Has Value : + fromClient[ i ]. res. res. Cookie Retrieval: Cookie[ ] fromClient = req.2. for ( int i = 0.getValue( ) ).out.getCookies( ).HTTP Servlet . i++ ) { System.

2.ServletContext and ServletConfig 3.HTTP Servlet . 3.Session Management 3.1.Life Cycle of Servlets 3.2.A Sample HTTP Servlet 3.filter.filter-mappings Presentation Name <Author Initial><Date> Page 78 HTC Confidential .5.2.servlet resource-access Servlet Cookies 3.Introduction to Servlets 3.Servlet -info in web configuration file 3.Servlets Servlet .

2.xml.Sevlet Configuration file Servlet s all deployment information is made available to the container in the web configuration file web..8.3.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 ..

8.2.</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.Sevlet Configuration file <servlet-mapping> <servlet-name> .

Sevlet Configuration file <session-config> <session-timeout>1800</session-timeout> </session-config> <filter> <filter-name> .</filter-class> </filter> <filter-mapping> <filter-name> .8.</servlet-name> </filter-mapping> Presentation Name <Author Initial><Date> Page 81 HTC Confidential .</filter-name> <filter-class> .</filter-name> <servlet-name> .3.2.

Introduction to Servlets 3.1.HTTP Servlet .Anatomy 3.filter-mappings Presentation Name <Author Initial><Date> Page 82 HTC Confidential .2.HTTP Servlet .3.2.2.HTTP Servlet .2.1.2.filter.A Sample HTTP Servlet 3.2.Servlet-info in web configuration file and ServletConfig 3.5.2.Cookies 3.3.2.servlet resource-access 3.2.Life Cycle of Servlets 3.2.Servlets .Session Management

3.xml file as <resource-ref> <res-ref-name>*</res-ref-name> <res-type> .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.</res-type> <res-auth> .2.<res-auth> </resource-ref> Presentation Name <Author Initial><Date> Page 83 HTC Confidential .

servlet resource access This is referred and accessed in servlet code from the jndi InitialContext object as InitialContext ctx=new InitialContext(). Presentation Name <Author Initial><Date> Page 84 HTC Confidential .lookup( java:comp/env/* ).2.9.3. resource-type-class obj=ctx.

HTTP Servlet .2.filter-mappings Presentation Name <Author Initial><Date> Page 85 HTC Confidential .1.6.HTTP Servlet .Cookies to Servlets 3.ServletContext and ServletConfig 3.2.HTTP Servlet .2.2.Session Management Cycle of Servlets 3.3.Servlet-info in web configuration file 3.A Sample HTTP Servlet 3.filter.Servlets .2.2.servlet resource-access 3.,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,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

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

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

Directives Declarations Scriptlets Expressions Standard actions

Presentation Name <Author Initial><Date>

Page 90

HTC Confidential

2. 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 .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.3.

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


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. %> Presentation Name <Author Initial><Date> Page 97 HTC Confidential .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.JSP .println( Welcome to JSP ).2.

%> <% i++ %> <%= JSP page has been accesssed + i + times %> Presentation Name <Author Initial><Date> Page 98 HTC Confidential .3.JSP .the result is converted to a string and displayed <%= java expression to be evaluated %> Ex:<%! int i=0 .Expressions Expressions are to display any user output or a manipulated value When the expression is evaluated .2.

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.

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 .

2.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 .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.3.JSP jsp:param Standard actions used to provide other tags with additional information in the form of name value pairs used in conjunction with jsp:include.

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 .3. 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 .2.

2.0 EL Expressions appear between ${ and }.) E.g..findAttribute( duck ) Presentation Name <Author Initial><Date> Page 103 HTC Confidential . not just variable names. session.JSP 2. request. application) ${duck} pageContext. ${myExpression + 2} Expressions default targets are scoped attributes (page. as in the Bourne shell (and its dozen derivatives.3. Note that ${ and } may contain whole expressions.

getBeakColor() Note the automatic type-cast.JSP 2.2. and [] operators refer to JavaBean-style properties and Map elements: ${duck.0 EL The .beakColor} can resolve to ((Duck) pageContext.getAttribute(´duck´)).3. 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 .

0 EL Expressions may also refer to cookies.3. request parameters.2.remoteUser} Presentation Name <Author Initial><Date> Page 105 HTC Confidential .crumb} ${param.request.JSP 2. and other data: ${cookie.password} ${header[ User-Agent ]} ${pageContext.

empty List.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 ( ).2. etc. null.3.x} Presentation Name <Author Initial><Date> Page 106 HTC Confidential . Useful for ${empty param.

9.Struts-Tag Libraries 3.2.5.XML 3.8.JSTL 3.4.JDBC 3.3.Junit 3.Struts 3.Servlets & JSP Libraries 3.Advanced-Java Contents -1 3.Ant Presentation Name <Author Initial><Date> Page 107 HTC Confidential .6.

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.3. 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.3. Example » <jsp:useBean/> » <jsp:setProperty/> Presentation Name <Author Initial><Date> Page 109 HTC Confidential .

3. Example <connection:getProducts/> The above codes connects to a database and get the product list.3.Tag Libraries Customized Tag Functionality provided by the programer. Access to implicit object.(details later) Presentation Name <Author Initial><Date> Page 110 HTC Confidential . Advantage The web page developer can concentrate on the content rather than business logic.

3.3. Tag Library Descriptor Contains various Tags Links Tags with Handler Classes Presentation Name <Author Initial><Date> Page 111 HTC Confidential .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.

tld extension Contains also information about attributes Presentation Name <Author Initial><Date> Page 112 HTC Confidential .3. 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 .Tag Libraries What is a TLD (Tag Library Descriptor) ? A XML file which contains list of tags and information about them.3.

Tag With Body.No Attribute). Nested Tag.Tag Libraries Types of Tag:-Simple Tag (No Body. Simple Tag With Attributes. 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:.3.3.jsp <%@ taglib uri="/TagCollection.tld" prefix="greet"/> <html> <body> <greet:sayHello/> </body> </html> Presentation Name <Author Initial><Date> Page 114 HTC Confidential .HelloWorld.

} } Presentation Name <Author Initial><Date> Page 115 HTC Confidential .3. // pageContext is object provided by container through // implicit objects can be created and used.Tag Libraries.Simple tag Tag Handler Class HelloWorld.getOut.3.write("Hello World").java public class HelloWorld extends SimpleTagSupport { public void doTag() throws JspTagException { // this method is called when the start is encountered pageContext.

Simple tag TagCollection.3.Tag Libraries.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.

Tag Libraries-Tags with attribute Adds flexibility to your tag library Allowing tags like <prefix:name attribute1= value1 attribute2= value2 Example:-AttribTag.jsp <%@ taglib uri="/TagCollection.tld" prefix="Hello"/> <html> <body> <Hello:input name="Gokul"/> </body> </html> .3.3./> Presentation Name <Author Initial><Date> Page 117 HTC Confidential .

*.servlet.getOut.servlet.http.tagext.Tags with attribute TagAttrib.*.name=name.jsp.write("Hello "+ name). } } Presentation Name <Author Initial><Date> Page 118 HTC Confidential .java import javax. import javax. import javax.3. import java.io. public setName(String name) { this.jsp. } public void doTag()throws JspTagException { pageContext.Tag Libraries.*. public class TagAttrib extends SimpleTagSupport { private String name.servlet.*.3.

Tags with attribute TagCollections.Tag Libraries.3.3.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 .

doInitBody() in Tag class Presentation Name <Author Initial><Date> Page 120 HTC Confidential .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. You have additional methods doAfterBody().Support class is BodyTagSupport.3.3.HTML. The Handler class implement BodyTag interface.

3.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 .Tag Libraries-Tag with Body Example:--Hello.3.

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

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 .3.we go for nested tags To define a tag that depend on a particular nesting order For ex:-in standard HTML.3. 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.Tag Libraries-Nested Tags Tag Handler Classes Can be extended from either TagSupport or BodyTagSupport.3. 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. Presentation Name <Author Initial><Date> Page 128 HTC Confidential . nested tags can use findAncestorWithClass to find the instance of a given class type that is closest to a given instance.

EnclosingTag.g.class) as arguments If no enclosing class is found . 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 .g.Tag Libraries-Nested Tags First (continued):-this method takes a reference to the current class(e.3.3. this) and the Class object of the enclosing class(e. 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.

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

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 .3. 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 .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.3.

Tag Libraries-Tag Validation Presentation Name <Author Initial><Date> Page 132 HTC Confidential .3.3.

3. Request-time attributes are indicated as such in the TagData parameter.3.Tag Libraries-Tag Extra Info Classes boolean isValid(TagData data) used for Translation-time validation of the attributes. Presentation Name <Author Initial><Date> Page 133 HTC Confidential .

XML 3.9.Ant Presentation Name <Author Initial><Date> Page 134 HTC Confidential .2.Tag Libraries 3.Struts 3.JSTL Contents -1 3.3.Junit Libraries 3.Servlets & JSP 3.JDBC 3.

e jsps Presentation Name <Author Initial><Date> Page 135 HTC Confidential . 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.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.Struts Framework set of multiple classes.4.3. McClanahan and donated to ASF in 2000.interfaces.

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.actual validator classes are available in the commons package.3.separate from struts Presentation Name <Author Initial><Date> Page 136 HTC Confidential .xml contents validator contain Struts specific extension classes meant for of validator.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.

Subclasses of Action class should give code for public ActionForward execute(ActionMapping.e RequestProcessor class in 1.4.struts.HttpServletRequest.Htt pServletResponse) as the framework creates a singleton of this and invoke its execute method since the super class the method returns null.apache.ActionForm.meant for flexibility to subclass.after this it delegates the handling of the request to a helper class which is a subclass of org.action.struts. Presentation Name <Author Initial><Date> HTC Confidential Page 137 .3.1 version.action.one of which is org.ActionServlet class whose main function is to receive the client s request and process it through a handler class i.Struts In struts framework the Controller component functionality is divided by more than one component.Action so that decoupling client-request & business-logic takes place.apache.

3.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.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 .4.xml file config/sub to specify additional configuration files debug controls how much info is to be logged detail detail level for Digestor.

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 .Struts the Action class will be configured in struts-config.4.3.by default ActionMapping forward the application-relative path to a resource to which further navigation occur.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.

3.4.Struts name the name of the form-bean associated with this action.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 .this value should one of name attribute of the form-bean elements defined already path the application-relative path to the submitted request.

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 .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.4.3.

ForwardAction and the forwarding target url is given by the parameter attribute Include Actions originally planned to integrate servletbased components into struts-based web applications.apache.actions.apache.IncludeAction and the url is given by the parameter attribute Presentation Name <Author Initial><Date> Page 142 HTC Confidential .struts.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.struts.type attribute will have org.the type attribute will be org.actions.4.3.

if wanted to switch to the default . Only required if you have more than one module.The type is org.the page request parameter should be there that gives the relative path.apache.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.3.SwitchAction Presentation Name <Author Initial><Date> Page 143 HTC Confidential .struts.4.actions.you can use zero-length string as .

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 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 .these are written as extending ActionForm class.4.3.

3.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.since the reset method is called for every new request particulary if default scope ie session is in effect.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 . These are configured under form-bean element under form-beans element.4.Struts these are created as subclasses of ActionForm(which is abstract) to capture an application-specific form-data.it may contain a validate() method which RequestProcessor class calls as well as reset() method.so that the bean fields are set back to their defaults.

String initial= Mr.lang.struts.apache.4.X /> </form-bean></form-beans> But if validate method is to be implementation.since by default reset(0 method is taken well care of Presentation Name <Author Initial><Date> Page 146 HTC Confidential .another class has to be written only for that.action.3.DynaActionForm ><formproperty name= uname type= java.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.

3.this will allow to configure. </field> </form> </formset></form-validation> Presentation Name <Author Initial><Date> Page 147 HTC Confidential .4.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.Struts Struts Validator struts framework allows to skip validation in actionforms and done through David winterfeldt s validator framework.mask > .xml the other file is validation.the framework rules are available in validator-rules.

for client-side validation you can use customTag called JavascriptValidator based on the javascript code available in validator-rules.4.3.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 .we can call as server-side validation.Struts Struts Validator all the above .

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 textinput 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> HTC Confidential

Page 152

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

title Presentation Name <Author Initial><Date> Page 154 HTC Confidential .3.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.5.Struts-Tag Libs-HTML tag <html:base /> Used to insert an HTML <base> element .

3.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:.5.property.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 Must be nested inside the body of an <html:form />tag Presentation Name <Author Initial><Date> Page 155 HTC Confidential .

5.property.3.title Must be nested inside the body of an <html:form />tag Presentation Name <Author Initial><Date> Page 156 HTC Confidential .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:.

5.property.title Must be nested inside the body of an<html:form/>tag Presentation Name <Author Initial><Date> Page 157 HTC Confidential .3.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 :.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 :.

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 :.5.3.title Presentation Name <Author Initial><Date> Page 158 HTC Confidential .

ActionErrors etc has a body type of JSP and supports 8 attributes Required attributes are :.value Presentation Name <Author Initial><Date> Page 159 HTC Confidential .5.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 :.Struts-Tag Libs-HTML tag <html:messages/> Used to display a general-purpose messages to the user stored in ActionMessages.3.

title Must be nested inside the body of an<html:form/>tag Presentation Name <Author Initial><Date> Page 160 HTC Confidential .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 :.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 :.3.property.5.

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 .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.5. value.3.

5.title Must be nested inside the body of an<html:form/>tag Presentation Name <Author Initial><Date> Page 162 HTC Confidential .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 :.3.

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.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 :. 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 .

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-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.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 :.

5.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 .Struts Tag Libs-Bean tag Bean Tag library provides a group of tags that encapsulates the logic necessary to access and manipulate JavaBeans.3.

Struts Tag Libs-Bean tag Custom tags are:.3.(continued) < bean:message/> <bean:page/> <bean:parameter/> <bean:resource/> <bean:size/> <bean:struts/> <bean:write/> Presentation Name <Author Initial><Date> Page 166 HTC Confidential .5.

name <bean:define /> Used to retrieve the value of a named bean property and define it as a scripting variable.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 :.5.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 :.3.id Presentation Name <Author Initial><Date> Page 167 HTC Confidential .id .

5. except that the response is stored in a page scoped object attribute.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:. 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.id. as opposed to being written to the output stream Presentation Name <Author Initial><Date> Page 168 HTC Confidential .3.

id.5. 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 :.Struts Tag Libs -Bean tag <bean:page/> Used to retrieve the value of an identified implicit JSP object.3. 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 .

id. name For ex:<bean:parameter id= userId name= username value= User Not Found /> Presentation Name <Author Initial><Date> Page 170 HTC Confidential . if the multiple value is not null Has no body and supports 4 attributes Required attributes are :.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[].

id. collection.3.5.or map Has no body and supports 5 attributes Required attributes are:.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 Presentation Name <Author Initial><Date> Page 171 HTC Confidential . name <bean:size/> Used to retrieve the number of elements contained in a reference to an array.

looping over object collections for repetitive generation of ouput text.Struts Tag Libs -Logic tag Contains tags that are useful for managing conditional genaration of output 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: <logic: <logic: <logic: empty/> notEmpty/> equal/> 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.

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 .5. 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.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:.

If this data member equals the value stored in the requiredAge variable. name.<logic:equal name= user property = age value= <%= requiredAge %> > You are exactly the right age.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. or property equals the constant value specified by the value attribute Has a body type of JSP and supports 7 attributes Required attributes are:.5.value Ex:-. </logic:equal> We test the age data member of the scripting variable user.3. parameter. then the tag s body will be evaluated Presentation Name <Author Initial><Date> Page 175 HTC Confidential .

jsp /> </global-forward> Presentation Name <Author Initial><Date> Page 176 HTC Confidential .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.3.5.

Struts Tag Libs -Logic tag <logic:redirect/> uses the HttpServletResponse. name Presentation Name <Author Initial><Date> Page 177 HTC Confidential .3.5.value.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.href .sendRedirect() method to redirect the cuttent request to a resource identified by either the forward. 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 :.

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:.5.id Presentation Name <Author Initial><Date> Page 178 HTC Confidential .3.

5.3.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 .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 :.

5.Struts Tag Libs -Nested tag In nested tags you can use one tag inside another tag that belong to the html . 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. bean .

5.3.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 .

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 .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/>.3.5.

3.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 :. 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 . representing a sub-component of a template.5.id <tiles:put/> Used to define the equivalent of a parameter .

5.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.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:.

3. this tag is functionally the same as the <tiles:insert/> tag Has no body content and supports 4 attributes Required attributes are :.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.name Presentation Name <Author Initial><Date> Page 185 HTC Confidential .5.

JDBC 3.Junit 3.3.JSTL 3.Advanced-Java Contents-1 3.Struts-Tag Libraries 3.4.Ant Presentation Name <Author Initial><Date> Page 186 HTC Confidential .Servlets & JSP 3.8.Tag Libraries 3.3.XML 3.1.

JSTL 1. XSLT database access Queries. updates Presentation Name <Author Initial><Date> Page 187 HTC Confidential .3.6.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.

0 libraries Library features Core (control flow.3. variable access) Text formatting XML manipulation Database access Recommended prefix c fmt x sql Presentation Name <Author Initial><Date> Page 188 HTC Confidential . URLs.JSTL 1.6.

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.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 .6.

6.JSTL features: conditional logic Conditional evaluation <c:if test=´${a == b}´> a equals b </c:if> Mutually exclusive conditionals <c:choose> <c:when test=´${a == b}´> a equals b </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.

com/cnn. HTTPS with JSSE) Local.JSTL features:URL management Retrieving data <c:import var=´cnn´ url=´http://www.rss´/> Data exposed as String or Reader All core URLs supported (HTTP. FTP.jsp´> Presentation Name <Author Initial><Date> Page 192 HTC Confidential .jsp´> Redirection <c:redirect url=´/foo. cross-context imports supported Printing URLs <c:url value=´/foo.3.6.cnn.

6. I will use it to buy myself a big {2}.JSTL features: text formatting Locale-sensitive formatting and parsing Numbers Dates Internationalization Message bundles <fmt:formatNumber type=³currency´ value=³${salary}´ /> Message argument substitution <fmt:message key=³welcome´ /> Hi {0}. Presentation Name <Author Initial><Date> Page 193 HTC Confidential . I would like to {1} your money today.3.

cnn.3.6.com/cnn.JSTL features: XML manipulation Use of XPath to access.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 . display pieces of XML documents <c:import url=´http://www.

.3. standard access to Java/JSP code.g. Functional versus imperative programming Presentation Name <Author Initial><Date> Page 195 HTC Confidential . then follow the URL and parse its contents.6. parse an article URL out of a document.Advantages of JSTL XML/XPath support Why not always use XSLT? JSTL integrates XPath with convenient. JSP/JSTL may be more familiar and convenient for simple tasks. E.

3.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 .6.

SQL tags: the debate Tag library Back-end Java code Tag library Database JSP page Presentation Name <Author Initial><Date> Page 197 HTC Confidential .6.3.

3.6. Presentation Name <Author Initial><Date> Page 198 HTC Confidential . prototyping is important users ask for it! The JSTL specification recommends avoidance of SQL tags in large applications. not all data is worth handling carefully. Even in an MVC application.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.

0 Nice JSP 2.1 tag protocol with assistance from JSTL 1. Ugly JSP 1.0 tag protocol. Presentation Name <Author Initial><Date> Page 199 HTC Confidential . doEndTag()). ConditionalTagSupport Instead of writing whole tag handler (doStartTag().6.0 is probably easier.JSTL programmer support JSTL also supports Java developers Simplifies tag development IteratorTagSupport. simply override a few methods: protected boolean condition() protected Object next() Still.1 tag protocol Ugly JSP 1.3. JSP 2.

3.) Time zone Presentation Name <Author Initial><Date> Page 200 HTC Confidential .6. etc.JSTL programmer support JSTL API allows registrations of defaults DataSource Limit on size of results Localization context (Locale.

2.Tag Libraries 3.Ant Presentation Name <Author Initial><Date> Page 201 HTC Confidential .8.XML 3.JDBC 3.1.5.Struts 3.Advanced-Java Contents-1 3. Servlets & JSP 3.9.3.JSTL 3.Struts-Tag Libraries 3.

7.bml Presentation Name <Author Initial><Date> Page 202 HTC Confidential .3.cml.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.mml.lot of it s derived languages are in the market like wml.

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 .7.3.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 .

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.3. Presentation Name <Author Initial><Date> Page 204 HTC Confidential .7. 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.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.

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 & . Presentation Name <Author Initial><Date> Page 205 HTC Confidential .3. to get use &quot. to get > use &gt. to get ` use &apos. to get < use &lt.. for ex: to get & use &amp.

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.7.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.3. attribute entity: these are meant to simplefy the dtd writing when multiple elements are going to have the same set of attributes. > <!ATTLIST vvvv %attrs.XML External entity: when want to insert repeatabing and reusable content you can use these. > Presentation Name <Author Initial><Date> Page 206 HTC Confidential .

you can give <!ELEMENT d (#PCDATA) > .7. an element can have.what list of attributes.if it is a leaf element.what entities are to mean etc.c.3. 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 .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.b.c.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.d) > meaning abcd parent element can have elements a.b.d in order one each by default .

> here CDATA means the character data is not going to parsed.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.3. Presentation Name <Author Initial><Date> Page 208 HTC Confidential .7.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 .

com|BCA) BCA > Entities are already discussed above Presentation Name <Author Initial><Date> HTC Confidential Page 209 .sc|B.3. #REQUIRED meaning that the attribute is to be there .A|B.XML DTD After CDATA you can give the following that puts adjectives to the attributes . #IMPLIED may be given or not . ID #REQUIRED meaning that the attribute is to be there and it should not have duplicates within the page. . #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.7.

the usage of prefix in xml for certain elements will be validated with that corresponding dtd file.3.org/TR/XHTML1/strict"> then html elements are used with <HTML:br/> Presentation Name <Author Initial><Date> Page 210 HTC Confidential .w3.XML Namespaces in an xml file you can use elements of more than one source dtd utilizing a prefix that points to uri.7.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. that is defined in the root element.

the main deference xml file using namespaces like <pur20 xmlns:xsi="http://www.xsd"> similar to dtd files saved with .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.org/2000.these are saved with .xsd extension Presentation Name <Author Initial><Date> Page 211 HTC Confidential .XMLSchemainstance xsi:noNamespaceSchemaLocation="pur20.10.w3.3.dtd extension.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.3.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 .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.

whitespace and well-formedness of an xml file b). syntax validators:: these will ensure case.javax.xml..transform .xml.x path etc Presentation Name <Author Initial><Date> Page 214 HTC Confidential .7.namespaces.w3c.3.javax..sax .javax.xml.org.4 & above)hava amalgamated these with the main jdk.dom.j avax.the related packages are rg.javax. 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.xml.xml.xml.XML Xml parsing There are two types of parsers that are available a).parsers.

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

parse(f1). then an object of DocumentBuilder is created like DocumentBuilder dBuilder=docF.7. Presentation Name <Author Initial><Date> Page 216 HTC Confidential .3.newInstance().newDocumentBuilder().XML xml parsing-DOM in this type of parsing first an instance of DocumentBuilderFactory is created like DocumentBuilderFactory docF=DocumentBuilderFactory. Document doc=dBuilder. then given file is parsed after getting InputSource/File object out of it File f1=new File(args[0]).

other handler interfaces are also there like EntityResolver.7.3.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 .ErrorHandler.DTDHandler which will handle various elements you encounter in parsing an xml file.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.

7.fatalError() EntityResolver::resolveEntity() DTDHandler:: notationDecl().error(). characters().startElement().endElement().startPrefixMapping(). startDocument().3.XML xml parsing-SAX Useful methods of these interfaces are ContentHandler:: ().unparsedEntityDecl() Presentation Name <Author Initial><Date> Page 218 HTC Confidential . processingInstruction().endDocument() ErrorHandler:: warning().

parse(source.7.newInstance(). Presentation Name <Author Initial><Date> Page 219 HTC Confidential .newSAXParser(). first an object of SAXParserFactory is created like SAXParserFactory spf=SSAXParserFactory. InputSource source=new InputSource(new FileInputStream( test.handler object)).3.XML xml parsing-SAX in this type of parsing. SAXParser sParser=spf.xml ) sParser.

3.it is an advantage for people who are more good with java and less with xml.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 .XML JAXB-XML Beans java architecture for xml-binding is meant to convert an xml representation of info into java classes.7.suppose student is the root element.java files are placed. 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 .the schemaderived 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.

newInstance( samp ). Presentation Name <Author Initial><Date> Page 221 HTC Confidential .JAXBContext like JAXBContext jxb=JAXBContext.xml.Unmarshaller can be got through Unmarshaller um=jxb.3. javax.bind.xml.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.unmarshall( students.xml ).7.bind.XML JAXB-XML Beans the above command will generate java classes which are to compiled to be used in the program.createUnmarshaller(). to get a tree of java content objects in memory under the root element Student stu=(Student)um.

Marshaller can be got through Marshaller m=jxb.createMarshaller().3.bind.you can once again you can marshall the tree as a different xml javax.7. You can marshall the xml file to any storage or to the console output m.XML JAXB-XML Beans after making any changes to the objects that are there in the tree .xml.which can be done by normal invocation of class methods on the objects.out).System. Presentation Name <Author Initial><Date> Page 222 HTC Confidential .marshall(stu.

having the root element like <xsl:stylesheet xmlns:xsl= http://www.XML XSLT-XPATH XSLT is a xml stylesheet transformation language meant for converting xml documents into other formats like xml of a different structure.7. 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). wml and predominanly used to convert xml into html.w3.html.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.

a way to pickup elements or sub-elements and a template that can instantiated to form part of the result tree.XML XSLT-XPATH XSl is a set of template rules.you can use html/xml tags freely in these templates Presentation Name <Author Initial><Date> Page 224 HTC Confidential .7.a template has two components a pattern means xpath.3. <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.

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= ...7.the match attribute tells how the element s content is matched to a value <xsl:choose><xsl:when match= .3.you can use <xsl:for-each> meant for iteration over a large number of same elements <xsl:if match= . /> the following other important elements . > used to process on reaching a condition..else if in programming Presentation Name <Author Initial><Date> Page 225 HTC Confidential . ><xsl:otherwise> is used like if.

Presentation Name <Author Initial><Date> Page 226 HTC Confidential .3..7. /> 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.XML XSLT-XPATH <xsl:sort select= .

xml )).get an instance of TransformerFactory TransformerFactory tFactory=TransformerFactory.xsl as Transformer transformer=tFactory.7.transform(src.html )). Source src=new StreamSource(new File( students. transformer.newInstance().res).newTransformer(new StreamSource(new File( students. Presentation Name <Author Initial><Date> Page 227 HTC Confidential .XML XSLT-XPATH you can use jaxp to complete the transformation in the following way. Get the transformer using the above xsl file say students.xsl ))) call transform method to get the converted html file programmatically Result res=new StreamResult(new FileWriter( students.3.

XML XSLT-XPATH Xpath is a language that consists path expressions.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.3.the value of a path expression is a node set which is mostly relevant in XSLT. location paths consists of Axis tells the direction like ancestor/ancestor-orself/attribute/child/descendant/descendant-orself/following/followingsibling/namespace/parent/preceding/precedingsibling/self Presentation Name <Author Initial><Date> Page 228 HTC Confidential .7.

node test text() is true only for leaf/text node comment().processing instructions Presentation Name <Author Initial><Date> Page 229 HTC Confidential .3. processing-instruction() for any associated comment.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.7.

XML XSLT-XPATH Abbreviations these can replace lengthy expressions above..7./student[5] Page 230 HTC Confidential .3. Presentation Name <Author Initial><Date> Parent::node() .::child is the default axis Abbreviation @ // [number] Meaning ::attribute ::descendant [position()=nu mber] self::node() Example [@color= blue ] . ../student[5] .//address student[5] .

3.actual formatting step.it is more complex than css XSL-FO output is produced from an XML source document in two steps a).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. Presentation Name <Author Initial><Date> Page 231 HTC Confidential .7.an XSLT transformation to add FO markup b).

7.3. <fo:region-body>.<fo:pagesequence-master><fo:region-after>.these areas then get rendered may not be linearly always. <fo:regionbefore>.<fo:listitem-label> Presentation Name <Author Initial><Date> Page 232 HTC Confidential . <fo:footnote><fo:listblock>. <fo:region-end>.w3. <fo:region-start>.XML XSL-FO In this process first a set of formatting objects tree is created after which a tree of areas is created.<fo:list-item-body>.<fo:simple-page-master>.org/1999/XSL/Format > <fo:block>.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.the generated files will hava .<fo:list-item>.

7.<fo:table-and-caption>.<fo:tablebody><fo:table-caption><fo:tablecell><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.XML XSL-FO <fo:table>.

Ant Presentation Name <Author Initial><Date> Page 234 HTC Confidential .8.Advanced-Java Contents -1 3.Servlets & JSP 3.Junit 3.XML 3.5.JDBC 3.Tag Libraries 3.1.Struts 3.2.JSTL 3.Struts-Tag Libraries

It is an instance of the xunit architecture for unit testing frameworks.3. 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.Junit Introduction What is JUnit? JUnit is an open source Java testing framework used to write and run repeatable tests. Presentation Name <Author Initial><Date> Page 235 HTC Confidential .8.

Installation. All the tests should pass OK.INSTALL_DIR\junit3\junit .3.Junit.zip file 2. Presentation Name <Author Initial><Date> Page 236 HTC Confidential .jar to the CLASSPATH. add junit. For example: set classpath=%classpath%. steps for installing JUnit: 1. test the installation by using either the batch or the graphical TestRunner tool to run the tests that come with this release.jar (should have any task-defined classes) 3. unzip the junit.8.

swingui.samples. Therefore make sure that the installation directory is on the class path for the batch TestRunner type: java junit.samples.AllTests for the graphical TestRunner type: java junit.TestRunner junit.TestRunner junit.3.jar but in the installation directory directly.8.AllTests for the Swing based graphical TestRunner type: java junit.textui.Junit .jar into the extension directory of your JDK installation.Installation(continued) Notice: that the tests are not contained in the junit.awtui.TestRunner junit. If you do so the test class on the files system Presentation Name <Author Initial><Date> Page 237 HTC Confidential .AllTests Important: don't install the junit.samples.

3.8. 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 .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().

Junit test case How to write and run a simple test? 1. import junit.util.framework. } Presentation Name <Author Initial><Date> Page 239 HTC Confidential .Create a subclass of TestCase: --package junitfaq.*.8. public class SimpleTest extends TestCase { public SimpleTest(String name) { super(name).3. import java.*.

assertTrue(collection.class).8. } Presentation Name <Author Initial><Date> Page 240 HTC Confidential .3. } 3.isEmpty()). 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. Write a test method to assert expected results on the object under test: --public void testEmptyCollection() { Collection collection = new ArrayList().Junit test case 2.

} } Presentation Name <Author Initial><Date> Page 241 HTC Confidential .3.run(suite()).textui.8.Junit .TestRunner.test case 4. Write a main() method to conveniently run the test with the textual test runner: --public static void main(String args[]) { junit.

3. type: -java junit. Run the test: --To run the test with the graphical test runner.test case 5.Junit .8.swingui.TestRunner junitfaq. Presentation Name <Author Initial><Date> Page 242 HTC Confidential .SimpleTest The passing test results in a green bar displayed in the graphical UI.

8.addTest(new MathTest("testDivideByZero")). suite.Junit . suite.TestSuite A TestSuite is a Composite of Tests. TestSuite suite= new TestSuite(MathTest. 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.addTest(new MathTest("testAdd")). It runs a collection of test cases Here is an example using the dynamic test definition. To do so you pass the class of your TestCase class to the TestSuite constructor.class). a TestSuite can extract the tests to be run automatically. TestSuite suite= new TestSuite().

4.Struts-Tag Libraries 3.Servlets 3.Advanced java contents-1 3.2.JSP 3.JSTL Libraries 3.1.Ant Presentation Name <Author Initial><Date> Page 244 HTC Confidential .Junit 3.9.Struts 3.7.6.XML 3.

3.describing what Ant is intended to be.9. Presentation Name <Author Initial><Date> Page 245 HTC Confidential . 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" . 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.Ant What is ant ? Introduction Ant is a Java based build tool. the name is an acronym for "Another Neat Tool".

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

Ant .3 3 March 2001 Presentation Name <Author Initial><Date> Page 247 HTC Confidential . The first official release of Ant as a stand alone product was Ant 1. This version has later been referenced to as Ant 0.1 released on 19 July 2000.3.1 release on 19 April 2000.History(continued) The first version of Ant that was exposed a lager audience was the one that shipped with Tomcat's 3.1 19 July 2000 24 October 2000 1. The complete release history: ‡ ‡ ‡ ‡ Ant Version Release Date 1.

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. This directory will be known as ANT_HOME Presentation Name <Author Initial><Date> Page 248 HTC Confidential .3. choose a directory and unzip the ant distribution zip file .

set the JAVA_HOME environment variable . Set the ANT_HOME environment variable to the directory where you installed Ant.jar file into the lib/ext directory of the JDK/JRE Presentation Name <Author Initial><Date> Page 249 HTC Confidential .Ant .jar in the classpath Do not install Ant's ant.9. Optionally.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.Keep the tools.3. This should be set to the directory where your JDK is installed.

2 set PATH=%PATH%.9.4.3. The following sets up the environment: set ANT_HOME=c:\ apache.%ANT_HOME%\bin Presentation Name <Author Initial><Date> Page 250 HTC Confidential .Ant Windows Assume Ant is installed in c:\apache-ant\.ant set JAVA_HOME=c:\jdk1.

If found. Presentation Name <Author Initial><Date> Page 251 HTC Confidential . If you use the -find option. it uses that file as the buildfile.3. Ant will search for a buildfile in the parent directory. To make Ant use another buildfile. and so on.Running Ant Running Ant is simple. use the command-line option -buildfile file. Ant looks for a build. until the root of the filesystem has been reached. when you installed it as described in the previous slides. Just type ant.Ant .xml file in the current directory. When nothing is specified.9. where file is the buildfile you want to use.

Ant .]] 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 Page 252 HTC Confidential Presentation Name <Author Initial><Date> .9.3..Running Ant Command-line option summary:--ant [options] [target [target2 [target3] ..

3. Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to this.Ant Using Ant Writing a Simple Buildfile Ant's buildfiles are written in XML.9. The value has to be unique Presentation Name <Author Initial><Date> Page 253 HTC Confidential . Each buildfile contains one project.

A task can have multiple attributes..9. Tasks have a common structure:--<name attribute1="value1" attribute2="value2" ...3. /> taskname is the name of the task taskID is a unique name for this task Presentation Name <Author Initial><Date> Page 254 HTC Confidential . /> 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" ..Ant Using Ant TASK A task is a piece of code that can be executed.

Core Task Ant Runs Ant on a supplied buildfile.3. When the antfile attribute is omitted.xml" in the supplied directory (dir attribute) is used. If no target attribute is supplied. the file "build.Ant .9. This can be used to build subprojects. the default target of the new project is used No required attributes are there Presentation Name <Author Initial><Date> Page 255 HTC Confidential .

when necessary. Examples <mkdir dir="${dist}"/> creates a directory ${dist}.3. Parameters Required Attribute s are :. <mkdir dir="${dist}/lib"/> creates a directory ${dist}/lib.9. Presentation Name <Author Initial><Date> Page 256 HTC Confidential .dir » the directory to create.Ant Mkdir core task Creates a directory. Also non-existent parent directories are created.

Ant Copy core task 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./some/dir/tree"/> Presentation Name <Author Initial><Date> Page 257 HTC Confidential . or when the destination file does not exist.3. 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.9.txt" todir=". However.

./new/dir"> <fileset dir="src_dir"/> </copy> Copy a set of files to a directory <copy todir=".3.java"/> </copy> Presentation Name <Author Initial><Date> Page 258 HTC Confidential .Ant Examples:-- core task Copy a directory to another directory <copy todir=".9./dest/dir" > <fileset dir="src_dir" > <exclude name="**/*./dest/dir" > <fileset dir="src_dir" excludes="**/*..java"/> </fileset> </copy> <copy todir="..

Presentation Name <Author Initial><Date> Page 259 HTC Confidential .3.Ant javac core task Compiles a Java source tree. Required attributes are :. Only Java files that have no corresponding class file or where the class file is older than the java file will be compiled.9. The source and destination directory will be recursively scanned for Java source files to compile.srcdir location of the java files.

and stores the .9. The classpath used contains xyz.java files under the ${src} directory. Presentation Name <Author Initial><Date> Page 260 HTC Confidential .jar debug="on" /> compiles all . and debug information is on.3.Ant core task Examples:-<javac srcdir="${src} destdir="${build}" classpath="xyz.class files in the ${build} directory.jar.

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 . In case this happens.exit(). because it will terminate the VM and thus Ant.exit() stops the other VM and not the one that is currently running Ant. Be careful that the executed class doesn't call System.9.3.Ant java core task Executes a Java class within the running (Ant) VM or forks another VM if specified. it's highly suggested that you set the fork attribute so that System.

Presentation Name <Author Initial><Date> Page 262 HTC Confidential .9.jarfile » the jar-file to create. Required Attributes are :.3. The basedir attribute is the reference directory from where to jar.Ant jar core task Jars a set of files. Note that file permissions will not be stored in the resulting jarfile.

jar basedir="${build}/classes /> jars all files in the ${build}/classes directory into a file called app.jar in the ${dist}/lib directory.jar in the ${dist}/lib directory.Ant core task Examples:-<jar jarfile="${dist}/lib/app.jar" basedir="${build}/classes" excludes="**/Test.3.class" /> jars all files in the ${build}/classes directory into a file called app.9. <jar jarfile="${dist}/lib/app.class are excluded Presentation Name <Author Initial><Date> Page 263 HTC Confidential . Files with the name Test.

) Required attributes are :earfile the ear-file to create. The same thing can be accomplished by using the prefix and fullpath attributes of zipfilesets in a Zip or Jar task. appxml location of application. (The Ear task is a shortcut for specifying the particular layout of a EAR file.9.Ant ear core task An extension of the jar task with special treatment for files that should end up in an Enterprise Application archive.3.xml file basedir location of files Presentation Name <Author Initial><Date> Page 264 HTC Confidential .

) The extended zipfileset element from the zip task (with attributes prefix.9. WEBINF/classes or WEB-INF directories of the Web Application Archive.Ant War core task An extension of the jar task with special treatment for files that should end up in the WEB-INF/lib. and src) is available in the War task Presentation Name <Author Initial><Date> Page 265 HTC Confidential . (The War task is a shortcut for specifying the particular layout of a WAR file. fullpath. The same thing can be accomplished by using the prefix and fullpath attributes of zipfilesets in a Zip or Jar task.3.

xml). Presentation Name <Author Initial><Date> Page 266 HTC Confidential .Ant core task Required Attributes are:Warfile the war-file to create.3.9. webxml The deployment descriptor to use (WEBINF/web.

Ant zip core task Creates a zipfile. The basedir attribute is the reference directory from where to zip.zipfile » the zip-file to create.3.9. Presentation Name <Author Initial><Date> Page 267 HTC Confidential . file permissions will not be stored in the resulting zipfile Required attributes are:.

If 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.Ant core task Examples:-1. 2. it is created.zip basedir="htdocs/manual /> zips all files in the htdocs/manual directory into a file called manual.9. <zip zipfile="${dist}/manual.zip in the ${dist} directory. otherwise it is updated with the new/changed files. <zip zipfile="${dist}/manual. Presentation Name <Author Initial><Date> Page 268 HTC Confidential .zip doesn't exist.3.

Ant core task 3. <zip zipfile="${dist}/manual.html" /> zips all files in the htdocs/manual directory.9.html are excluded Presentation Name <Author Initial><Date> Page 269 HTC Confidential .3. 4. <zip zipfile="${dist}/manual.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. **/todo. or files with the name todo.html" excludes="**/todo.zip basedir="htdocs/manual" includes="api/**/*.zip" basedir="htdocs/manual" excludes="mydocs/**. Files in the directory mydocs.

9. Attributes (Optional) are showoutput test s output to Ant's logging system as well as to the formatters(default only).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.3.For this you have to put junit. 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 .Ant core task Integrating Junit testing with Ant This will enable testing Junit framework tests from ant environment.

value= /> Presentation Name <Author Initial><Date> Page 271 HTC Confidential ..3./>(required) <test name=classname outfile= <formatter type=plain/xml/brief classname= ./> <sysproperty key= .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 .

users and contributors can create other templates and @tags and add support for other technologies also.xml generation.3.xml or ejb-jar. 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.Ant core task xdoclet: XDoclet is an extended javadoc doclet engine.9. XDoclet supports a set of common standard tasks such as web. 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 .

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

* * @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.9. It is an example of how to use the * EJBDoclet tags. For example: @jboss:create-table create="${jboss.Account" */ these will have generic syntax @namespace:tag-name parameter-name="parameter value Tag values can be specified as ant properties.3.Ant xdoclet: core task /** * This is an Item bean.create.table}" Presentation Name <Author Initial><Date> Page 274 HTC Confidential .interfaces.

@author" ejbspec="2.path}.jar.pat h}" /> <ejbdoclet sourcepath="${java.EjbDocletTask" classpath="${xdoclet.path}.jar.class.${log4j.dir}"> <include name="**/*Bean.ejb.3.${ant.Ant core task xdoclet: typical ant task will appear as <target name="ejbdoclet" depends="prepare"> <taskdef name="ejbdoclet" classname="xdoclet.dir}" destdir="${generated.0" force="${xdoclet.9.java.jar.dir}" classpathref="project.java" /> </fileset> Presentation Name <Author Initial><Date> Page 275 HTC Confidential .path" excludedtags="@version.force}"> <fileset dir="${java.

Ant-Core Tasks <dataobject/> <remoteinterface/> <localinterface/> <homeinterface/> <localhomeinterface/> <entitypk/> <entitycmp/> <deploymentdescriptor destdir="${build.4" xmlencoding="UTF-8" typemapping="Hypersonic SQL" datasource="java:/DefaultDS" destdir="${build.dir}/ejb/METAINF"/> <jboss version="2.dir}/ejb/META-INF"/> </ejbdoclet> </target> Presentation Name <Author Initial><Date> Page 276 HTC Confidential .9.3.

9.you are using. Presentation Name <Author Initial><Date> Page 277 HTC Confidential .3.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.

NET. Building and deploying a C#-based Web Service.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.useful ones are Integrating with a Java based SOAP Service -generating C# code from the server's WSDL and running it against the server. then using the Apache Axis tasks to create JUnit tests to call the endpoints. Here.Net NET tasks can be used to a limited extent. anyone who has a cross-platform project can use these tasks to cover the . . Patching .NET side of the problem.9. cross-platform can mean more than just Java and .3. Hence the disassembler and the reassembler.NET type libraries to work with more complex IDL than the basic <importtypelib> wrapper around tlbimport supports. Presentation Name <Author Initial><Date> Page 278 HTC Confidential .

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 .NET executables and libraries assembles .net code compiles j# code disassembles .is files Generates .Ant-Core Tasks the tasks are Task-Name Csc Vbc jsharpc ildasm ilasm WsdlToDotnet Usage compiles c# code compiles vb.3.9.

Ant-Core Tasks Resource This is a resource that is included in the build. 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. password .3.can use get/del/list/) Presentation Name <Author Initial><Date> Page 280 HTC Confidential .important attributes are server . Ant uses this for dependency checking -if resources included this way have changed. userid . action (default is send.9.

Thank You Presentation Name <Author Initial><Date> Page 281 HTC Confidential .

Sign up to vote on this title
UsefulNot useful