Java EE Course Material - Srikanth Pragada

April 2, 2018 | Author: Dany Cenas Vásquez | Category: Software Engineering, Data, Information Retrieval, Data Management Software, Areas Of Computer Science


Comments



Description

Java EECourse Material Srikanth Pragada (SCJP, SCWCD, SCBCD, MCTS for .Net 4.0, Oracle Database SQL Expert, Oracle PL/SQL Associate Developer) COPYRIGHT Copyright @ 2016 by Srikanth Technologies. All rights reserved. No part of this book may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the author & publisher – Srikanth Pragada, with the exception that the programs may be entered, stored, and executed in a computer system, but they may not be reproduced for publication. Although every precaution has been taken in the preparation of this book, the author assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of information contained therein. Srikanth Technologies ABOUT THE AUTHOR Srikanth Pragada is the director of Srikanth Technologies, a software training company. He started programming in early 90s and worked with more than 15 different programming languages. Srikanth Pragada holds the following certifications:  Sun Certified Java Programmer  Sun Certified Web Component Developer  Sun Certified Business Component Developer  Oracle Database SQL Certified Expert  Oracle PL/SQL Developer Certified Associate  Microsoft Certified Technology Specialist for .NET 4.0  (Web Applications) He currently conducts online, classroom and onsite training on C, Java, Oracle, Microsoft.NET and Android technologies. His website www.srikanthtechnologies.com provides more information about C, Java, Android programming, Oracle and Microsoft.Net. It contains online examinations, programs, projects, articles and his blog. When he is not teaching or learning, he would like to visit new places, read books, involve in sports and listen to music. He can be reached through his email address [email protected]. Srikanth Technologies HOW TO USE THIS MATERIAL This is to be carried to classroom everyday as long as the contents of this material are being discussed. You are suggested to read relevant content before and after attending the class. Use picture and text to grasp the concept. Programs are to illustrate how to implement the concepts. Try the programs given in this material in your system. REQUEST FOR FEEDBACK We have taken considerable effort to ensure accuracy of the contents of this material. However if you come across any mistakes or have any suggestions to improve the quality of this material, please take a few minutes of your valuable time to send mail to me at [email protected]. Alternatively you can visit my website www.srikanthtechnologies.com/feedback.aspx and provide feedback there. Srikanth Technologies JDBC SQL>connect SYSTEM 3. enter password that you gave at the time of installing Oracle. So you must log in as SYSTEM (DBA) to unlock this account. DEPARTMENTS etc. The password of this account is expired by default. But this account is locked by default. SQL>alter user hr identified by hr. When prompted to enter password. Use CONNECT command at SQL> prompt to connect to Oracle using SYSTEM account. … Note: HR account comes with a set of tables like EMPLOYEES. JOBS. Then connect Oracle as HR by using CONNECT command as follows: SQL>Connect hr/hr SQL>select * from tab. 5. SQL>alter user hr account unlock. Srikanth Technologies . Unlock HR account and reset password by giving following two commands at the SQL> prompt.JDBC 1 Getting Started With Oracle11g Express Edition Oracle11g express edition provides HR account by default. StartAll ProgramsOracle Database 11g Express EditionRun SQL Command Line. 2. Steps to unlock HR Account: 1. 4. SQL>select * from jobs. so you have to reset password as well. The following are the tables we use in Java programs.JDBC 2 The following are some of the tables that come with HR account.2) MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4) SQL> desc departments Name Null? Type ---------------------------------. SQL> desc jobs Name Null? Type ---------------------------------. -------------- DEPARTMENT_ID NOT NULL NUMBER(4) DEPARTMENT_NAME NOT NULL VARCHAR2(30) MANAGER_ID NUMBER(6) LOCATION_ID NUMBER(4) SQL> Srikanth Technologies .-------------- EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8.-------.-----------.2) COMMISSION_PCT NUMBER(2. -------. -------.JOB_ID NOT NULL VARCHAR2(10) JOB_TITLE NOT NULL VARCHAR2(35) MIN_SALARY NUMBER(10) MAX_SALARY NUMBER(6) SQL> desc employees Name Null? Type ---------------------------------. Both packages are included in the Java SE and Java EE platforms What is JDBC Driver?  To use the JDBC API with a particular DBMS.sql and javax.x API is divided into two packages: java. It is standard API to access databases from Java  Using JDBC API you can access any database that may run on any platform  The JDBC 4.sql. you need a JDBC technology-based driver to access database  Driver must support at least ANSI SQL-2 Entry Level (1992) Srikanth Technologies .JDBC 3 What is JDBC (Java Database Connectivity)?  The JDBC API provides universal data access from Java language  JDBC is Java API to execute SQL Statements. A driver contains a collection of classes to implement these interfaces. Driver The interface that every driver class must implement. These interfaces are implemented by driver. DatabaseMetaData Comprehensive information about the database as a whole. JDBC-ODBC The JDBC-ODBC bridge allows ODBC drivers to be bridge used as JDBC drivers. Important Interfaces The following are the interfaces provided with JDBC API. ResultSet A ResultSet provides access to a table of data. Connection A connection (session) with a specific database. It actually is quite small and simple. It provides a way to access less popular DBMS if JDBC driver is not implemented for it. Interface Meaning CallableStatement The interface used to execute SQL stored procedures. its primary function is to connect Java applications to the correct JDBC driver and then get out of the way. Srikanth Technologies . JDBC driver The JDBC driver manager is the backbone of the manager JDBC architecture. ResultSetMetaData An object that can be used to find out about the types and properties of the columns in a ResultSet.JDBC 4 JDBC Components JDBC provides the following components as part of the JDK. PreparedStatement An object that represents a precompiled SQL statement. Date that allows JDBC to identify this as SQL TIMESTAMP value. Class Description Date A thin wrapper around a millisecond value that allows JDBC to identify this as SQL DATE.util. Important Classes The following are the classes provided by JDBC API.JDBC 5 Statement The object used for executing a static SQL statement and obtaining the results produced by it. Srikanth Technologies .sql package. DriverPropertyInfo Driver properties for making a connection. Timestamp This class is a thin wrapper around java. Time A thin wrapper around java. called JDBC types.util. DriverManager Class  Part of java.  Sits between the application programs and the drivers.Date that allows JDBC to identify this as SQL TIME value. used to manage JDBC drivers. DriverManager The basic service for managing a set of JDBC drivers. These classes are provided in addition to interfaces mentioned above. Types The class that defines constants that are used to identify generic SQL types.  Keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. String un. Enumeration getDrivers() Returns the drivers that are currently loaded. void registerDriver (Driver Registers the given driver.JDBC 6 Method Meaning Connection getConnection Establishes a connection with the (String url. int getMinorVersion() Returns minor version number. Properties info) int getMajorVersion() Returns major version number. connection object. specified database. String pwd) Driver getDriver(String url) Returns a driver that can understand the URL. Connection Connects to a database and returns connect(String url. Method Meaning boolean Returns true if the driver thinks that it can acceptsURL(String url) open a connection to the given URL. driver) Driver Interface  This is the interface that every driver has to implement.  Each driver should supply a class that implements the Driver interface. Srikanth Technologies . JDBC 7 Connection interface  Represents a connection to specific database. Method Meaning Statement createStatement() Creates and returns an object of Statement Statement createStatement Creates a Statement object that (int resultSetType. will generate ResultSet objects int resultSetConcurrency) with the given type and concurrency DatabaseMetaData Returns an object of getMetaData() DatabaseMetaData.  SQL statements are executed and results are returned within the context of a connection. which can be used to get information about the database boolean isClosed() Returns true if connection is closed Srikanth Technologies . 02: import java.close().getConnection 09: ("jdbc:oracle:oci8:@".driver.DriverManager.printStackTrace(). 11: con. 15: } 16: } // end of main 17: } // class Srikanth Technologies . username and password.OracleDriver").println("Connected Using OCI driver").sql.JDBC 8 CallableStatement Creates a callable statement prepareCall(String sql) PreparedStatement Creates a prepared statement prepareStatement(String sql) void close() Closes the connection Steps to connect to Oracle using OCI driver  Include ojdbc6.Connection.sql. 12: } 13: catch(Exception ex) { 14: ex. loading driver class is optional  Establish a connection to database by using DriverManager.forName("oracle."hr".jdbc.getConnection() with required connection string. 03: 04: public class OracleOCIConnection { 05: public static void main(String args[]) { 06: try { 07: Class.jar file in classpath of the application  Load jdbc driver for Oracle using Class.0. 10: System. 01: import java.forName() method  Starting from Jdbc 4.out. 08: Connection con = DriverManager."hr"). getConnection 08: ("jdbc:oracle:thin:@localhost:1521:XE".  Connection string contains host. 02: import java. username and password.Connection. port number of listener.out.printStackTrace(). 14: } 15: } // end of main 16: } // end of OracleThinConnection Srikanth Technologies .JDBC 9 Using Oracle’s Thin driver  Thin driver provided by Oracle belongs to Type 4 category of JDBC drivers. 01: import java. 03: 04: public class OracleThinConnection { 05: public static void main(String args[]) { 06: try (Connection con = 07: DriverManager. oracle instance name.DriverManager.sql.sql.  This accesses oracle’s TNS listener on the server.println("Connected Using Thin Driver"). 11: } 12: catch (Exception ex) { 13: ex. 09: "hr". "hr")) { 10: System. but it is recommended that you use datasources.  You can use both facilities in the same application.  Method setConnectionCachingEnabled(true) is used to turn on connection pooling. so that you can access databases by logical names. It can be implemented in three different ways:  A basic DataSource implementation produces standard Connection objects that are not pooled or used in a distributed transaction. Srikanth Technologies . datasources can be bound to Java Naming and Directory Interface (JNDI) entities.JDBC 10 DataSource  Datasource objects can provide connection pooling and distributed transactions. that is.  A DataSource implementation that supports distributed transactions produces Connection objects that can be used in a distributed transaction.  A DataSource implementation that supports connection pooling produces Connection objects that participate in connection pooling.  For convenience and portability. a transaction that accesses two or more DBMS servers.  The datasource facility provides a complete replacement for the previous JDBC DriverManager facility. The DataSource interface is implemented by a driver vendor. that is. connections that can be recycled. so that the number of connections is limited only by the number of database sessions configured for the database.jdbc.pool.println 15: ("Connected To Oracle using DataSource"). MinLimit Sets the minimum number of connections the cache maintains.JDBC 11 The following are the properties related to connection pool. Property Meaning InitialLimit Sets how many connections are created in the cache when it is created or reinitialized. 16: } 17: } // main() 18: } Srikanth Technologies . This guarantees that the cache will not shrink below this minimum limit.out.MAX_VALUE.setURL("jdbc:oracle:thin:@localhost:1521:xe").OracleDataSource. Default is 0. Default is 0. 3: 4: public class OracleDatasourceConnection { 5: 6: public static void main(String[] args) 7: throws Exception { 8: OracleDataSource ods = new OracleDataSource(). 2: import oracle.getConnection()) { 14: System. The default value is Integer. 1: import java. MaxLimit Sets the maximum number of connection instances the cache can hold. 11: ods. 9: ods. 10: ods.setPassword("hr").Connection.sql. 12: 13: try (Connection con = ods. meaning that there is no limit enforced by the connection cache.setUser("hr"). 3: import java.setUser("hr"). 20: 21: try (Connection con = ods. 18: prop.setProperty("MaxLimit".jdbc. 10: ods.setProperty("InitialLimit".setConnectionCacheProperties(prop). 2: import java.util. 24: } 25: } 26: } Srikanth Technologies .setPassword("hr").OracleDataSource. "25").setURL("jdbc:oracle:thin:@localhost:1521:xe"). 12: ods.println 23: ("Connected To Oracle using DataSource").setProperty("MinLimit".Connection.out.getConnection()) { 22: System. "5"). 4: import oracle.JDBC 12 The following program enables connection pooling and sets connection pool settings: 1: import java. 11: ods.Scanner.setConnectionCachingEnabled(true).Properties. 14: 15: Properties prop = new Properties(). 13: ods. 17: prop.util.sql.pool. 5: 6: public class OracleDatasourceWithCP { 7: public static void main(String[] args) 8: throws Exception{ 9: OracleDataSource ods = new OracleDataSource(). 16: prop. "5"). 19: ods. out.println("Updation is unsuccessful").out. 10: "hr".sql.executeUpdate("update employees 14: set salary=salary*1.println("Updation is successful"). 3: import java.sql. 20: } catch (Exception ex) { 21: ex. 15: 16: if (count == 1) 17: System. 2: import java. 22: } 23: } // end of main 24: } // end of ExecuteUpdate Srikanth Technologies .printStackTrace(). 11: Statement st = con.JDBC 13 Steps to execute an SQL command  Establish a connection to database  Create a statement using createStatement() method of Connection interface  Execute an SQL statement using one of the methods of Statement interface 1: import java.getConnection 9: ("jdbc:oracle:thin:@localhost:1521:XE".Connection.DriverManager.sql.Statement.createStatement()) { 12: 13: int count = st. 4: 5: public class ExecuteUpdate { 6: public static void main(String args[]){ 7: try (Connection con = 8: DriverManager. "hr"). 18: else 19: System.1 where employee_id=120"). Srikanth Technologies . boolean execute(String) Executes SQL command and returns true if query is executed.  Contains a cursor that points to a particular record in the ResultSet.  This cursor is positioned initially before the first row. int getUpdateCount() Returns update count of most recently executed command.  Columns are numbered from 1. of rows updated. The following are the constants declared in ResultSet interface that are used at the time of creating a Statement to specify the type of ResultSet required. Columns can be referred either by column number or name.  Only one ResultSet per a statement can be opened at a time. int executeUpdate(String) Executes DML command and returns the no.  At the time of creating Statement we have to specify what type of ResultSet is to be created from this Statement.  A ResultSet may be either scrollable or forward only.JDBC 14 Statement Interface  Is used to execute an SQL command. ResultSet Interface  Provides access to a set of rows. void close() Enables the resources to be released. Connection getConnection() Returns the connection object that produced this statement. ResultSet getResultSet() Returns current ResultSet.  You can retrieve values of columns using get<type>() methods. Method Meaning ResultSet Executes the query in the statement executeQuery(String) and returns ResultSet. It may be either updatable or read-only. TYPE_FORWARD_ONLY The type for a ResultSet object whose cursor may move only forward.JDBC 15 CONCUR_READ_ONLY Concurrency mode for a ResultSet object that may NOT be updated. CONCUR_UPDATABLE Concurrency mode for a ResultSet object that may be updated. TYPE_SCROLL_INSENSITIVE The type for a ResultSet object that is scrollable but generally ResultSet is insensitive to changes made to the underlying data source while it is open. ResultSet Record Pointer Srikanth Technologies . TYPE_SCROLL_SENSITIVE The type for a ResultSet object that is scrollable and reflects changes made to the underlying data source while the result set remains open. boolean previous() Moves to the previous record. getMetaData() boolean next() Moves cursor to next row and returns true if next row is valid. void beforeFirst() Moves to immediately before first record. type get<type> Returns the value of the column identified (String name) by name. boolean wasNull() Returns true when the last columns read was null. ResultSetMetaData Returns metadata of the ResultSet. void afterLast() Moves to immediately after the last record. cancelRowUpdates() int Maps the given ResultSet column name to findColumn(columnName) its ResultSet column index. Returns true on success. boolean isLast() Returns true if cursor is on the last record. boolean relative(int) Moves forward or backward by specified number of rows. void close() Closes ResultSet. boolean isAfterLast() Returns true if cursor is after the last record. boolean Moves the cursor to the given row. boolean isFirst() Returns true if cursor is on the first record. boolean last() Moves to the last record. Row number starts with 1. int getRow() Returns current row number. boolean first () Moves to first record.JDBC 16 Method Meaning type get<type> Returns the value of the column identified (int index) by index. absolute(int row) void Cancels the updates made to a row. Returns true on success. boolean isBeforeFirst() Returns true if cursor is before the first Srikanth Technologies . getInt(1) + " . void update<type>(int. void deleteRow() Deletes the current row of the ResultSet from the table. 2: import java.ResultSet.out.sql.createStatement().executeQuery 13: ("select employee_id.getConnection( 9: "jdbc:oracle:thin:@localhost:1521:XE".Connection.next()) { 16: System. moveToInsertRow() void insertRow() Appends the new row to the table. 11: ResultSet rs = 12: st. void updateRow() Updates the database with the new contents of the current row. void refreshRow() Refreshes current row with its most recent values in the database. 3: import java. Changes the existing data." + 17: rs. "hr")."hr". 5: public class EmployeeList { 6: public static void main(String args[]) { 7: try (Connection con = 8: DriverManager. value) void Cancels the updates made to a row.Statement.JDBC 17 record.DriverManager. 10: Statement st = con. 4: import java.sql.getString("first_name")). 18: } // end of while 19: } // end of try 20: catch (Exception ex) { Srikanth Technologies .println(rs.sql. cancelRowUpdates() void Creates a new blank row.first_name from 14: employees where employee_id <= 110")) { 15: while (rs. 1: import java.sql. 18: // values before change 19: System.println(rs. 1: import java. min_salary 15: from jobs")){ 16: // goto last row 17: rs.getConnection( 9: "jdbc:oracle:thin:@localhost:1521:XE".getString(2)). 20: System. 4: import java.Connection. 13: ResultSet rs = st.println(rs.Statement.createStatement (ResultSet.sql.out.TYPE_SCROLL_INSENSITIVE.sql. First parameter specifies scrollable nature of the ResultSet.sql.CONCUR_UPDATABLE).ResultSet.TYPE_SCROLL_INSENSITIVE. 12: ResultSet.createStatement 11: (ResultSet.job_title.CONCUR_UPDATABLE). "hr". first the Statement object is to be created as follows: Statement st= con.out.JDBC 18 21: ex. 3: import java. The second parameter of createStatement() specifies whether ResultSet created from this Statement is updatable or read-only.executeQuery( 14: "select job_id.last(). 22: } 23: } // end of main 24: } // end of EmployeeList Modifying Rows in ResultSet In order to update a ResultSet. Srikanth Technologies . 2: import java. 5: public class UpdateResultSet { 6: public static void main(String[] args) 7: throws Exception { 8: try (Connection con = DriverManager.getString(3)).ResultSet.DriverManager.printStackTrace().sql. 10: Statement st = con. "hr"). println(rs. 10: PreparedStatement ps = con.sql. 4: 5: public class ChangeName { 6: public static void main(String args[]) { 7: try (Connection con = 8: DriverManager.getString(2)). 2: import java. // update database 24: 25: // values after change 26: System. Sets the given value to the parameter at the value) specified index.prepareStatement 11: ("update employees set first_name = ? 12: where employee_id = ? ")) { Srikanth Technologies . 27: System.out. 1: import java. void set<type>(int .  Extends Statement interface."hr").out.println(rs.getString(3)). Command can be executed efficiently for multiple times.sql.Connection.println(ex). Method Meaning void clearParameter() Clears values of all parameters."hr". 30: } 31: } 32: } PreparedStatement Interface  Contains a precompiled SQL statement.sql. Obtained using prepareStatement() method of Connection interface. 28: } catch (Exception ex) { 29: System. 3: import java. 23: rs. rs.updateRow().updateInt(3.out.DriverManager.getConnection 9: ("jdbc:oracle:thin:@localhost:1521:XE".getInt(3) + 1000).JDBC 19 21: // update minimum salary 22: rs.PreparedStatement. out.setInt(2.]} To call a procedure: {call <procedure-name>[<arg1>. 100). (int index. 22: } 23: } // end of main 24: } CallableStatement Interface  Used to execute a stored procedure or function. "SMITH"). 16: if (rows == 1) 17: System.printStackTrace(). To call a function: {?=call<function-name>[<arg1>.println("Updation is unsuccessful"). .println("Updation is successful").setString(1.out. 14: ps. 20: } catch (Exception ex) { 21: ex. 18: else 19: System. Srikanth Technologies .  It extends PreparedStatement interface.]} Method Meaning type get<type> Returns the value of the given parameter.<arg2>.int type) boolean wasNull() Returns true if last OUT parameter read has SQL NULL. .JDBC 20 13: ps. (int index) void Registers an OUT parameter at the specified registerOutParameter parameter index to the SQLType.<arg2>..... 15: int rows = ps.executeUpdate(). setInt(2. 6000).sql.Connection. "hr"). 1: import java. 6: commit.){ 11: 12: // set employee number 13: cs.execute(). 8: "hr". 100).?)}"). 20: } 21: } // end of main 22: } Srikanth Technologies . 4: public class CSExample { 5: public static void main(String args[]) { 6: try (Connection con = DriverManager.prepareCall("{call UpdateSalary(?. 9: CallableStatement cs= 10: con. 14: // set salary 15: cs. 7: end.println("Error : " + ex).JDBC 21 UPDATESALARY procedure 1:create or replace procedure UpdateSalary(p_empid number.getConnection 7: ("jdbc:oracle:thin:@localhost:1521:XE". 16: // execute update command 17: cs.DriverManager. 2: import java. 18: } catch (Exception ex) { 19: System.sql.out.CallableStatement.setInt(1. 2: p_sal number) is 3: begin 4: update employees set salary = p_sal 5: where employee_id = p_empid. 3: import java.sql. boolean isNullable(int) Returns true if column can contain null. String Returns the version of this database getDatabaseProductVersion() product. DatabaseMetaData Interface It provides information about the database. String getColumnName(int) Returns the name of the column. int getColumnType(int) Returns column's SQL type. Note: Use getMetaData() method of ResultSet to get ResultSetMetaData object. We can find out the features supported by database and objects available in database.JDBC 22 ResultSetMetaData Interface It contains the properties of columns in the ResultSet. String getTableName(int) Returns the table name for the given column. int getScale(int column) Gets a column's number of digits to right of the decimal point. Method Meaning String Returns the name of this database getDatabaseProductName() product. int getPrecision(int) Gets a column's number of decimal digits. Srikanth Technologies . int getColumnDisplaySize(int) Indicates the column's normal max width in chars. String Retrieves a column's database- getColumnTypeName(int) specific type name. of columns in the ResultSet. Method Meaning int getColumnCount() Returns the no. For example. available in the specified catalog. String tabletype[]) ResultSet getColumns Gets a description of table columns (String catalog.jar. String tableNamePattern. ResultSet getTables (String Returns the list of tables that match catalog. . the criteria. . The following picture shows the relationship between JDBC interface and classes in Oracle driver. . String table. . String schema. JDBC driver for Oracle is a collection of classes provided in a single jar file – ojdbc6. String schemaPattern. Jdbc driver is a collection of classes that implements JDBC interfaces. String columnNamePattern) Note: Use getMetaData() method of Connection object to get DatabaseMetaData object. Srikanth Technologies .JDBC 23 ResultSet getSchemas() Returns the list of schemas of the database. Oracle Driver JDBC is a collection of interfaces and a few classes. . JDBC Interfaces vs. JDBC Interface Class in Oracle Driver Driver OracleDriver Connection OracleOCIConnection Statement OracleStatement ResultSet OracleResultSet . Srikanth Technologies .JDBC 24 Type of JDBC Drivers The following are different types of JDBC drivers that can be used with JDBC.  Requires the ODBC driver to be present on the client.  JDBC-ODBC Bridge Driver  Native API Partly Java Driver  Network Protocol Pure Java Driver  Native Protocol Pure Java Driver JDBC-ODBC bridge driver  Allows you to access any ODBC data source using ODBC Driver. JDBC driver accesses ODBC driver. 5. 8. 3. Srikanth Technologies . 6. Select Data Sources (ODBC). In case you access Oracle from a remote client then enter Oracle service name in Server field. Select Oracle In XE from List of Drivers and click on Finish. 4. In the next dialog box enter Data Source name – oraclejava and other information such as username and password. 7. Now oraclejava must appear in the list of DSNs. Select Administrative tools. It displays ODBC Data Source Administrator window. first we have to create DSN (Data Source Name) using ODBC administrator (steps are given below) and then use DSN in connection URL. 2. Go to User DSN tab and click on Add button. Steps to create Data Source Name (DSN): 1. Invoke Control Panel. Click on Ok button.JDBC 25 Java Application Type 1 JDBC Driver ODBC Driver Database Using JDBC-ODBC Bridge Driver In order to use ODBC driver. 3: public class OracleODBCConnection { 4: public static void main(String args[]) { 5: try (Connection con = DriverManager. 11: } 12: } 13: } Srikanth Technologies . 1: import java.println("Connected using ODBC driver").out. Change the steps regarding ODBC Administrator in case you use another operating system.printStackTrace().sql.DriverManager. 8: } 9: catch (Exception ex) { 10: ex. 2: import java.getConnection 6: ("jdbc:odbc:oraclejava".sql.Connection.JDBC 26 Note: The above process lists steps in Windows 7 or above. "hr")) { 7: System. "hr".  Fusion Middleware is an example for middleware. Java Application Type 3 JDBC Driver Middleware API Database Srikanth Technologies .  This driver is provided by middleware (application server) vendor. which is then translated to a DBMS protocol by a server.  Requires that some binary code be loaded on each client machine.JDBC 27 Native API partly Java driver  Converts JDBC calls into calls on the client API for Oracle.  Oracle’s OCI driver is an example for this. or other DBMS. Informix. DB2.  Clients need not have any binary code. Sybase. Java Application Type 2 JDBC Driver Native API Database Network Protocol Pure Java driver  Translates JDBC calls into a DBMS-independent net protocol. Method Meaning void setAutoCommit(boolean) Turns on/off auto commit mode. Srikanth Technologies . Transaction Management  A transaction consists of one or more statements that have been executed. the method commit will be called on that statement automatically. completed. meaning that when a statement is completed. driver categories 3 and 4 will be the preferred way to access databases from JDBC. boolean getAutoCommit() Returns the current auto commit mode. void commit() Makes all changes since previous commit point permanent. Java Application Type 4 JDBC Driver Database Note: Eventually.  A new connection is in auto-commit mode by default. the current transaction ends and another one begins. and then either committed or rolled back.JDBC 28 Native-protocol Pure Java driver  This kind of driver converts JDBC calls into the network protocol used by DBMS directly. When the method commit or rollback is called.  Oracle Thin driver is an example for this. Savepoint Sets a savepoint in the current setSavepoint(name) transaction. void rollback(Savepoint) Rolls back changes made from the given savepoint.executeUpdate(sqlcommand).executeUpdate(cmd2)..  Method releaseSavepoint(savepoint) releases savepoint from the current transaction. int rows = stmt. con.JDBC 29 void rollback() Drops all changes made since the previous commit/rollback.. if ( rows > 5 ) conn.executeUpdate( sqlcommand ). } Savepoints  Savepoint is a point within a transaction to which you can roll back.executeUpdate(cmd1). Srikanth Technologies . conn. Connection interface provides setSavepoint () method to set savepoint. try { st.commit(). Savepoint savepoint1 = conn..createStatement(). st.setAutoCommit(false). Statement stmt = conn. void releaseSavepoint(sp) Releases savepoint from current transaction.rollback(svpt1).setSavepoint("SAVEPOINT1").commit(). rows = stmt. .rollback(). con. . } catch(Exception ex) { con.. out.Statement. 27: con. 22: } // end of for loop 23: } 24: catch (BatchUpdateException ex) { 25: System.rollback().println("Batch Update Exception :" + 26: ex. 10: Statement stmt = con.//execute batch 18: con."hr")) { 09: con. 28: } Srikanth Technologies .Connection.DriverManager. 05: public class BatchUpdateDemo { 06: public static void main(String args[]) { 07: try (Connection con = DriverManager.sql. i < uc.executeBatch().getConnection 08: ("jdbc:oracle:thin:@localhost:1521:xe".addBatch("update employees set 13: salary=salary+2000 where salary>10000").out. 19: 20: for (int i = 0. 01: import java.sql.  Reduces overhead on database server as it has to execute only one command.JDBC 30 Batch Updates  It allows multiple DML statements to be executed in a single request. 02: import java.createStatement().getMessage()).commit().addBatch("update employees set 15: salary=salary+1000 where salary<10000"). 04: import java. 14: stmt.sql.length.  Improves performance when large number of statements are executed."hr". 16: 17: int[] uc = stmt. i++) { 21: System.println(i + ":" + uc[i]). 11: try { 12: stmt.sql. 03: import java.BatchUpdateException.setAutoCommit(false). url.  CachedRowSet  JDBCRowSet  WebRowSet  FilteredRowSet  JoinRowSet Srikanth Technologies . The following are different types of rowsets offered by Oracle. data source name. type. 32: } 33: } // end of main 34: } // BatchUpdateDemo RowSet  A RowSet is an object that encapsulates a set of rows from either JDBC ResultSet or tabular data sources. with a standard set of properties and an event notification mechanism.  A rowset's properties include its command. user name.printStackTrace().JDBC 31 29: } // outer try 30: catch (Exception ex) { 31: ex. password etc.  RowSets support component-based development models like JavaBeans. Application components.removeRowSetListener method. rowChanged This event is generated when a row is inserted.RowSetListener interface and register such listener objects with a RowSet object.sql.sql. must implement the standard javax. updated. rowset. rowSetChanged This event is generated when the whole RowSet is created or changed. cursorMoved This event is generated whenever there is a cursor movement.ResultSet interface.sql. For example.RowSet interface extends the java.addRowSetListener method and unregistered using the RowSet. Srikanth Technologies .addRowSetListener(new OracleRowSetListenerAdapter () { public void rowSetChanged(RowSetEvent event) { } } ). The javax.JDBC 32 RowSet Events The following types of events are supported by the RowSet interface. when the execute method is called. For example. or deleted from the RowSet. A listener can be registered using the RowSet. when the next or previous method is called. which are interested in these events. void execute() Fills this RowSet object with data. void Sets the concurrency of setConcurrency(int concurrency) this RowSet object to the given concurrency level. Srikanth Technologies . void setUrl(String url) Sets the URL this RowSet object will use when it uses the DriverManager to create a connection.JDBC 33 The following are important methods of RowSet. void Sets the database password for setPassword(String password) this RowSet object to the given String. Method Description void clearParameters() Clears the parameters set for this RowSet object's command. void setType(String columnName. void setCommand(String cmd) Sets this RowSet object's command property to the given SQL query. void Sets the data source name setDataSourceName(String name) property for this RowSet object to the given String. void setType(int parameterIndex. Sets the value to the given Type value) parameter identified by columname. Sets the value to the given Type value) parameter identified by index. it does not maintain an active connection to the database. insert and delete changes made to this CachedRowSet object to the underlying data source. Srikanth Technologies . void commit() Each CachedRowSet object's SyncProvide contains a Connection object from the ResultSet or JDBC properties passed to its constructors. CachedRowSet A CachedRowSet is a RowSet in which the rows are cached and the RowSet is disconnected. that is.JDBC 34 void setUsername(String name) Sets the username property for this RowSet object to the given String. boolean Indicates whether the designated column columnUpdated(int idx) in the current row of this CachedRowSet object has been updated. int[] getKeyColumns() Returns an array containing one or more column numbers indicating the columns that form a key that uniquely identifies a row in this CachedRowSet object. The following are important methods of CachedRowSet: Method Description void acceptChanges() Propagates row update. CachedRowSet Creates a RowSet object that is a deep createCopy() copy of the data in this CachedRowSet object. boolean Indicates whether the designated column columnUpdated(String in the current row of this CachedRowSet columnName) object has been updated. void rollback() Each CachedRowSet object's SyncProvider contains a Connection object from the original ResultSet or JDBC properties passed to it. ResultSet Returns a ResultSet object containing the getOriginalRow() original value for the current row only of this CachedRowSet object. void undoDelete() Cancels the deletion of the current row and notifies listeners that a row has changed. int getPageSize() Returns the page-size for the CachedRowSet object boolean Retrieves a boolean indicating whether getShowDeleted() rows marked for deletion appear in the set of current rows. int size() Returns the number of rows in this CachedRowSet object. Srikanth Technologies . Collection<?> Converts this CachedRowSet object to toCollection() a Collection object that contains all of this CachedRowSet object's data.JDBC 35 ResultSet getOriginal() Returns a ResultSet object containing the original value of this CachedRowSet object. void undoUpdate() Immediately reverses the last update operation if the row has been modified. void undoInsert() Immediately removes the current row from this CachedRowSet object if the row has been inserted. and also notifies listeners that a row has changed. updateInt(3. 8: crs.sql. 10: crs.setCommand("select * from jobs").setPassword("hr"). 7: crs.updateRow().getString(2) + ":" + crs. 2: import oracle.beforeFirst().next()) { 13: System.setUrl("jdbc:oracle:thin:@localhost:1521:XE").CachedRowSet.rowset. 17: 18: crs.OracleCachedRowSet.execute().rowset.getString(2) + ":" + crs.next()) { 23: System.out. 19: crs.absolute(1).println 14: (crs.acceptChanges().getInt(3) + 1000).jdbc. 9: crs. 12: while ( crs. 27: } 28: } Srikanth Technologies . 11: crs.println 24: (crs.getInt(3)).getInt(3)). 25: } 26: crs. 15: } 16: crs.JDBC 36 1: import javax.out. crs. 3: public class CachedRowSetDemo { 4: public static void main(String[] args) 5: throws Exception { 6: CachedRowSet crs = new OracleCachedRowSet(). 20: 21: crs.setUsername("hr"). 22: while ( crs. WebRowSet A WebRowSet is an extension to CachedRowSet.*. 18: } 19: } Srikanth Technologies . 17: rs.*.close(). 5: public class WebRowSetDemo { 6: public static void main(String[] args) 7: throws Exception{ 8: OracleWebRowSet rs = new OracleWebRowSet(). 9: rs.setUsername("hr"). The Oracle implementation of JDBCRowSet is OracleJDBCRowSet.io.Reader reader) 1: import java. 11: rs. 14: // write to XML 15: FileWriter fw = new FileWriter("c:\\jobs.*. public void writeXml(java.sql.*. The Oracle implementation of WebRowSet is OracleWebRowSet. 4: import java. 3: import oracle.setCommand("select * from jobs").rowset.io.io. 10: rs.setPassword("hr"). 16: rs.Writer writer) public void readXml(java.execute().sql. It represents a set of fetched rows or tabular data that can be passed between tiers and components in a way such that no active connections with the data source need to be maintained. 12: rs. 2: import javax.jdbc.writeXml(fw). 13: rs. It is a connected RowSet that provides JDBC interfaces in the form of a JavaBean interface.setUrl("jdbc:oracle:thin:@localhost:1521:XE").xml").JDBC 37 JDBCRowSet A JDBCRowSet is a RowSet that wraps around a ResultSet object. void setFilter(Predicate p) Applies the given Predicate object to this FilteredRowSet object. modifies.JDBC 38 FilteredRowSet A FilteredRowSet is an extension to WebRowSet that provides programmatic support for filtering its content. Null clears the current filter. and conversely. boolean Called by the FilteredRowSet object to evaluate(Object value. Predicate Interface  Allows applications to define the filter they wish to apply to filter rows. or updates only rows that are within the constraints of the filter. Oracle implementation of FilteredRowSet is OracleFilteredRowSet. boolean This method is typically called Srikanth Technologies . The following are methods related to FilteredRowSet: Method Description Predicate getFilter() Retrieves the active filter for this FilteredRowSet object. Method Description boolean This method is called by a FilteredRowSet evaluate(Object value. check whether the value lies between the String columnName) filtering criteria set using the setFilter(). it inserts.  A FilteredRowSet object enforces the filter constraints in a bi- directional manner: It outputs only rows that are within the constraints of the filter. object to check whether the value lies int column) between the filtering criterion set using the setFilter(). setFilter(new TitlePredicate()). 11: rs.println(rs. 15: 16: System.rowset.jdbc.out. 12: rs. 13: rs.setFilter(new MinSalaryPredicate()). 25: rs.next()) { 20: System.sql.sql.sql. 26: while (rs. int i) Srikanth Technologies . 3: import javax. 22: } 23: System.getString("job_title") 21: + ":" + rs.println("Jobs with Length(Title) >15"). 1: import java. 17: rs.JDBC 39 evaluate(RowSet rs) as FilteredRowSet object internal methods (not public) that control the RowSet object's cursor from row to the next.println("Jobs with MinSalary > 10000"). 24: rs.next()) { 27: System.out.setUsername("hr"). 14: rs.setCommand("select * from jobs").close(). 5: import oracle. 2: import javax.getString("job_title") 28: + ":" + rs. 10: rs.out.setUrl("jdbc:oracle:thin:@localhost:1521:XE").getString("min_salary")).getString("min_salary")).setPassword("hr").OracleFilteredRowSet.SQLException.println(rs.execute().rowset.Predicate.execute().RowSet.out. 29: } 30: rs.sql. 4: import javax. 18: 19: while (rs.FilteredRowSet. 6: public class FilteredRowSetDemo { 7: public static void main(String[] args) throws 8: Exception{ 9: FilteredRowSet rs = new OracleFilteredRowSet(). 31: } 32: } 33: class MinSalaryPredicate implements Predicate { 34: @Override 35: public boolean evaluate(Object o.rowset. 65: } 66: 67: @Override 68: public boolean evaluate(Object o.length() > 15) { Srikanth Technologies . 70: } 71: @Override 72: public boolean evaluate(RowSet rs) { 73: try { 74: String title = rs. 43: } 44: @Override 45: public boolean evaluate(RowSet rs) { 46: try { 47: Integer minsal = rs.JDBC 40 36: throws SQLException { 37: return true. int i) 63: throws SQLException { 64: return true. 38: } 39: @Override 40: public boolean evaluate(Object o. 56: } 57: } 58: } 59: 60: class TitlePredicate implements Predicate { 61: @Override 62: public boolean evaluate(Object o.getString(2). 52: } 53: 54: } catch (Exception ex) { 55: return false. 50: } else { 51: return false.getInt(3). 75: if (title. String string) 41: throws SQLException { 42: return true. 48: if (minsal > 10000) { 49: return true. String string) 69: throws SQLException { 69: return true. 16: crs2. 18: crs2.CachedRowSet. 83: } 84: } 85: } JoinRowSet There is no standard way to establish a SQL JOIN between disconnected RowSets without connecting to the data source.OracleJoinRowSet.rowset. 12: crs1.OracleCachedRowSet.execute().setCommand 20: ("select job_id.setUrl("jdbc:oracle:thin:@localhost:1521:xe"). 17: crs2. The Oracle implementation of JoinRowSet is the oracle.rowset.rowset. 14: crs1. 11: crs1. 3: import oracle. 10: crs1.setPassword("hr"). 13: from jobs").OracleJoinRowSet class.first_name. A JoinRowSet addresses this issue. 5: public class JoinRowSetDemo { 6: public static void main(String[] args) 7: throws Exception { 8: CachedRowSet crs1 = new OracleCachedRowSet().sql.rowset. 77: } else { 78: return false. 15: CachedRowSet crs2 = new OracleCachedRowSet().setPassword("hr").salary from employees"). Srikanth Technologies . 4: import oracle. 2: import javax. 9: crs1.JDBC 41 76: return true.setUsername("hr").sql.setUrl("jdbc:oracle:thin:@localhost:1521:xe").setUsername("hr").JoinRowSet.jdbc. 19: crs2.jdbc.jdbc. 1: import javax.job_title from jobs"). 79: } 80: 81: } catch (Exception ex) { 82: return false.rowset.setCommand("select job_id. 32: jrs. 4."job_id"). for job_id.first_name. 22: crs2. // join column 25: jrs. 1. 3. salary 29: while (jrs.JDBC 42 21: from employees").job_title. 23: JoinRowSet jrs = new OracleJoinRowSet(). // join column 26: 27: // get values using column number."job_id"). Create a table called PLAYERS as follows: 1: create table players 2: ( name varchar2(20) primary key.getString(2)). 3: photo blob 4: ). 28: 2.getInt(4) > 10000) // salary > 10000 31: System. jrs. The following java program takes player name and filename that contains the photo of the player and writes the name and photo into PLAYERS table. 24: jrs.execute().getString(3).printf("Employee [%s] is [%s]\n".next()) { 30: if ( jrs.addRowSet(crs1. Srikanth Technologies .out. 33: } // while 34: } 35:} Writing a picture into BLOB of Oracle The following example shows how to write into a BLOB column in Oracle.addRowSet(crs2. printStackTrace(). 15: String playername = s. 26: ps.out.File. is. 24: FileInputStream is = 25: new FileInputStream(picfile). 32: ps.setBinaryStream(2.setAutoCommit(false). 18: 19: con. 3: import java.print("Enter Photo filename :"). 36: } 37: } 38: } Srikanth Technologies . 31: con. 6: import java. playername).commit(). 17: String photofilename = s.sql.io. 14: System.executeUpdate().Connection.length()).PreparedStatement.sql. 23: File picfile = new File(photofilename). 29: (int) picfile. 4: import java. 27: 28: ps. 11: "hr".prepareStatement("insert into players 22: values(?. 7: public class AddPlayer { 8: public static void main(String args[]) { 9: try(Connection con = DriverManager.in).setString(1.?)"). 16: System.getConnection 10: ("jdbc:oracle:thin:@localhost:1521:xe".sql.io.nextLine().close().out. 20: PreparedStatement ps = 21: con.JDBC 43 1: import java.FileInputStream."hr")) { 12: // Take input from user 13: Scanner s = new Scanner(System.print("Enter player name :"). 5: import java.DriverManager. 30: ps. 2: import java.nextLine(). 33: } 34: catch (Exception ex) { 35: ex.Scanner.util. read()) != -1) System. while( (ch=is. Statement st = con. Srikanth Technologies . Clob clob = rs. ResultSet rs = st. It prints data taken from a CLOB column.getAsciiStream(). int ch.createStatement(). rs.print( (char) ch). //get lob from second column // get stream to read data from lob InputStream is = clob. Create table applicants ( id number(5). resume clob ).next().getClob(1).out.executeQuery ("select resume from applicants where id = 1").JDBC 44 Reading data from CLOB column The following code is used to read data from CLOB column. Web Applications .I . Tag Description <a> Defines an anchor <b> Defines bold text <body> Defines the body element <br> Inserts a single line break <div> Defines a section in a document <form> Defines a form <h1> to <h6> Defines header 1 to header 6 <head> Defines information about the document <hr> Defines a horizontal rule <html> Defines an html document <i> Defines italic text <img> Defines an image <input> Defines an input field <li> Defines a list item <link> Defines a resource reference <meta> Defines meta information <object> Defines an embedded object <ol> Defines an ordered list <option> Defines an option in a drop-down list <p> Defines a paragraph <param> Defines a parameter for an object <pre> Defines preformatted text <script> Defines a script Srikanth Technologies .Java EE (Web Applications – I) 1 HTML  HTML stands for (Hyper Text Markup Language)  HTML is a tag based language to present data  Endorsed by W3C (World Wide Web Consortium)  HTML5 is new HTML standard  HTML5 allows us to build rich and interactive websites that can play audio and video and support animations from within the browser without the need for plug-ins Important Tags of HTML The following are important tags in HTML. Java EE (Web Applications – I) 2 <select> Defines a selectable list <span> Defines a section in a document <strong> Defines strong text <style> Defines a style definition <table> Defines a table <td> Defines a table cell <textarea> Defines a text area <th> Defines a table header <title> Defines the document title <tr> Defines a table row <ul> Defines an unordered list 1: <!DOCTYPE html> 2: <html><head><title>My First HTML Page</title></head> 3: <body><h1>Java EE (Web)</h1> 4: This course teaches how to develop web applications 5: using Java EE. 6: <h2>Topics</h2> 7: <ul><li>JDBC, Servlets and JSP</li> 8: <li>Struts, JSF and Hibernate</li> 9: <li>AJAX, Web Services </li> 10: </ul> 11: <h2>Recommended Books</h2> 12: <table border="1"> 13: <tr><th>Title</th><th>Author</th><th>Price</th></tr> 14: <tr> 15: <td>JSF in Action</td><td>Kito Mann</td><td>500</td> 16: </tr> 17: <tr> 18: <td>Prof. Struts</td><td>Goodwill</td><td>450</td> 19: </tr></table> 20: </body></html> Srikanth Technologies Java EE (Web Applications – I) 3 CSS (Cascading Style Sheet)  Styles can be applied to elements in document and they define how to display HTML elements  Styles are normally stored in Style Sheets  External Style Sheets are stored in CSS files  Styles can be inline – they are applied to one element using style attribute  Style sheet may be internal – style sheet is defined within the document  Style sheet may be external – style sheet is linked with document using link element What style will be used when there is more than one style specified for an HTML element?  Browser default  External style sheet  Internal style sheet (inside the <head> tag)  Inline style (inside an HTML element) selector {property: value} h1,h2,h3,h4,h5,h6 {color: green } p.right {text-align: right} .center {text-align: center} <p class="right"> This paragraph will be right-aligned. </p> <h1 class=”center”> … </h1> <h2 class=”center”>… </h2> Srikanth Technologies Java EE (Web Applications – I) 4 cssdemo.html 1: <html> 2: <head> 3: <title>CSS Demo </title> 4: <link href="styles.css" rel="stylesheet" 5: type="text/css"/> 6: <style type="text/css"> 7: h2 {color:red; font:20pt arial} 8: .bright 9: {background-color:red;color:white;font:700 20pt arial} 10: .bottom {position:absolute;width:400px;height:100px; 11: left:100px;top:400px;background-color:gray} 12: .bigbutton 13:{position:relative;width:100px;height:50px;margin:10px} 14: </style> 15: </head> 16: <body> 17: <h1>CSS Demo</h1> 18: <h2>First heading2 using default settings</h2> 19: <h2 class="bright">Second Heading with class</h2> 20: <h3 style="color:Green; font:italic 14pt verdana"> 21: Inline styles applied to H3</h3> 22: <div class="bottom"> 23: <h4>Absolute Positioning</h4> 24: <input type="button" value="Button1" 25: class="bigbutton"/> 26: <input type="button" value="Button2" 27: class="bigbutton"/> 28: </div> 29: </body> 30: </html> styles.css body { font-size: 12pt; font-family: Verdana; background-color: wheat; } h1{font-weight:bold;color:#993333; font-family: Arial;} Srikanth Technologies Java EE (Web Applications – I) 5 HTML Forms Html forms are used to interact with end user. A form contains fields, which are submitted when user clicks on submit button. register.html 1: <html> 2: <head><title>Registration</title></head> 3: <body> 4: <form action="register.jsp" method="post"> 5: <h2>Registration</h2> 6: <table cellspacing="2pt"> 7: <tr> 8: <td>Email Address</td> 9: <td><input id="email" type="email" 10: size="30"/></td> 11: </tr> 12: <tr><td>Password </td> 13: <td><input id="pwd" type="password" /></td> 14: </tr> 15: <tr><td>Re-enter password</td> 16: <td><input id="pwd2" type="password" /></td> 17: </tr> 18: <tr><td>Occupation</td> 19: <td><select id="Select1" name="occup"> 20: <option selected="selected" 21: value="1">Student</option> 22: <option value="2">Employee</option> 23: <option value="3">House Wife</option> 24: <option value="4">Others</option> 25: </select></td> 26: </tr> 27: <tr><td>Gender</td> 28: <td><input type="radio" checked="true" 29: id="radio1" name="gender">Male</input> 30: <input type="radio" id="radio2" 31: name="gender">Female</input> 32: </td> 33: </tr> 34: <tr><td colspan="2"> 35: <input id="Checkbox1" type="checkbox"/> 36: Subscribe To Newsletter</td> 37: </tr> Srikanth Technologies Java EE (Web Applications – I) 6 38: </table> 39: <p/> 40: <input id="Button1" type="submit" value="Register"/> 41: </form> 42: </body> 43: </html> HTML 5 New Input Elements  HTML5 introduced new input types  Attribute TYPE of INPUT element is used to specify one of the following color, date, datetime, datetime-local, email, month, number, range, search, tel, time, url, week The following are new attributes related to INPUT elements. autocomplete, autofocus, form, formaction, formenctype, formmethod, formnovalidate, formtarget, multiple, pattern (regexp), placeholder, required, step Srikanth Technologies }" /> 11: <p /> 12: <input type="submit" value="Login" /> 13: <input type="submit" value="Cancel" 14: formaction="cancel" 15: formnovalidate="formnovalidate" /> 16: </form> Srikanth Technologies . Novalidate(Form).Java EE (Web Applications – I) 7 Attributes related to validation Required. Formnovalidate(Submit) 1: <form action="login" method="post"> 2: <h3>Login</h3> 3: Email: <br/> 4: <input type="email" required="required" 5: name="email" title="Email Address"/> 6: Password: <br/> 7: <input type="password" required name="password" 8: title="Password must contain at least 6 chars 9: consisting of letters and digits" 10: pattern="[0-9A-Za-z_]{6. Pattern. js. onMouseMove etc. Where to put JavaScript? JavaScript is placed using <script> tag as follows or script can be taken from a file.js"> </script> Srikanth Technologies . their value determines the type  Interpreted language – every time you run the script it is interpreted and executed by the browser  Derived from C language syntax and case sensitive language  It is not a subset of Java What can we do with JavaScript?  Validate data entered by user  Place dynamic content into HTML elements  Can make asynchronous request (AJAX) to server and place data into HTML elements  Can react to events such as onBlur.Java EE (Web Applications – I) 8 JavaScript  Created by Netscape to add interactivity to HTML pages  JavaScript was renamed from “livescript”  JavaScript was standardized by ECMA (European Computer Manufacturer Association) and also called as ECMAScript  JavaScript is a scripting language (lightweight programming language) used to execute code in client (browser)  It is loosely typed language – variables are not declared as of any type. <script ="text/javascript"> … </script> <script type="text/javascript" src="events. which typically contains extension .  A variable declared outside all functions can be accessed from any function. === !== /* === checks for same data types also */ x=5 y="5" x==y returns true x===y returns false Srikanth Technologies . Operators The following table lists operators in different categories in JavaScript.  Variable life time begins with declaration (or assignment) and ends when page is unloaded. Arithmetic Relational Logical Miscellaneous + == && + (Concatenation) .  A variable declared inside the function can be accessed only from that function. Amount = 1000. != || instanceof * > ! this / < typeof % >= new ++ <= -. name.Java EE (Web Applications – I) 9 Variable Declaration Though variables need not be declared. Name = “Srikanth”. it can be done using var keyword as follows: var amount. break case 2: code. break default: code. } for loop for (var=startvalue.var=var+increment) { code to be executed } for (variable in object){ code to be executed } while loop while (condition) { code to be executed } do while loop do{ code to be executed } while (condition) Srikanth Technologies .Java EE (Web Applications – I) 10 Conditional operator variablename=(condition)?value1:value2 if (condition) code to be executed if condition is true else code to be executed if condition is not true switch(n) { case 1: code.var<=endvalue. onabort Loading of an image is interrupted onblur An element loses focus onchange The user changes the content of a field onclick Mouse clicks an object ondblclick Mouse double-clicks an object onerror An error occurs when loading a document or an image onfocus An element gets focus onkeydown A keyboard key is pressed onkeypress A keyboard key is pressed or held down onkeyup A keyboard key is released onload A page or an image is finished loading onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element onmouseover The mouse is moved over an element onmouseup A mouse button is released onreset The reset button is clicked onresize A window or frame is resized onselect Text is selected onsubmit The submit button is clicked onunload The user exits the page Srikanth Technologies . Event The event occurs when.Java EE (Web Applications – I) 11 Events Events represent actions that JavaScript can react to... Event handlers are JavaScript functions that handle events. They are provided by global object. 7: txtname.value == "") { 6: alert("Please enter your name").html 1: <html><head> 2: <script type="text/javascript" 3: language="javascript"> 4: function check() { 5: if (txtname.  isNaN(expr)  parseFloat(string)  parseInt(string)  eval(expr) Srikanth Technologies . 14: } 15: </script> 16: </head> 17: <body> 18: Enter your name: 19: <input type=text size=20 onblur="check()" 20: id="txtname"/> 21: <input type="Button" onclick="fun()" 22: value="Click Here"/> 23: </body> 24: </html> Global Functions These functions are directly accessible from script. 8: } 9: } 10: function fun() { 11: var res = confirm("Do you want to continue?").focus().Java EE (Web Applications – I) 12 js1. 12: if ( res == true) 13: alert("Thank you"). "BMW") document. The elements are separated by a specified delimiter pop() Removes and returns the last element of an array push() Adds one or more elements to the end of an array and returns the new length reverse() Reverses the order of the elements in an array shift() Removes and returns the first element of an array slice() Returns selected elements from an existing array sort() Sorts the elements of an array toString() Converts an array to a string and returns the result Srikanth Technologies ."Volvo".write(mycars[0]) Method Description concat() Joins two or more arrays and returns the result join() Puts all the elements of an array into a string. var mycars=new Array() mycars[0]="Saab" mycars[1]="Volvo" mycars[2]="BMW" var mycars=new Array("Saab".Java EE (Web Applications – I) 13 Using JavaScript Objects The following are important objects of JavaScript. String Provides methods and properties related to string manipulation Date Provides methods related to date and time Array Provides methods related to array manipulations Math Provides properties and methods related to arithmetic Boolean Represents a Boolean Array object The Array object is used to store a set of values in a single variable name. 14: b[1] = "Yuvraj". 11: 12: var b = new Array(). 8: document.sort(). 13: b[0] = "Dhoni".push("Virat"). 16: document.write(a). 5: a[1] = "Suresh Raina" 6: a[2] = "Yuvraj Singh". 4: a[0] = "M.length). 17: </script> 18: </head> 19: <body></body> 20: </html> Srikanth Technologies . 7: a.Dhoni".write("<br>" + a[n] +":"+ a[n].S.write("<p>" + a. 9: for ( var n in a) 10: document.concat(b)). 15: b.Java EE (Web Applications – I) 14 1: <html><head> 2: <script type="text/javascript"> 3: var a = new Array(). Collection Description anchors[] Returns a reference to all Anchor objects in the document forms[] Returns a reference to all Form objects in the document images[] Returns a reference to all Image objects in the document links[] Returns a reference to all Area and Link objects in the document Property Description body Gives direct access to the <body> element cookie Sets or returns all cookies associated with document domain Returns the domain name for the current document lastModified Returns the date and time a document was last modified referrer Returns the URL of the document that loaded the current document title Returns the title of the current document URL Returns the URL of the current document Method Description getElementById() Returns a reference to the first object with the specified id getElementsByName() Returns a collection of objects with the specified name getElementsByTagName() Returns a collection of objects with the specified tagname write() Writes HTML expressions or JavaScript code to a document Srikanth Technologies .Java EE (Web Applications – I) 15 Document Object The Document object represents the entire HTML document and can be used to access all elements in a page.document property. The Document object is part of the Window object and is accessed through the window. Property Meaning closed True if window is closed length Returns the number of frames in the window name Name of the window opener Returns a reference to the window that created the window status Text of the status bar of the window self Refers to itself top Returns top most assessor window Method Meaning alert(msg) Displays the given message in a message box close() Closes window confirm(message) Displays a confirmation dialog box createPopup() Creates a popup window open() Opens a window print() Prints the content of the current window prompt() Prompts user to enter a value resizeTO() Resizes window to the given size setTimeout(code. Executes the given code after specified ms. Srikanth Technologies .Java EE (Web Applications – I) 16 writeln() Identical to the write() method. Window object The Window object is the top level object in the JavaScript hierarchy.lang) number of milliseconds clearTimeout() Clears timeout set earlier setInterval Will wait for specified number of milliseconds. frames[] collection represents frames in the window. ms) and then execute function. with the addition of writing a new line character after each expression. The Window object represents a browser window. and it will continue to execute the function. once at every given time-interval. (code. Java EE (Web Applications – I) 17 clearInterval() Clears interval set earlier Location Object The Location object is automatically created by the JavaScript runtime engine and contains information about the current URL. Srikanth Technologies . These URLs are the URLs the user has visited within a browser window. Property Description hash Sets or returns the URL from the hash sign (#) host Sets or returns the hostname and port number of the current URL hostname Sets or returns the hostname of the current URL href Sets or returns the entire URL pathname Sets or returns the path of the current URL port Sets or returns the port number of the current URL protocol Sets or returns the protocol of the current URL search Sets or returns the URL from the question mark (?) Method Description assign(url) Loads a new document reload() Reloads the current document replace(url) Replaces the current document with a new one History Object It consists of an array of URLs. Method Description back() Loads the previous URL in the history list forward() Loads the next URL in the history list go(URL | n) Loads a specific page in the history list Property length returns the number of elements in the history list. 7: var pwd2 = document. 8: 9: if ( pwd.value != pwd2. // everything is fine 16: } 17: </script> 18: </head> 19: <body style="background-color:#eeeeee"> 20: <form action="register. 14: } 15: return true.jsp" method="post" id="form1" 21: onsubmit="return validate()"> 22: <h2>Registration</h2> 23: <table cellspacing="2pt"> 24: <tr> 25: <td>Email Address</td> 26: <td><input id="email" type="email" 27: required=”required” size="30"/></td> 28: </tr> 29: 30: <tr> 31: <td>Password </td> 32: <td><input id="pwd" required=”required” 33: type="password" /></td> 34: </tr> 35: <tr><td>Re-enter password</td> Srikanth Technologies . 12: pwd2. 13: return false. 1: <html> 2: <head> 3: <title>Registration</title> 4: <script type="text/javascript"> 5: function validate() { 6: var pwd = document.getElementById("pwd2").html – registration form with validation using JavaScript The following program shows how to use JavaScript to validate data entered by the user into a HTML form.getElementById("pwd").Java EE (Web Applications – I) 18 Register.value){ 10: alert("Password and Re-entered password 11: do not match!").focus(). Java EE (Web Applications – I) 19 36: <td><input id="pwd2" type="password"/></td> 37: </tr> 38: </table> 39: <p/> 40: <input id="Button1" type="submit" value="Register" /> 41: </form> 42: </body> 43: </html> Srikanth Technologies . Java EE (Web Applications – I) 20 Web Applications  Web application is an application that runs in Web.  Client makes a request to server and server then processes the request and sends response back to client. Http Request Web Browser Web Server Http Response What is web server?  It is the software that takes request from Web client (Browser). Web is consisting of Web Server and Web Client. What is web client/browser?  Web client makes a request to web server using HTTP protocol.  Web client receives HTML sent from server and displays it to end- user.  Java EE (Java Enterprise Edition) provides specifications for Web Containers. and WebLogic Server. Client- side script is done using JavaScript. it is called as client-side scripting. Mozilla Firefox and Netscape Navigator are widely used Web Browsers.  When the script (code) is executed on the server. Apache Web Server. it is called as server-side scripting.  They are also called as Web Containers. It also provides the framework and runtime environment.  Browser is also responsible for running client-side scripting written in JavaScript.  Internet Explorer.  Some of the examples for Web Servers are Tomcat. Srikanth Technologies .  Server-side scripting is done using Java Servlets and JSP. processes the request and sends response to client. If script is executed on the client.  Internet applications are used by client from different parts of the world. it is called as Intranet application. Intranet Application  When a web application runs in Internet. Http Protocol  HTTP is an application protocol implemented on TCP/IP.  It is stateless protocol – client and server do not maintain information about each other. it is called as Internet application. whereas Intranet applications are used only by users of the intranet.  When a web application runs inside local area network (LAN). JavaServer Pages Standard Tag Library (JSTL) JavaServer Faces JavaServer Pages JavaServlet Srikanth Technologies .Java EE (Web Applications – I) 21 Internet vs.  It is a request and response protocol.  Client sends a request to receive information from server or invoke a process on the server. class files and packages lib .Java EE (Web Applications – I) 22 Java Servlets  Java Servlets and JSP technologies allow you to develop programs that are executed when a request is made from web client. Servlets are platform independent server-side programs that allow you to build web applications. Its methods are called by web server. They are invoked by client using a URL.  Just like an Applet a Servlet is a Java class that is executed by Web Server upon a request from client. The web container is responsible for initializing.  Servlets form server-side scripting.html and .  Servlets are totally managed by Web Server and run inside JVM of the Web Server. demo .xml Web Containers A web container is a Java Runtime providing an implementation of Java Servlet API and JSP.  Java Servlet is a Java class that is loaded into memory of web server.  Java Servlets are java programs that reside on Web Server and get executed on web server. invoking and managing the life cycle of Java Servlets and Java Server Pages. The following are different types of Web Containers: Srikanth Technologies .jsp files WEB-INF classes .jar files web. 01: package servlets.io. Web server such as IIS (Internet Information Server) from Microsoft requires this type of web container to run Servlets. 10: urlPatterns={"/datetime"}) 11: public class DateTimeServlet extends HttpServlet { 12: @Override 13: protected void doGet(HttpServletRequest request. Glassfish. This is the case with Apache TomCat etc.annotation. Creating a Servlet Creating a servlet is creating a class and annotating it with @WebServlet. 03: import java. 19: } 20: } Srikanth Technologies .Date.http. JBoss and WebSphere application server include web container built in. 14: HttpServletResponse response) 15: throws ServletException. Web container (JVM) is plugged into a web server that otherwise doesn’t support java. 07: import javax. Web container built into web server In this a web server contains web container. 04: import java. 05: import javax.getWriter().servlet. 08: 09: @WebServlet(name="DateTimeServlet". 17: PrintWriter pw = response.io.println( new Date().servlet.toString()). 02: import java.servlet.util. 18: pw. Web container in a separate runtime This is the case with non-Java EE world.PrintWriter. IOException { 16: response.*.WebServlet.setContentType("text/html").IOException. 06: import javax.Java EE (Web Applications – I) 23 Web Container in J2EE Application Server Commercial Java EE application server such as Weblogic Server.ServletException. datetime The URL Pattern related to servlet. Srikanth Technologies . localhostName of the system on which web server is running.Java EE (Web Applications – I) 24 Running a Servlet Select the servlet in the project window. click on the right button and select Run File from popup menu. This causes web application to be deployed first. webdemo The name of the application. 8888 The port number at which server is running. This can vary depending on your web server. If server is not yet started then NetBeans starts the server first and then deploys the web application. Then it invokes browser and starts the servlet by giving the required url .http://localhost:8888/webdemo/datetime Here is the description for components in the URL.  The default http request is GET request. the amount of data that can be passed is limited. data is passed along with body of HTTP request. The following is the structure of the HTTP request. Post request  An http request could be either of type GET or POST. Srikanth Technologies .  In case of POST request. Also confidential data cannot be passed as it becomes visible to others.Java EE (Web Applications – I) 25 Http Request Every request made by the browser to web server is called HTTP request as it uses HTTP protocol to make a request. data passed from HTML form is passed along with URL of the request.1 Headers Header: value sent by Header: value Browser Blank line separating headers from body Body Request Body Get request vs. http://localhost:8888/webdemo/list?price=500&qty=10  As data is passed along with URL.  In case of GET request. Http Request Requested URI Method GET URI HTTP/1.  The following URL contains data passed from client using GET request. headers and HTML to be displayed by browser. It typically contains status. Status Code Brief description HTTP/1. Http Response The response sent from server to client is called HTTP response.1 200 OK Headers Header: value sent to Header: value Browser by Blank line Server separating headers from body Body Response Body currency.Java EE (Web Applications – I) 26  You can specify which type of request you want using method attribute of <form> tag.html 01: <html> 02: <body> 03: <form action="currency"> 04: <h2>Currency Conversion </h2> 05: Enter amount in INR : 06: <input type="text" size="20" name="amount" /> <p/> 07: <input type="submit" value="Convert To USD" /> 08: </form> 09: </body> 10: </html> Srikanth Technologies . Srikanth Technologies .servlet.getParameter("amount").html first and NOT CurrencyServlet using /currency URL pattern. 10: urlPatterns = {"/currency"}) 11: public class CurrencyServlet extends HttpServlet { 12: public static double RATE = 66. 25: } 26: } 27: } Note: You must call currency. 07: import javax.println("<h3>Amount is required!</h3>").io.charset=UTF-8"). 06: import javax. 19: if (samount != null) { 20: double amount = Double. 18: String samount = request. 21: double usd = amount / RATE. 13: protected void doGet(HttpServletRequest request.IOException. 22: out.ServletException.Java EE (Web Applications – I) 27 CurrencyServlet.annotation. CurrencyServlet expects request parameters which are provided by currency. 14: HttpServletResponse response) 15: throws ServletException.*.servlet.WebServlet. 17: PrintWriter out = response.html page.parseDouble(samount).io.PrintWriter.http. 08: 09: @WebServlet(name = "CurrencyServlet".servlet.java 01: package servlets. 23: } else { 24: out.getWriter(). 04: import java. 05: import javax. 02: 03: import java.setContentType("text/html.println(" USD = " + usd). IOException { 16: response.  If an instance of the servlet does not exist. Put.  Response headers must always be set before the response has been committed. or Trace) of an HttpServlet object. Delete. in the doMethod methods (where method can take the value Get. Any attempt to set or add headers after the response has been committed will be ignored by the web container.  Invokes the service() method. When a request is mapped to a servlet. then fill in the response headers. the web container  Loads the servlet class.  For HTTP servlets. Writing Service Methods  The service provided by a servlet is implemented in the service method of a GenericServlet.Java EE (Web Applications – I) 28 Servlet Life Cycle The life cycle of a servlet is controlled by the container in which the servlet has been deployed.  Creates an instance of the servlet class. the container performs the following steps. Initializing a Servlet After the web container loads and instantiates the servlet class and before it delivers requests from clients.  Initializes the servlet instance by calling the init() method. it calls destroy() method. Post. A servlet that cannot complete its initialization process should throw UnavailableException. Options. the web container initializes the servlet. Srikanth Technologies . passing request and response objects. and finally write any body content to the output stream.  When container wants to remove servlet from memory. the correct procedure for populating the response is to first retrieve an output stream from the response. You can override the init method of the Servlet interface. Java EE (Web Applications – I) 29 Servlet Interface  Specifies the method to be implemented by the class (Servlet) that is to be run by Web Container. void destroy() This method is called before removing a servlet from web container. This is an abstract class.  Each Servlet must directly or indirectly implement this interface. GenericServlet Class It provides the basic implementation of Servlet interface. This ServletResponse res) method in turn may call other methods such as doPost and doGet in HttpServlet. Method Meaning void init It is invoked by web container after the (ServletConfig config) servlet is instantiated. All sub classes of this class must implement Service method. void service This is called whenever a request is (ServletRequest req. ServletConfig This returns the ServletConfig that was getServletConfig() passed to the servlet during init() method. It has the following additional methods in addition to Servlet interface that it implements. made by client for this servlet.  void init()  void log(String message) Srikanth Technologies . void setAttribute Sets the named attribute to the (String name.HttpServletResponse res) <<Interface>> GenericServlet Servlet HttpServlet SimpleHttpServlet ServletRequest Interface An object of this interface is passed when web container calls service() method. void removeAttribute Removes the named attribute from (String name) the list of attributes. Enumeration Returns the names of all attributes getAttributeNames() contained in the request. if attribute is not present. This class provides the following methods that you most likely override:  void doGet(HttpServletRequest req.Java EE (Web Applications – I) 30 HttpServlet class This class extends GenericServlet class and provides Http-specific implementation of the Servlet interface. Method Description Object getAttribute Returns value of the given attribute (String name) or null. The name is case sensitive. String getParameter Returns the value of the named (String name) parameter.Object value) given value. Srikanth Technologies . HttpServletResponse res)  void doPost(HttpServletRequest req. (String name) Enumeration Returns names of all the header fields of the getHeaderNames() request. Using request dispatcher you can forward request to the required path.Java EE (Web Applications – I) 31 String[] getParameterValues Returns an array of Strings (String name) containing all of the values the given request parameter has. HttpSession Returns the session associated with the getSession(boolean) request. String getRemoteAddr() Returns the address of the client making the request.GET. String getHeader Returns the value of the given header field. Srikanth Technologies . String getRemoteHost() Returns the name of the server from where client is making the request. String Returns the query string that is associated getQueryString() with the request. HttpSession Returns the session associated with the getSession() request. It creates a new session if one doesn't exist. HttpServletRequest Interface This interface extends ServletRequest and adds methods related to Http protocol. It creates a new session if one doesn't exist when the parameter is true. POST etc. String getMethod() Returns the type of HTTP request made . RequestDispatcher Returns an object of getRequestDispatcher RequestDispatcher for the given (String path) path. or null if the parameter does not exist. StringBuffer Reconstructs the URL the client used to make getRequestURL() the request. Method Description Cookie[] Returns all cookies passed from client along getCookies() with the request. PrintWriter getWriter() Returns writer. void reset() Clears any data that exists in the buffer as well as the status code and headers.String value) name and value. void setContentType Sets the content type of the response (String type) being sent to the client. it has methods to access HTTP headers and cookies. 06: value = request. boolean containsHeader Returns a boolean indicating whether Srikanth Technologies . 03: String name. void addHeader Adds a response header with the given (String name.hasMoreElements()) { 05: name = (String) e.getHeaderNames(). 04: while ( e. Method Description void flushBuffer() Forces any content in the buffer to be written to the client.println(name + " : " + value + "<br/>").nextElement(). HttpServletResponse Interface Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. 07: out. void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code. For example.value. Method Description void addCookie (Cookie) Adds the specified cookie to the response. which can be used to write to client. 08: } ServletResponse interface Provides means for servlet to send response to client.getHeader(name).Java EE (Web Applications – I) 32 01: // get the list of request headers along with values 02: Enumeration e = request. void sendRedirect Sends a redirect response to the client (String location) using the specified URL. void setStatus(int sc) Sets the status code for this response. void setHeader Sets a response header with the given (String name. The following table shows some of the common status codes and their meaning. To pass information between the original servlet and the next request. void sendError (int sc) Sends an error response to the client using the specified status code and clearing the buffer.Java EE (Web Applications – I) 33 (String name) the named header is already set. This means that there is always a round trip to the client side. Srikanth Technologies . you normally pass the information as a query string appended to the destination URL.String value) name and value. Code Description 200 Ok 301 Moved permanently 307 Temporary Redirect 401 Unauthorized 403 Forbidden 404 Resource not found 500 Internal Server Error Note: The sendRedirect() method works by sending a status code that tells the browser to request another URL. Each servlet belongs to an application and each application is associated with a servlet context. Enumeration Returns the names of all initialization getInitParameterNames() parameters.Java EE (Web Applications – I) 34 ServletConfig Interface It contains methods that provide information about Servlet configuration such as initialization parameters. ServletContext Returns ServletContext object associated getServletContext() with the web application. Srikanth Technologies . Method Meaning String getInitParameter Returns the value of the initialization (String name) parameter whose name is supplied.xml. This interface is implemented by GenericServlet. Initialization parameters are supplied through web. So methods of this interface can be called directly from servlet or you can obtain an object of ServletConfig using getServletConfig() method of Servlet interface. Java EE (Web Applications – I) 35 String getServletName () Returns the name assigned to a servlet in its deployment descriptor. If no name is specified then the servlet name is returned instead. Deployment descriptor - web.xml  It is an XML file that provides information about how to configure and deploy web application.  Can contain information about servlets, listeners , filters, context parameters and security.  When you create a web application using Java EE 6.0, web.xml is not provided by default. For web application in Java EE 5.0 or before, it is automatically provided.  At the time of creating a Servlet, we can provide init parameters and opt to put information about Servlet in web.xml as shown in the following picture. 01: <web-app …> 02: <servlet> 03: <servlet-name>InitParametersDemoServlet</servlet-name> 04: <servlet-class>servlets.InitParametersDemoServlet 05: </servlet-class> 06: <init-param> 07: <param-name>title</param-name> 08: <param-value>Srikanth Technologies</param-value> 09: </init-param> 10: </servlet> 11: <servlet-mapping> 12: <servlet-name>InitParametersDemoServlet</servlet-name> 13: <url-pattern>/initparamsdemo</url-pattern> 14: </servlet-mapping> 15: </web-app> InitParametersDemoServlet.java 01: package servlets; 02: import java.io.*; 03: import javax.servlet.*; 04: import javax.servlet.http.*; 05: public class InitParametersDemoServlet 06: extends HttpServlet { Srikanth Technologies Java EE (Web Applications – I) 36 07: String msg; 08: int counter=0; 09: @Override 10: protected void doGet(HttpServletRequest request, 11: HttpServletResponse response) 12: throws ServletException, IOException { 13: response.setContentType("text/html"); 14: PrintWriter out = response.getWriter(); 15: counter ++; 16: out.println("<h1>" + msg + ". </h1><h3>Displayed 17: for " + counter + " time(s)" + "</h3>"); 18: } 19: @Override 20: public void init(ServletConfig config){ 21: msg = config.getInitParameter("title"); 22: } 23: } It is possible to provide init parameters to a Servlet using @WebServlet annotation as follow: 01: @WebServlet( 02: name = "TestServlet", 03: urlPatterns = {"/test"}, 04: initParams = { 05: @WebInitParam(name = "param1", value = "value1"), 06: @WebInitParam(name = "param2", value = "value2")} 07: ) 08: public class TestServlet { 09: } Srikanth Technologies Java EE (Web Applications – I) 37 Cookies  A cookie is a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server.  A cookie's value can be used to uniquely identify a client, so cookies are commonly used for session management.  A cookie has a name, a single value, and optional attributes such as path, domain qualifiers, and maximum age.  Cookies may be stored in either Browser (Browser based cookies) or stored on disk (Durable cookies). Cookie(String name, String value) Method Description String getDomain() Returns the domain name set for this cookie. int getMaxAge() Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. String getName() Returns the name of the cookie. String getPath() Returns the path on the server to which the browser returns this cookie. String getValue() Returns the value of the cookie. void setDomain Specifies the domain within which this cookie (String path) should be presented. void setMaxAge Sets the maximum age of the cookie in (int expiry) seconds. void setPath Specifies a path for the cookie to which the (String uri) client should return the cookie. void setValue Assigns a new value to a cookie after the (String value) cookie is created. Srikanth Technologies Java EE (Web Applications – I) 38 addcookie.html 01: <!DOCTYPE html> 02: <html> 03: <body > 04: <h2>Cookies Demo</h2> 05: <form action="addcookie"> 06: Cookie Name <br/> 07: <input type="text" name="cname" size="20"><p/> 08: Cookie Value <br/> 09: <input type="text" name="cvalue" size="20"> 10: <p/> 11: <input type="checkbox" name="durable" value="y"> 12: Durable Cookie <p/> 13: <input type="submit" value="Add Cookie"><p/> 14: <a href="listcookies">List Cookies</a> 15: </form> 16: </body> 17: </html> AddCookieServlet.java 01: package servlets; 02: import java.io.*; 03: import javax.servlet.ServletException; 04: import javax.servlet.annotation.WebServlet; 05: import javax.servlet.http.*; 06: @WebServlet(name = "AddCookieServlet", 07: urlPatterns = {"/addcookie"}) 08: public class AddCookieServlet 09: extends HttpServlet { 10: protected void doGet(HttpServletRequest request, 11: HttpServletResponse response) 12: throws ServletException, IOException { 13: response.setContentType("text/html;charset=UTF-8"); 14: PrintWriter out = response.getWriter(); 15: String name = request.getParameter("cname"); 16: String value = request.getParameter("cvalue"); 17: String durable = request.getParameter("durable"); 18: Cookie c = new Cookie(name, value); 19: if (durable != null) 20: c.setMaxAge(7 * 24 * 60 * 60); 21: response.addCookie(c); 22: out.println("<h3>Cookie is created</h3>"); 23: out.close(); Srikanth Technologies Java EE (Web Applications – I) 39 24: } 25: } ListCookiesServlet.java 01: package servlets; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import javax.servlet.ServletException; 05: import javax.servlet.annotation.WebServlet; 06: import javax.servlet.http.*; 07: @WebServlet(name = "ListCookiesServlet", 08: urlPatterns = {"/listcookies"}) 09: public class ListCookiesServlet extends HttpServlet { 10: protected void doGet(HttpServletRequest request, 11: HttpServletResponse response) 12: throws ServletException, IOException { 13: response.setContentType("text/html"); 14: PrintWriter out = response.getWriter(); 15: String st = "<body><h3>List of Cookies</h3> 16: <table border='1' cellpadding='5'> 17: <tr><th>Name<th>Value</tr>"; 18: 19: for (Cookie c : request.getCookies()) { 20: st = st + "<tr><td>" + c.getName() + "<td>" 21: + c.getValue() + "</tr>"; 22: } 23: st = st + "</table></body>"; 24: out.println(st); 25: out.close(); 26: } 27: } Srikanth Technologies you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. Web-based applications are responsible for maintaining such state. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet.  Cookies  URL rewriting  Hidden form fields All of the above involve passing an identifier between the client and the server. otherwise.Java EE (Web Applications – I) 40 Session Tracking Many applications require that a series of requests from a client be associated with one another.println("<ahref=’" + response. Srikanth Technologies .getContextPath()+"/list") + "’>List</a>").encodeURL(request. If your application uses session objects. Sessions are represented by an HttpSession object. it returns the URL unchanged. You can use any of the following mechanisms to maintain a session. You access a session by calling the getSession() method of a request object. or the web component can include the identifier in every URL that is returned to the client. out. This method includes the session ID in the URL only if cookies are disabled. The identifier can be maintained on the client as a cookie. You can associate object-valued attributes with a session by name. because HTTP is stateless. called a session. 1970 GMT. void setAttribute Binds an object to this session. String getId() Returns a string containing the unique identifier assigned to this session. void Specifies the time. void invalidate() Invalidates this session then unbinds any objects bound to it. Method Description Object getAttribute Returns the object bound with the (String name) specified name in this session. or null if no object is bound with the given name. using the (String name. long getCreationTime() Returns the time when this session was created. Enumeration Returns Enumeration of String objects getAttributeNames() containing the names of all the objects bound to this session. void removeAttribute Removes the object bound with the (String name) specified name from this session.Java EE (Web Applications – I) 41 HttpSession Interface Provides methods to access session object and manipulate it.Object val) name specified. in seconds. between Srikanth Technologies . measured in milliseconds since midnight January 1. ServletContext Returns the ServletContext to which this getServletContext() session belongs. Java EE (Web Applications – I) 42 setMaxInactiveInterval client requests before the servlet (int interval) container will invalidate this session. 01: <!DOCTYPE html> 02: <html> 03: <body> 04: <h2>Session Variables Demo </h2> 05: <form action="sessionsdemo"> 06: Variable Name <br/> 07: <input type="text" size="20" name="key"> 08: <p/> 09: Variable Value <br/> 10: <input type="text" size="20" name="value"> 11: <p/> 12: <input type="submit" value="Add" name="act"> 13: <input type="submit" value="Remove" name="act"> 14: </form> 15: </body> 16: </html> SessionsDemoServlet.java 01: package servlets; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import java.util.Enumeration; 05: import javax.servlet.ServletException; 06: import javax.servlet.annotation.WebServlet; 07: import javax.servlet.http.HttpServlet; 08: import javax.servlet.http.HttpServletRequest; 09: import javax.servlet.http.HttpServletResponse; 10: import javax.servlet.http.HttpSession; 11: 12: @WebServlet(name = "SessionsDemoServlet", 13: urlPatterns = {"/sessionsdemo"}) 14: public class SessionsDemoServlet extends HttpServlet { 15: public void doGet(HttpServletRequest request, 16: HttpServletResponse response) 17: throws IOException, ServletException { 18: response.setContentType("text/html"); 19: PrintWriter out = response.getWriter(); 20: String act = request.getParameter("act"); 21: String key, value; Srikanth Technologies Java EE (Web Applications – I) 43 22: key = request.getParameter("key"); 23: HttpSession s = request.getSession(); 24: if (act.equals("Add")) { 25: value = request.getParameter("value"); 26: s.setAttribute(key, value); 27: } 28: else 29: s.removeAttribute(key); 30: // display session variables 31: out.println("<h3>Available Session Variables</h3>"); 32: Enumeration e = s.getAttributeNames(); 33: 34: while (e.hasMoreElements()) { 35: key = (String) e.nextElement(); 36: value = s.getAttribute(key).toString(); 37: out.println(key + " : " + value + "<br/>"); 38: } // end of while 39: } // end of doGet 40: } ServletContext Interface  A servlet context or application represents a single web application in web container.  ServletContext object is used to store application-level object in web application. Method Description Object Returns the servlet container attribute getAttribute(String name) with the given name, or null if there is no attribute by that name. Enumeration Returns an Enumeration containing the getAttributeNames() attribute names available within this servlet context. String getInitParameter Returns a String containing the value (String name) of the named context-wide initialization parameter, or null if the parameter does not exist. Srikanth Technologies Java EE (Web Applications – I) 44 Enumeration Returns the names of the context's getInitParameterNames() initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. int getMajorVersion() Returns the major version of the Java Servlet API that this servlet container supports. int getMinorVersion() Returns the minor version of the Servlet API that this servlet container supports. String Returns a String containing the real getRealPath(String path) path for a given virtual path. RequestDispatcher Returns a RequestDispatcher object getRequestDispatcher that acts as a wrapper for the resource (String path) located at the given path. void log(String msg) Writes the specified message to a servlet log file, usually an event log. void removeAttribute Removes the attribute with the given (String name) name from the servlet context. void setAttribute Binds an object to a given attribute (String key, Object object) name in this servlet context. // getServletContext() is provided by GenericServlet ServletContext ctx = this.getServletContext(); ctx.setAttribute("companyname","Srikanth Technologies"); Srikanth Technologies Java EE (Web Applications – I) 45 Request Dispatching It allows a servlet or JSP to dispatch a request to another servlet or a JSP. The following are possible scenarios:  A servlet processed the request but a JSP is to send output to client.  A servlet processed the request partially and remaining is to be done by another servlet. You obtain an object of RequestDispatcher in either of the ways:  Using getRequestDispatcher(String path) method or getNamedDispatcher(String) method of ServletContext. The path is relative to the root of the ServletContext.  Using getRequestDispatcher(String path) method of ServletRequest. Path is relative to the current request. The following methods of this interface are used to send control from one servlet/jsp to another. forward (ServletRequest, Sends control from current servlet/jsp ServletResponse) to the servlet/jsp to which RequestDispatcher points. include(ServletRequest, Calls the resource and includes the ServletResponse) content produced by the resource in the current response. FirstServlet.java 01: package servlets; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import javax.servlet.RequestDispatcher; 05: import javax.servlet.ServletException; 06: import javax.servlet.annotation.WebServlet; 07: import javax.servlet.http.HttpServlet; 08: import javax.servlet.http.HttpServletRequest; 09: import javax.servlet.http.HttpServletResponse; 10: 11:@WebServlet(name = "FirstServlet", urlPatterns = {"/first"}) Srikanth Technologies Java EE (Web Applications – I) 46 12: public class FirstServlet extends HttpServlet { 13: protected void doGet(HttpServletRequest request, 14: HttpServletResponse response) 15: throws ServletException, IOException { 16: response.setContentType("text/html"); 17: PrintWriter out = response.getWriter(); 18: out.println("First Servlet"); 19: request.setAttribute ("name", "Jason Hunter"); 20: RequestDispatcher rd = 21: request.getRequestDispatcher("/second"); 22: // rd.forward(request,response); 23: rd.include(request,response); 24: out.println("Again in First Servlet"); 25: out.close(); 26: } 27: } SecondServlet.java 01: package servlets; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import javax.servlet.ServletException; 05: import javax.servlet.annotation.WebServlet; 06: import javax.servlet.http.HttpServlet; 07: import javax.servlet.http.HttpServletRequest; 08: import javax.servlet.http.HttpServletResponse; 09: @WebServlet(name = "SecondServlet", 10: urlPatterns = {"/second"}) 11: public class SecondServlet extends HttpServlet { 12: protected void doGet(HttpServletRequest request, 13: HttpServletResponse response) 14: throws ServletException, IOException { 15: 16: PrintWriter out = response.getWriter(); 17: String name = (String) request.getAttribute ("name"); 18: out.println("<h1>" + name + "</h1>"); 19: } 20: } Srikanth Technologies the included servlet cannot set headers or call any method that affects the header of the response. Srikanth Technologies .  In case of include().  In case of forward(). the buffer must be cleared before the target servlet's service method is called. if output exists in the response buffer that has not been committed.Java EE (Web Applications – I) 47 Methods forward() and include()  The forward() method of the RequestDispatcher interface may be called only by the calling servlet if no output has been committed to the client. sendRedirect() The following are the differences between sendRedirect() and request dispatching. FirstServlet sends some response to Client 3.Java EE (Web Applications – I) 48 FirstServlet 1 Code 2 rd. Method sendRedirect()  Sends a request to client to redirect to the resource  URL changes in the browser  Request data is lost as a new request is made to target Methods forward() and include()  Redirect on the server  URL doesn’t change in browser  Request data is transferred from caller to called Srikanth Technologies . Control returns to FirstServlet 6. Response from FirstServlet goes to Client Request Dispatching vs.include(…) 6 Client Code 3 4 SecondServlet 5 1. Client Request for FirstServlet 2. SecondServlet response goes to client 5. FirstServlet calls SecondServlet 4. ServletContextListener Interface  public void contextInitialized (ServletContextEvent sce)  public void contextDestroyed (ServletContextEvent sce) ServletContextAttributeListener Interface  public void attributeAdded(ServletContextAttributeEvent evt)  public void attributeRemoved(ServletContextAttributeEvent evt)  public void attributeReplaced(ServletContextAttributeEvent evt) HttpSessionListener Interface  public void sessionCreated(HttpSessionEvent se)  public void sessionDestroyed(HttpSessionEvent se) HttpSessionAttributeListener Interface  public void attributeAdded(HttpSessionBindingEvent sbe)  public void attributeRemoved(HttpSessionBindingEvent sbe)  public void attributeReplaced(HttpSessionBindingEvent sbe) HttpSessionBindingEvent  public String getName()  public Object getValue() ServletRequestListener  public void requestInitialized(ServletRequestEvent sre)  public void requestDestroyed(ServletRequestEvent sre) RequestAttributeListener  public void attributeAdded(ServletRequestAttributeEvent srae)  public void attributeRemoved(ServletRequestAttributeEvent srae)  public void attributeReplaced(ServletRequestAttributeEvent srae) Srikanth Technologies .Java EE (Web Applications – I) 49 Listeners Allow you to monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when life-cycle events occur. which implements a listener interface. To use these listener objects you must define and specify the listener class. HttpSessionEvent.getSession().getAttribute("count"). 27: } 28: 29: @Override 30: public void sessionDestroyed(HttpSessionEvent se) { 31: ServletContext ctx = 32: se. 33: Integer count = (Integer) ctx.servlet. 03: import javax.servlet.servlet.setAttribute("count". 26: ctx.setAttribute("count". 05: import javax.ServletContextListener.servlet.ServletContext.servlet.getServletContext().annotation. 25: Integer count = (Integer) ctx. 04: import javax. 08: 09: @WebListener 10: public class SessionCountListener implements 11: ServletContextListener.getAttribute("count"). count + 1). 34: ctx.Java EE (Web Applications – I) 50 SessionsCountListener. 0).getSession().HttpSessionListener.java 01: package listeners. HttpSessionListener { 12: @Override 13: public void contextInitialized(ServletContextEvent sce) { 14: ServletContext ctx = sce. 02: import javax.WebListener.getServletContext(). // autoboxing 16: } 17: @Override 18: public void contextDestroyed(ServletContextEvent sce) { 19: } 20: 21: @Override 22: public void sessionCreated(HttpSessionEvent se) { 23: ServletContext ctx = 24: se.ServletContextEvent. 35: } 36: } Srikanth Technologies . 06: import javax.http. 07: import javax.getServletContext(). 15: ctx.http.servlet.1).setAttribute("count". count . servlet. IOException { 14: response.WebServlet.*. 04: import javax.ServletException.servlet.*. 12: HttpServletResponse response) 13: throws ServletException.setContentType("text/html.intValue()+"</h1>").http.servlet. 06: @WebServlet(name = "DisplaySessionsCountServlet". 03: import javax.println("<h1>Session Count:"+obj.getWriter(). 20: } 21: } Srikanth Technologies . 19: out.io.getAttribute("count").getSession(). 18: out.annotation.Java EE (Web Applications – I) 51 DisplaySessionsCountServlet. 05: import javax. 17: getServletContext().java 01: package servlets. 15: PrintWriter out = response. 07: urlPatterns = {"/sessionscount"}) 08: public class DisplaySesssionsCountServlet 09: extends HttpServlet { 10: @Override 11: protected void doGet(HttpServletRequest request. 16: Integer obj = (Integer) request. 02: import java.close().charset=UTF-8"). A filter gives you access to the HttpServletRequest and the HttpServletResponse objects before they are passed in to a servlet. You also can use a filter as an encryption and decryption device. Other uses include user authentication. HttpServletResponse res. and so on.FilterChain chain) public void destroy() FilterConfig Interface It is passed as parameter to init() method in Filter.  You can write a filter that records all incoming requests and logs the IP addresses of the computers from which the requests originate. The life cycle of a filter is represented by this interface's three methods: public void init(FilterConfig filterConfig) public void doFilter(HttpServletRequest reqest. Filter Interface It must be implemented by every filter. Srikanth Technologies . user input validation. data compression.Java EE (Web Applications – I) 52 Filters  Filter enables you to intercept a request before it reaches a resource. to invoke the next resource (Servlet).*. response).java 01: package filters.doFilter(request.annotation.servlet. 02: import java.WebFilter. 04: import javax. or. 21: } 22: } Srikanth Technologies . urlPatterns = {"/*"}) 07: public class LogFilter implements Filter { 08: @Override 09: public void init(FilterConfig config) throws 10: ServletException { 11: } 12: @Override 13: public void destroy() { 14: } 15: @Override 16: public void doFilter(ServletRequest request. 05: 06: @WebFilter(filterName = "LogFilter".IOException.io.out.Java EE (Web Applications – I) 53 public String getFilterName() public String getInitParameter(String parameterName) public Enumeration getInitParameterNames() public ServletContext getServletContext() FilterChain Interface Filters use the FilterChain object to invoke the next filter in the chain.getRemoteHost()).FilterChain chain) 18: throws IOException. ServletException { 19: System. 20: chain. HttpServletResponse res) LogFilter. if the filter is the last in the chain.println(request. 17: ServletResponse response. void doFilter (HttpServletRequest req. 03: import javax.servlet. 12: } 13: } The following code shows how to use a ServletContext Listener to dynamically add servlet to ServletContext at the time of context being initialized.*. The following methods of ServletContext are used to add servlet or filter dynamically. Class <? extends Servlet>servletClass) addFilter(String filterName. it is possible to add a servlet dynamically.http. 01: package servlets. 02: import java. IOException { 09: response. addServlet(String servletName.xml nor associated with annotation.println("<h1>Dynamic Servlet</h1>"). First create a class (servlet).io.setContentType("text/html").getWriter(). 03: import javax. 11: out.Java EE (Web Applications – I) 54 Dynamically adding Servlet  Starting from Servlets 3.servlet. which contains addMapping() method to associate mapping with servlet.0.*. 04: import javax. Class <? extends Filter> filterClass) The following code shows how to add a servlet dynamically.servlet. 10: PrintWriter out = response. Srikanth Technologies .ServletException. which is neither declared in web. 05: public class DynamicServlet extends HttpServlet { 06: protected void doGet(HttpServletRequest request.  Method addServlet() returns ServletRegistration object. 07: HttpServletResponse response) 08: throws ServletException.  Method addServlet() in ServletContext interface is used to add a servlet dynamically. servlet. 03: import javax.HttpSessionListener. 02: import javax.http.servlet.WebListener. 12: ServletRegistration sr = context. 11: ServletContext context = sce. 14: sr.Java EE (Web Applications – I) 55 AddServletListener.annotation. 15: } 16: public void contextDestroyed(ServletContextEvent sce){} 17: } Srikanth Technologies .getServletContext().java 01: import javax. 04: import javax.servlet.addServlet 13: ("DynamicServlet".HttpSessionEvent.DynamicServlet").addMapping(urlPatterns)."servlets.*. 05: @WebListener() 06: public class AddServletListener 07: implements ServletContextListener { 08: public void contextInitialized(ServletContextEvent sce) { 09: // add servlet dynamically 10: String[] urlPatterns = new String[]{"/dynamic"}.servlet.http. xml is not modular. web-fragment.xml file. there is no way but to edit the web.xml.Java EE (Web Applications – I) 56 Web Fragments  In previous versions of Java EE.xml.xml and it can be imagined that one or more web fragments constitute a single web. All the configuration details about one particular application are included in one single web. web.xml in the META-INF directory of the jar file.  Typically a framework is bundled in the form of a jar file and it is the responsibility of that framework to define the web fragment file with the name web-fragment. A web-fragment can include all the possible elements that are applicable for the web. Consider a sample web-fragment file.  Servlet 3.  A web fragment can be considered as one of the segments of the whole web.myServlet </servlet-class> 05: </servlet> 06: <listener> 07: <listener-class>myFramework. it is the responsibility of the Container to scan the information that is found in the /META-INF/web-fragment.xml file.xml 01: <web-fragment> 02: <servlet> 03: <servlet-name>myFrameworkSpecificServlet</servlet-name> 04: <servlet-class>myFramework. During the application startup.0 specification addresses this issue by introducing web fragments.xml file available in the application's classpath.myListener</listener-class> 08: </listener> 09: </web-fragment> Srikanth Technologies . When one or more frameworks are used. the HttpServletRequest can make available the various parts of the multipart request via the following methods. upload. if a request is of type multipart/form- data and if the servlet handling the request is annotated using the @MultipartConfig.Java EE (Web Applications – I) 57 Uploading Files Starting from Servlets 3.html 01: <html><head><title>Upload File</title></head> 02: <body> 03: <form action="upload" method="post" 04: enctype="multipart/form-data"> 05: <table> 06: <tr><td>Select File : </td> 07: <td><input name="file" type="file"/> </td> 08: </tr> 09: <tr><td>Enter Filename : </td> 10: <td><input type="text" name="filename" size="20"/></td> 11: </tr> 12: </table><p/> 13: <input type="submit" value="Upload File"/> 14: </form> 15: </body> 16: </html> Srikanth Technologies .0. public Iterable<Part> getParts() public Part getPart(String name) Each part provides access to the headers. content type related with it and also the content via the getInputStream()method. getRealPath(filename). 07: import javax.servlet. 23: 24: // save file in server 25: String outputfile= 26: getServletContext().getPart("file"). 38: } 39: } 40: } Srikanth Technologies . 08: @WebServlet(name="UploadServlet".getInputStream()).java 01: package servlets. 12: HttpServletResponse response) 13: throws ServletException.read(). 19: 20: Part p2 = request. 05: import javax.servlet. 36: } finally { 37: out.servlet.servlet.close(). 16: try { 17: Part p1 = request. 03: import java. urlPatterns={"/upload"}) 09: @MultipartConfig 10: public class UploadServlet extends HttpServlet { 11: protected void doPost(HttpServletRequest request.Java EE (Web Applications – I) 58 UploadServlet. 22: String filename = s.println("<h3>File uploaded successfully!</h3>").getWriter().nextLine(). 27: FileOutputStream os=new FileOutputStream (outputfile). 15: PrintWriter out = response.getPart("filename"). 28: 29: int ch = is.charset=UTF-8").http.getInputStream().write(ch).annotation. 21: Scanner s = new Scanner(p2.WebServlet.*.ServletException. 04: import javax.*. 18: InputStream is = p1.setContentType("text/html. IOException { 14: response.annotation.read(). 02: import java.MultipartConfig. 32: ch = is.io. 30: while (ch != -1) { 31: os. 33: } 34: os.util. 06: import javax.Scanner. 35: out.close().  A JSP page is a text document that contains two types of text: Static data. 08: %> 09: </h2> 10: </body> 11: </html> Srikanth Technologies .Date().println(cd.Java EE (Web Applications – I) 59 JavaServer Pages (JSP)  JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components.util.Date cd = new java.toString()). which construct dynamic content. WML. and XML) and JSP elements.util.  JSP specifications extend the Java Servlet API. which can be expressed in any text-based format (such as HTML. 07: out.  Provides expression language for accessing server-side objects. 01: <html> 02: <body> 03: <h2> 04: Current Date and Time: 05: <% 06: java. it calls the jspDestroy method. Srikanth Technologies . jsp[include|forward] Elements are converted into invocations of the Java Servlet API. Scripting elements Are inserted into the JSP page’s servlet class. the web container translates the JSP page into a servlet class and compiles the class. Expression language Expressions are passed to JSP expression evaluator. Thus. the life cycle of JSP pages is determined by Java Servlet technology.  The container invokes the _jspService method.Java EE (Web Applications – I) 60 Life Cycle of a JSP Page  A JSP page services requests as a servlet. jsp[set|get]Property Elements are converted into method calls to JavaBeans components. the JSP page’s servlet follows the servlet life cycle:  If an instance of the JSP page’s servlet does not exist.  When a request is mapped to a JSP page. the web container first checks whether the JSP page’s servlet is older than the JSP page. the container loads the JSP page’s servlet class. Custom tags Are converted into calls to the tag handler that implements the custom tag.  If the container needs to remove the JSP page’s servlet. After the page has been translated and compiled. instantiates an instance of the servlet class then initializes the servlet instance by calling the jspInit method. JSP elements are treated as follows: Directives Are used to control how the web container translates and executes the JSP page. If the servlet is older. passing request and response objects. HttpJspPage jspInit() jspDestroy() _jspService(. which is called by the JSP container to generate the content of the JSP page. HttpServletResponse response) throws ServletException. void _jspService(HttpServletRequest request.Java EE (Web Applications – I) 61 JspPage interface  Every JSP Servlet class must implement JspPage interface  Extends Servlet interface  Contains two methods void jspInit() .) HttpJspBase currentdate_jsp jspInit() _jspService(…) Srikanth Technologies .same as init() void jspDestroy() .same as destroy() HttpJspPage Interface Contains one method jspService().. IOException It is up to the web container to implement HttpJspPage interface. Object Description pageContext The context for the JSP page. response The response returned by the JSP page.  Directives start with @character within the tag. include and taglib.  Declarations are initialized when the JSP page is initialized and have Class Scope.  Declaration block is enclosed between <%! and %> 01: <%! 02: // the following content is placed in class at class level 03: private int i. config Allows access to ServletConfig for JSP page. Provides access to various objects including implicit objects. session The session object for the client.  There are three directives – page. servletContext The context for the JSP page’s servlet and any web components contained in the same application. 04: public void m1() 05: { } 06: %> Srikanth Technologies . out Writes the given data to output stream of client. Declarations  Declaration is a block of Java code that is used to define class- wide variables and methods in the generated class file.Java EE (Web Applications – I) 62 Implicit Objects The following implicit objects can be used in JSPs. request The request triggering the execution of the JSP page. Directive  Specifies what JSP container must do. 03: %> Expressions  An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client.println("Hello JSP World"). <%-.getParameter("age")%>’ 03: name=’age’> Comments in JSP Comments in JSP are given using <%-. wish.Java EE (Web Applications – I) 63 Scriptlets  Scriptlet is the block of Java code that is executed when JSP is executed.and --%>.  It is enclosed in <%= and %> 01: <%=new Date()%> 02: <input type=text value=’<%=request.comment --%> HTML form invoking JSP The following example shows how to invoke JSP from HTML Form and send data.html 01: <html><body> 02: <form action="wish. 01: <% 02: out.jsp"> 03: <h2>Wish Form</h2> 04: Enter your name <input type="text" name="uname" 05: size="20"> 06: <input type="submit" value="Submit"> 07: </form> 08: </body></html> Srikanth Technologies . It is enclosed in <% and %>  Scriptlets are placed in jspService() method. jsp 01: <html> 02: <body bgcolor="tan"> 03: <% 04: String name = request.equals("")) // empty string was passed 09: out.getParameter("uname").println("No name passed").println("Empty Name").Java EE (Web Applications – I) 64 wish. 07: else 08: if (name. 05: if (name == null ) // no parameter passed 06: out.println(name). 12: %> 13: </body> 14: </html> Srikanth Technologies . 10: else 11: out. 14: if ( n % 2 == 0 ) 15: out.println("<h3>Odd Number </h3>"). It is taken from EL (expression language). When user submits form.getParameter("num"). Srikanth Technologies .parseInt(num). 18: } 19: %> 20: </body> 21: </html> Note: Expression ${param. 12: if ( num != null && num.length() > 0 ){ 13: int n = Integer. It is important to differentiate the first call from other calls (post back – JSP calling itself).jsp 01: <html> 02: <body> 03: <form action="even.Java EE (Web Applications – I) 65 Using HTML form and process in a single JSP The following JSP demonstrates how to create an HTML form and script to process the input given by the form in the same JSP. even. it displays form. it calls the same JSP again. 16: else 17: out.jsp"> 04: Enter a number : 05: <input type="text" name="num" size="10" 06: value="${param.num}"> 07: <p> 08: <input type="submit" value="Submit"> 09: </form> 10: <% 11: String num = request.println("<h3>Even Number </h3>").num} refers to request parameter num. When JSP is called first. setUrl("jdbc:oracle:thin:@localhost:1521:XE").rowset.close().  The rest of the process is same as what we have seen in JDBC module listdept. 11: rs.Java EE (Web Applications – I) 66 Accessing Database from Web Applications Accessing database from a JSP/Servlet needs the following steps:  Make sure .setPassword("hr").execute(). 24: %> 25: </table> 26: </center> 27: </body> 28: </html> Srikanth Technologies . 10: rs.jar) is placed in /WEB-INF/lib directory  Import package java. 08: rs.sql and (if required) javax.getString(2) %></td></tr> 21: <% 22: } // end of while 23: rs.getString(1) %> </td> 20: <td> <%= rs.rowset. 09: rs.sql.setUsername("hr"). 12: rs.jdbc.sql etc.CachedRowSet rs = 07: new oracle.setCommand("select * from departments").jar file of JDBC driver (like ojdbc6.jsp 01: <html> 02: <body> 03: <center> 04: <h2>List of Departments </h2> 05: <% 06: javax.OracleCachedRowSet().next()){ 18: %> 19: <tr><td> <%= rs. 13: %> 14: <table border=1 cellpadding=5> 15: <tr><th>Id</th><th>Name </th></tr> 16: <% 17: while ( rs. .. the bean must have a method of the form setProperty(type pc) { .Java EE (Web Applications – I) 67 JavaBeans A Bean is a Java class that follows the conventions given below:  Must have a zero-argument (empty) constructor  Should have no public instance variables (fields)  Persistent values should be accessed through methods called getXxx() and setXxx()  Must be placed in a package A JavaBeans component property can be:  Read/write. or indexed. read-only. the bean must have a method of form type getProperty() { . or write-only  Simple.. } For each writable property.. It must simply be accessible using public methods that conform to the following conventions: For each readable property. which means it contains a single value. } Srikanth Technologies . which means it represents an array of values  A property does not have to be implemented by an instance variable. Once a bean is included in JSP. application Objects are available in any session that is in the same application as the session that created the bean. request Objects are available as long as the request is being processed. <jsp:useBean id="name" scope="scope" class="fullyqualifiedclassname"/> <jsp:useBean id="count" scope="page" class="test.Java EE (Web Applications – I) 68 Using JavaBeans with JSP In order to use a JavaBean in JSP.Count class and assigns id count. scope and id for Java Bean. you have to use <jsp:useBean> standard action as follows: <jsp:useBean> This standard action is used to create or access an instance of Java Bean. They are released when request is over or another page is invoked. The scope of the bean can be any of the following: Scope Meaning page Objects are available throughout the page. Its life time is the execution of the page. throughout the page the bean can be accessed using id of the bean. This package starts with classes directory (/WEB-INF/classes). It specifies class. Srikanth Technologies .Count" /> The above example creates an object of test. Remember the class Count is to be placed in package test. session Objects are available in the session in which they are created. <jsp:setProperty name=“emp” property=“*” /> <jsp:setProperty name=“emp” property=“bs” param=“sal” /> <jsp:setProperty name=“emp” property=“bs” value=“12000” /> Srikanth Technologies . property Name of the property to be changed. value Value to assign to the bean property.Java EE (Web Applications – I) 69 Session Object An object of UserBean with id user login. If the property is set to * then the tag iterates over all the parameters of the request. <jsp:setProperty name="beanname" property="propertyname|*" value="value" | param="parametername" /> Attribute Meaning Name Name of the bean defined by <jsp:useBean> tag. This cannot be given if param is already given.jsp <jsp:useBean id=“user” <jsp:useBean id=“user” scope=“session” scope=“session” class=“demo.jsp home.UserBean” /> <jsp:setProperty > It is used to set property of the bean to the given value or the specified parameter of the form. matching parameter names and value types to bean properties. param Specifies the name of the request parameter whose value is to be assigned to a bean property.UserBean” /> class=“demo. and setting each matched property to the value of the matching parameter. setString(1. "hr".prepareStatement 10: ("insert into jobs values(?. 13: ps.null)")) { 11: ps. <jsp:getProperty name="beanname" property="propertyname" /> Name is the name of the bean specified by <jsp:useBean> tag and property is the name of the property whose value is to be retrieved. 14: } 15: } 16: public String getId() { 17: return id.sql. 05: public void addJob() throws Exception { 06: Class.getConnection 08: ("jdbc:oracle:thin:@localhost:1521:XE".setString(2. <jsp:getProperty name="emp" property="sal" /> JobBean.driver. "hr").title = title.null. 03: public class JobBean { 04: private String id.*. getId()). 18: } 19: public void setId(String id) { 20: this. 09: PreparedStatement ps = con. 27: } 28: } Srikanth Technologies .java 01: package beans. 21: } 22: public String getTitle() { 23: return title.forName("oracle.id = id. 07: try (Connection con = DriverManager.executeUpdate(). 12: ps. 02: import java. 24: } 25: public void setTitle(String title) { 26: this.OracleDriver"). getTitle()).?.jdbc.Java EE (Web Applications – I) 70 <jsp:getProperty> It is used to retrieve the value of the parameter. title. and it cannot set headers or Cookies.html 01: <html> 02: <head> 03: <title>Add Job</title> 04: </head> 05: <body> 06: <form action="addjob.JobBean" 04: scope="page" id="job" /> 05: <jsp:setProperty name="job" property="*"/> 06: <% 07: try { 08: job.println("Added Successfully!").  The included page has access only to JspWriter object.jsp"> 07: <h2>Add Job</h2> 08: Job Id : <input type="text" name="id" size="10" /> 09: Job Title : <input type="text" name="title" size="20"/> 10: <input type="submit" value="Add Job" /> 11: </form> 12: </body> 13: </html> addjob.getMessage()). 09: out.addJob(). Srikanth Technologies .println(ex.  If page output is buffered then the buffer is flushed prior to the inclusion. 13: } 14: %> 15: </body> 16: </html> <jsp:include>  This action allows a static or dynamic resource to be included in the current JSP at request time.jsp 01: <html> 02: <body> 03: <jsp:useBean class="beans.Java EE (Web Applications – I) 71 addjob. 10: } 11: catch(Exception ex) { 12: out. The buffer is cleared. <jsp:include page=“second. the old values are kept intact.  The included page can access both the original and the new parameters. and the request is modified to augment additionally specified parameter using <jsp:param>.html”/> <jsp:forward> Allows the request to be forwarded to another JSP. Srikanth Technologies . <jsp:forward page=“url”> <jsp:param name=“name” value=“value” /> </jsp:forward> The resource to which the request is being forwarded must be in the same context as the JSP dispatching the request.  If parameter names are same. a servlet. or a static resource. Execution in the current JSP stops when it encounters a <jsp:forward> tag.Java EE (Web Applications – I) 72 <jsp:include page=“urlspec”> <jsp:param name=“name” value=“value” /> </jsp:include>  May take one or more <jsp:param> tags in its body. but the new values take precedence over existing values. p1} <p/> 03: P2 = ${param. <%@ include file=“filename” %> caller.setAttribute("color". 06: %> 07: <jsp:include page="called.jsp"> 08: <jsp:param name="p3" value="30"/> 09: </jsp:include> 10: 11: <h2>Back in Caller </h2> Srikanth Technologies .p2} <p/> 04: <% 05: request."Red").jsp?p1=10&p2=20 01: <h1>Caller Page </h1> 02: P1 = ${param.Java EE (Web Applications – I) 73 @Include directive It is used to include the content of the specified file at translation time. the changes are not incorporated in to JSP. So even if the contents of the file included after calling JSP are compiled. p3} 07: <p/> 08: Color = ${requestScope.Java EE (Web Applications – I) 74 called.jsp 01: <h1>Called Page </h1> 02: P1 = ${param.p2} 05: <p/> 06: P3 = ${param.color} Output for include() Caller Page P1 = 10 P2 = 20 Called Page P1 = 10 P2 = 20 P3 = 30 Color = Red Back in Caller Output for forward() Called Page P1 = 10 P2 = 20 P3 = 30 Color = Red Srikanth Technologies .p1} 03: <p/> 04: P2 = ${param. initParam Maps a context initialization parameter name to a single value.Java EE (Web Applications – I) 75 Expression Language . missing values result in empty strings. and not exceptions Srikanth Technologies . Expression language supports the following capabilities:  Concise access to attributes in objects like session. headerValues Maps a request header name to an array of values. paramValues Maps a request parameter name to an array of values. header Maps a request header name to a single value. sessionScope Maps session-scoped variable names to their values.0  Provides shorthand language for accessing values that are stored in standard locations such as session. request. pageScope Maps page-scoped variable names to their values. relational. application  Shorthand notation for bean properties  Simple access to collection elements  Provides arithmetic. param Maps a request parameter name to a single value. cookie Maps a cookie name to a single cookie. logical operators to manipulate objects within EL  Automatic type conversion  In most cases.EL  Expression language is supported from JSP 2. cookies etc. applicationScope Maps application-scoped variable names to their values. requestScope Maps request-scoped variable names to their values. Object Meaning page This is a synonym to this object in JSP page. name} 08: <p> 09: ${header["User-Agent"]} 10: <p> 11: ${cookie. >=.setAttribute("name". !=.Java EE (Web Applications – I) 76 Operators in EL The following are different types of operators available in EL. ||.User" scope="page"/> 02: <% 03: request. < .n2?"First is big":"Second is big"} Srikanth Technologies .n2} 14: <p> 15: ${param. Arithmetic +.name} 07: ${param.n1 + param. <= Logical &&.n1 == param.n2} 16: <p> 17: ${param.value} 12: 13: ${param. * . -.n1 > param. ! Empty Empty Conditional condition ? expression1 : expression2 expression 01: <jsp:useBean id="user" class="beans."Srikanth"). 04: %> 05: ${name} 06: ${user. / . % Relational ==.JSESSIONID. >. 07: out.parseInt(request.jsp"%> 04: <% 05: int n. Translation time errors Errors that occur during translation (conversion) of JSP to Servlet are called as translation errors. 06: n = Integer. They result in Internal Servlet Error (error code 500). Srikanth Technologies . These errors can be handled using exception handling of Java language or handled using error directive and error page. you have to take two steps:  Specify error page that will handle errors in JSP using page directive and errorPage attribute of page directive as follows: testerror. Runtime Errors Errors that occur when translated servlet is running are called as runtime errors.println(n).jsp 01: <html> 02: <body> 03: <%@page errorPage="error. This page must use isErrorPage attribute of page directive. 08: %> 09: </body> 10: </html>  Create JSP that will handle errors.Java EE (Web Applications – I) 77 Error Handling in JSP The following are different types of errors that might occur in a JSP page.getParameter("num")). To handle runtime errors using error page. session Specifies if the page participates in an HTTP session.*" session="false" %> Srikanth Technologies . errorPage Specifies the name of the JSP to be invoked when an error occurs.  Is automatically invoked whenever an exception occurs in the page that referred to it. contentType Specifies the MIME type for the response of the page. isErrorPage Indicates if the current JSP page is to handle errors.  Contains access to exception object.back()">Back </a> 06: </body> 07: </html> Error Page  Is used to provide a more user-friendly message to user. The following are the attributes of page directive.Java EE (Web Applications – I) 78 error. through which the attributes of most recent exception can be obtained. <%@ page import="java.java.*. Use comma to separate multiple packages. buffer Specifies whether output is buffered or not and the size of the buffer.  Defined using <%@ page isErrorPage=“true” %> Page directive Page directive defines attributes that affect the process of the whole page. Attribute Meaning import Imports the packages specified.getMessage()%> <p/> 05: <a href="javascript:history.jsp 01: <%@page isErrorPage="true" %> 02: <html> 03: <body> 04: Error : <%= exception.util.io.  Maintainability .A tag library is simply a collection of one or more custom tags. The web container then invokes those operations when the JSP page’s servlet is executed. the tag is converted to operations on a tag handler.  Communicate with each other. also known as JSP tag extensions (because they extend the set of built-in JSP tags).  Custom tags.  Pass variables back to the calling page.  Readability . changes or fixes to that functionality are made only to the custom tag. Why we need custom tags?  Reusability . and then every JSP page that uses the tag automatically gets the fix.  Be nested within one another. on several pages in an application.If you can encapsulate some bits of functionality in a custom tag.  Access all the objects available to JSP pages.Java EE (Web Applications – I) 79 JSP Tag Extensions – Custom Tags  Tag extensions are user-defined tags (custom tags) in JSP. Srikanth Technologies . provide a way of encapsulating reusable functionality on JSP pages.  When a JSP page containing a custom tag is translated into a Servlet. Custom tags can:  Be customized via attributes passed from the calling page.Custom tags improve readability by encapsulating Java code away from the page. A tag library can be reused on a single page. or across different applications. such as its name and a list of any attributes that it takes. When the tag is finally used on the page. SimpleTag interface The SimpleTag interface defines the basic contract between simple tags and the JSP page on which they are used. IOException. are then defined in a tag library descriptor (TLD) file. Srikanth Technologies . We have to extend SimpleTagSupport class and override doTag() method. an instance of the tag handler class is created and its methods are called to execute the reusable functionality. } SimpleTagSupport Class The SimpleTagSupport class implements SimpleTag interface and provides default implementations for all methods. public void setParent(JspTag parent). public interface SimpleTag extends JspTag { public void doTag() throws JspException.Java EE (Web Applications – I) 80 Create a tag handler – Simple Tags The following are the steps to be taken to create a tag:  Create a class that implements SimpleTag interface or extend SimpleTagSupport class  Override doTag() method to provide functionality related to tag  Place required entries in . This must process the tags and react to callback methods invoked by JSP engine. public void setJspContext(JspContext jspContext). public JspTag getParent().tld file regarding tag  Refer to the tag library in JSP using taglib directive and use tag Creating Tag Handler A tag needs a tag handler. public void setJspBody(JspFragment jspBody). The characteristics of the tag. 08: try { 09: out. 13: } 14: } 15: } Tag Library Descriptor TLD is a file with extension . tlib-version The tag library’s version.java 01: package st. It is required to map the tag handler to tag.getOut().getMessage()). 05: public class CurrentTime extends SimpleTagSupport { 06: public void doTag() throws JspException { 07: JspWriter out=getJspContext(). The following are important elements of root elements <taglib> Element Description description (optional) A string describing the use of the tag library. 02: import java.servlet. Tag library is typically given extension .tld. The following are important elements of <tag> element.IOException ex) { 12: throw new JspException(ex.tagext. display-name(optional) Name intended to be displayed by tools.Date. 03: import javax.*.jsp. 10: } 11: catch (java.tld file.jsp.*.Java EE (Web Applications – I) 81 CurrentTime. uri A URI that uniquely identifies the tag library.io. It is an XML file with standard elements. 04: import javax. short-name (optional) Name that could be used by a JSP page- authoring tool to create names with a mnemonic value.tld and placed in /WEB-INF or one of its sub folders.toString()). Srikanth Technologies . Each tag contains a <tag> element in .println( new Date().util.servlet. 0" encoding="UTF-8"?> 02: <taglib version="2.Java EE (Web Applications – I) 82 Element Meaning name Name of the tag. empty and scriptless. tagdependent Specifies that the body of the tag is handled by tag handler in the way it needs.sun.w3.xsd"> 08: <tlib-version>1. empty Specifies tag is having empty body. st. scriptless It is same as JSP body content except that it cannot contain any Java code wrapped up as scriptlets.sun.srikanthtechnologies. description(optional) Description of the element.tld 01: <?xml version="1.com/xml/ns/javaee 06: http://java. The valid values are – tagdependent. tag-class Name of the class that is the tag handler for this tag.com/xml/ns/javaee" 04: xmlns:xsi="http://www.CurrentTime</tag-class> 14: <body-content>empty</body-content> 15: </tag> 16: </taglib> Srikanth Technologies . No content is allowed between start and end tags.com/xml/ns/javaee/web-jsptaglibrary 07: _2_1. attribute Declares an attribute of the custom tag. body-content Specifies how the content of the tag is to be processed.sun.org/2001/XMLSchema-instance" 05: xsi:schemaLocation="http://java.1" 03: xmlns="http://java. Body Content Body content may be any of the following.0</tlib-version> 09: <short-name>st</short-name> 10: <uri>http://www.com/tags</uri> 11: <tag> 12: <name>currenttime</name> 13: <tag-class>st. com/tags" 02: prefix="st"%> 03: <html> 04: <body> 05: <h1> <st:currenttime /> </h1> 06: </body> 07: </html> Creating an Attribute for Tag A tag can contain attributes. <%@taglib uri="uri | .tld file or the location of .tld file.Java EE (Web Applications – I) 83 Using Tag Extensions in JSP Page Custom tags are to be explicitly imported into JSP page that wishes to use them.  prefix can be any name.  tagname must be name of one of the tags defined in . It is used to prefix tags in the library.tld file" prefix="tagprefix" %> <tagprefix:tagname>body</tagprefix:tagname>  uri is either uri given in . Attributes could be either optional or required.tld file.jsp 01: <%@taglib uri="http://www. Srikanth Technologies .  An attribute element in tag element of . Each attribute of the tag must have the following:  Tag handler must have a variable and a setter method for every attribute that it supports. usetime.srikanthtechnologies.tld file. Directive taglib is used to specify the uri of the tag library and the prefix to be used to refer to tags in tag prefix. The default is false. name The unique name of the attribute being declared. Srikanth Technologies . The default is false. Element Meaning description(optional) A description of the attribute.Java EE (Web Applications – I) 84 The following are the sub elements of attribute element. required (optional) Whether the attribute is required. rtexprvalue(optional) Whether the attribute’s value can be processed at runtime by an EL expression. Java EE (Web Applications – I) 85 Srikanth Technologies . util. 02: import java. 10: try { 11: SimpleDateFormat sd = new SimpleDateFormat(format).FormattedDate</tag-class> 04: <body-content>empty</body-content> 05: <attribute> 06: <name>format</name> 07: <rtexprvalue>true</rtexprvalue> 08: <type>java. 16: } 17: } 18: public void setFormat(String value) { 19: this.servlet.tagext.SimpleTagSupport.format = value.format(new Date())).lang. 08: public void doTag() throws JspException { 09: JspWriter out=getJspContext(). 05: import javax.SimpleDateFormat. 04: import javax.servlet. 13: } 14: catch (java.jsp.Java EE (Web Applications – I) 86 FormattedDate.java 01: package st.Date.io.jsp. 03: import java. 20: } 21: } st.IOException ex) { 15: throw new JspException(ex.String</type> 09: </attribute> 10: </tag> Srikanth Technologies .*. 12: out.println(sd.getOut().tld 01: <tag> 02: <name>FormattedDate</name> 03: <tag-class>st. 06: public class FormattedDate extends SimpleTagSupport { 07: private String format.getMessage()).text. Java EE (Web Applications – I) 87 index.java 01: package st. 22: crs. 06: import javax. 21: crs.DriverManager. 03: import java.servlet.jsp 01: <%@taglib uri="/WEB-INF/tlds/st. 15: PageContext ctx = (PageContext) getJspContext().tagext.setUsername("hr").jsp.sql.*. 23: crs.SimpleTagSupport. 09: 10: public class JobTagHandler extends SimpleTagSupport { 11: 12: @Override 13: public void doTag() throws JspException.Connection. which represents the tag’s body content.sql.setPassword("hr").tld" prefix="st" %> 02: <html> 03: <body> 04: <h1><st:FormattedDate format="dd-MMM-yy hh:mm:ss"/></h1> 05: </body> 06: </html> Evaluating Body Content  The JspFragment object. JobTagHandler.Statement. 02: import java. 17: try { 18: OracleCachedRowSet crs = new OracleCachedRowSet().execute(). 19: crs.JspFragment.servlet.servlet. IOException { 14: JspWriter out = getJspContext().jsp.tagext. 07: import javax. 04: import java. 05: import java. 08: import javax. 16: JspFragment body = getJspBody().sql. 24: Srikanth Technologies .  The JspFragment has one method that is of interest here: invoke().setCommand("select * from jobs").jsp.sql. is passed to the tag via the setJspBody() method.ResultSet. Calling this method effectively asks the JSP container to evaluate and process the body content and send it back to the page.getOut().setUrl("jdbc:oracle:thin:@localhost:1521:xe"). 20: crs. println(ex. crs.getMessage()). ${title}</li> 08: </st:jobs> 09: </ul> 10: <h2>Jobs</h2> 11: <table border="1"> 12: <tr><th>Job Id </th> <th>Job Title</th></tr> 13: <st:jobs> 14: <tr> 15: <td>${id} </td> 16: <td>${title} </td> 17: </tr> 18: </st:jobs> 19: </table> 20: </body> 21: </html> Srikanth Technologies . 31: } 32: catch (Exception ex) { 33: System.close(). 27: ctx.out. 28: body.next()) { 26: ctx.jsp 01: <%@taglib uri="/WEB-INF/tlds/st.tld 01: <tag> 02: <name>jobs</name> 03: <tag-class>st. // process body 29: } 30: crs.setAttribute("id".crs.getString("job_title")).tld" prefix="st"%> 02: <html> 03: <body> 04: <h2>List Of Jobs </h2> 05: <ul> 06: <st:jobs> 07: <li>${id}.Java EE (Web Applications – I) 88 25: while (crs.JobTagHandler</tag-class> 04: <body-content>scriptless</body-content> 05: </tag> usejobs.invoke(out).setAttribute("title". 34: } 35: } 36: } st.getString("job_id")).  JSTL allows you to employ a single.com/jsp/jstl/sql Functions http://java.com/jsp/jstl/xml Internationalization http://java. The URIs for the libraries are as follows: Core http://java.2</version> </dependency> Using JSTL JSTL is exposed as multiple tag libraries. standard set of tags to perform common tasks.com/jsp/jstl/core XML http://java.com/jsp/jstl/fmt SQL http://java.jar file from http://repo1.sun.sun.  JSTL has tags for iterators and conditional operations. internationalization.2 If you are using maven.sun.com/jsp/jstl/functions Srikanth Technologies . for manipulating XML documents. Note: Download JSTL .Java EE (Web Applications – I) 89 JSTL  JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications.org/maven2/jstl/jstl/1.sun. accessing databases using SQL.sun. where each tag library contains a set of tags related to one topic. use the following dependency: <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.maven. var. flow control. Tag Attributes out value. begin. Area Related Tags Variable support Remove. var. begin. var. if URL management Import (param). redirect (param). value choose otherwise when test catch var Srikanth Technologies . url (param) Miscellaneous catch. scope url value. out The following table shows commonly used attributes of core tags. otherwise) forEach. scope if test. scope remove var. end. escapeXml. step forTokens var. context param name. items. and accessing URL based resources.Java EE (Web Applications – I) 90 Core Tags Core tags include tags related to variable manipulation. value. default set var. forTokens. end. scope forEach var. set Flow control choose (when. items. scope redirect url. delims. step import url. "/> 05: <c:set var="bookId" value="${param..bookid}"/> 06: 07: <c:remove var="cart" scope="session"/> 08: 09: <c:if test="${!empty param.number}"> 10: <c:forEach var="value" begin="1" 11: end="${param..com/jsp/jstl/core" 02: prefix="c"%> 03: 04: <c:set var="foo" scope="session" value=".sun.number}"> 12: ${value} <br/> 13: </c:forEach> 14: </c:if> 15: 16: <c:out value="<h1>For Heading</h1>" escapeXml="true" /> 17: 18: <c:redirect url="second.Java EE (Web Applications – I) 91 core.jsp"> 19: <c:param name="name" value="Srikanth" /> 20: </c:redirect> Srikanth Technologies .jsp 01: <%@taglib uri="http://java. Java EE (Web Applications – I) 92 cfor.anders.micheal:hunter" delims=":."> 25: <li> ${name} </li> 26: </c:forTokens> 27: </ul> 28: <table border="1"><tr><th>Name</th><th>Value</th></tr> 29: <c:forEach var="hname" 30: items="<%=request.com/jsp/jstl/core"%> 04: <!DOCTYPE html> 05: <html> 06: <body> 07: <c:forEach var="i" begin="1" end="10" > 08: <c:if test='${i % 2 == 0}'> 09: ${i} <br/> 10: </c:if> 11: </c:forEach> 12: <p/> 13: <c:forEach var="i" begin="10" end="20" step="2" > 14: ${i} <br/> 15: </c:forEach> 16: <ul> 17: <c:forEach var="name" 18: items="james.jsp 01: <%@page contentType="text/html" pageEncoding="UTF-8"%> 02: <%@taglib prefix="c" 03: uri="http://java.roberts.sun.getHeaderNames()%>"> 31: <tr><td>${hname} </td> 32: <td>${header[hname]} </td></tr> 33: </c:forEach> 34: </table> 35: </body> 36: </html> Srikanth Technologies .hunter"> 19: <li> ${name} </li> 20: </c:forEach> 21: </ul> 22: <ul> 23: <c:forTokens var="name" 24: items="james:roberts.micheal. maxRows.Java EE (Web Applications – I) 93 SQL tags These tags allow you to access database to execute queries and manipulate database. Tag Attributes setDataSource dataSource. param)  update (dateParam.driver.user. These methods are part of Result interface.var. The following are the tags in SQL tag library.scope query dataSource.password.scope transaction dataSource param Value dateParam Value The data retrieved by query tag can be accessed by the following methods.url.var.dataSource. param) The following table lists important attributes for each SQL Tag.sql. Method Description String[] Provides names of columns getColumnNames() int getRowCount() Returns number of rows Map[] getRows() Returns an array of maps that can be supplied to the items attribute of <c:forEach> Object[][] Returns the result of the query as an getRowsByIndex() array of arrays Srikanth Technologies .  setDataSource  transaction  query (dateParam.var.startRow.scope update sql. salary 13: from employees 14: </sql:query> 15: <ul> 16: <c:forEach var="row" items="${emplist.jsp?empno=100&sal=5000 01: <%@taglib prefix="c" 02: uri="http://java.sun.sun.com/jsp/jstl/sql"%> 05: 06: <sql:setDataSource var="oracle" 07: driver="oracle.sal}"/> 15: <sql:param value="${param.first_name}.rows}"> 17: <li>${row.driver.${row.com/jsp/jstl/core" %> 03: <%@ taglib prefix="sql" 04: uri="http://java.jdbc.OracleDriver" 08: url="jdbc:oracle:thin:@localhost:1521:XE" 09: user="hr" password="hr" /> 10: 11: <sql:query var="emplist" dataSource="${oracle}"> 12: select employee_id.first_name.com/jsp/jstl/core" %> 03: <%@taglib prefix="sql" 04: uri="http://java.salary} 18: </c:forEach> 19: </ul> Srikanth Technologies .jdbc.empno}"/> 16: </sql:update> 17: 18: <c:if test="${uc > 0 }"> 19: Updated Sucessfully! 20: </c:if> emplist.Java EE (Web Applications – I) 94 updatesal.sun.employee_id}.sun.driver.jsp 01: <%@ taglib prefix="c" 02: uri="http://java.OracleDriver" 08: url="jdbc:oracle:thin:@localhost:1521:XE" 09: user="hr" password="hr" /> 10: 11: <sql:update dataSource="${oracle}" var="uc"> 12: update employees set salary = ? 13: where employee_id = ? 14: <sql:param value="${param.com/jsp/jstl/sql" %> 05: 06: <sql:setDataSource var="oracle" 07: driver="oracle. ${row. 17: %> 18: <sql:setDataSource 19: var="oracle" driver="oracle.OracleDriver" 20: url="jdbc:oracle:thin:@localhost:1521:XE" 21: user="hr" password="hr" /> 22: 23: <sql:query var="results" dataSource="${oracle}"> 24: ${param.query} 25: </sql:query> 26: 27: <table border="1" cellpadding="3" width="100%s"> 28: <tr> 29: <c:forEach var="cn" items="${results.sun.jdbc.driver.sun.getParameter("query"). 15: if (query == null || query.com/jsp/jstl/core"%> 03: <%@taglib prefix="sql" 04: uri="http://java.rowsByIndex}"> 34: <tr> 35: <c:forEach var="colvalue" items="${row}"> 36: <td>${colvalue}</td> 37: </c:forEach> 38: </tr> 39: </c:forEach> 40: </table> 41: </body> 42: </html> Srikanth Technologies .length() == 0) 16: return.com/jsp/jstl/sql"%> 05: <html> 06: <body> 07: <form action="sqlplus.jsp 01: <%@taglib prefix="c" 02: uri="http://java.columnNames}"> 30: <th>${cn}</th> 31: </c:forEach> 32: </tr> 33: <c:forEach var="row" items="${results.query} 11: </textarea><br/> 12: <input type="submit" value="Execute"> 13: </form> 14: <% String query = request.jsp" method="post"> 08: Enter Query : <br/> 09: <textarea cols="80" rows="3" 10: name="query">${param.Java EE (Web Applications – I) 95 sqlplus. parse. value Srikanth Technologies . select. xslt. scope. var. xml. XML flow control actions.  out. var. escapeXml set select. scope when select forEach var. var. if  transform (param) Tag Attributes parse doc. scope. scope if select.Java EE (Web Applications – I) 96 XML Tags The XML actions are divided into three categories: XML core actions. otherwise)  forEach. out select. end. result param name. step transform doc. and XML transform actions. var. The XML set of actions in JSTL is therefore based on XPath. begin. set  choose (when. sun.com/jsp/jstl/core" 02: prefix="c"%> 03: <%@taglib uri="http://java.xml 01: <?xml version="1.sun.xml" var="doc" /> 08: <x:parse doc="${doc}" var="catalog" /> 09: <x:forEach var="product" 10: select="$catalog/catalog/product"> 11: <x:out select="$product/name"/> : 12: <x:out select="$product/price"/> <br/> 13: </x:forEach> 14: </body> 15: </html> Srikanth Technologies .com/jsp/jstl/xml" 04: prefix="x"%> 05: <html> 06: <body> 07: <c:import url="catalog.jsp 01: <%@taglib uri="http://java.0" encoding="UTF-8"?> 02: <catalog> 03: <product> 04: <name>IBM Server</name> 05: <price>150000</price> 06: </product> 07: <product> 08: <name>Dell Server</name> 09: <price>165000</price> 10: </product> 11: </catalog> xmlread.Java EE (Web Applications – I) 97 catalog. the Internet Message Access Protocol (IMAP).net/projects/javamail/pages/Home  A mail agent to access Mail server .mail.  Oracle provides providers for Simple Mail Transfer Protocol (SMTP). Email Sender Email Recipient SMTP Server POP3 Server Messages Mail Server What you need to use JavaMail? The following are required to use JavaMail to either send a mail or receive a mail.  JavaMail API allows mails to be sent and received using Java.  JavaMail providers implement the API and provide support for most common protocols. and Post Office Protocol 3 (POP3). Download it from https://java.jar. POP3.  javax. which includes SMTP.  JavaMail is dependent on the JavaBeans Activation Framework.  It supports the development of Mail Agents (programs used to send and receive mails) such as Outlook Express.mail package provides the required interfaces and classes. IMAP providers – javax.Java EE (Web Applications – I) 98 Java Mail  JavaMail specifications provide a collection of abstract classes that define the common objects and their interfaces for any general mailing system.Outlook Express Srikanth Technologies .  Mail server with SMTP and POP3/IMAP servers  Java Mail API. internet packages.  Start a mail session with the Session.host property to point to the local mail server. It provides abstract interface to message transfer protocol such as SMTP. It provides attributes to specify sender.getInstance( ) method. message's subject and the content of the message. message etc.  Create a new Message object.send() method.  Set the message's from and to addresses.  Send the message with the Transport. These classes are provided through javax.mail and javax. recipient. Store Supports storing and retrieving the messages.Java EE (Web Applications – I) 99 Java Program Java Mail API SMTP Provider SMTP Server Steps to send mail using Java Mail API :  Set the mail. Class Description Message Provides the basic encapsulation of message objects. Session Used to implement Mail Session. These classes are abstract classes and implemented by a specific provider. Java Mail API The following are important classes in Java Mail API. Srikanth Technologies . Folder Used to represent a folder for storing mails. probably by instantiating one of its concrete subclasses.mail. Transport Is used to exchange messages with message transfer agents. Srikanth Technologies . String getProperty(String name) Returns the value of the specified property. Store getStore(String protocol) Get a Store object that implements the specified protocol. It collects together properties and defaults used by the mail API's. void setDebug(boolean debug) Set the debug setting for this Session. getInstance(Properties props. Method Meaning static Session getDefaultInstance Get the default Session object. (Properties props. Provider[] getProviders() Returns an array of all the implementations installed via the JavaMail.  A single default session can be shared by multiple applications on the desktop. Authenticator authenticator) Properties getProperties() Returns the Properties object associated with this Session. Transport Get a Transport object that getTransport(String protocol) implements the specified protocol.  The Session class represents a mail session. Provider getProvider Returns the default Provider for (String protocol) the protocol specified.Java EE (Web Applications – I) 100 Session Class  It acts as a factory for the installed Transport and Store implementation. Store getStore() Get a Store object that implements this user's desired Store protocol. Authenticator authenticator) static Session Get a new Session object. host The host specific to a particular protocol. Subclasses should override the default implementation. Method Description Folder getDefaultFolder() Returns a Folder object for 'root'. mail.IMAPStore and POP3Store. PasswordAuthentication getPasswordAuthentication() Called when password authentication is needed. mail. Subclasses provide actual implementations .transport.Java EE (Web Applications – I) 101 Session Properties The following are Java Mail related properties. Srikanth Technologies . It is simply a repository for a user name and a password.protocol The default Transport protocol.host The default host for both Store and Transport protocols. mail.store. for storing and retrieving messages. PasswordAuthentication class This class is a data holder that is used by Authenticator. Property Description mail. Authenticator Class The class Authenticator represents an object that knows how to obtain authentication for a network connection.user The default user name for both Store and Transport.protocol.  String getPassword()  String getUserName() Store Class Store class models a message store and its access protocol.protocol The default Store protocol. Folder getFolder(name) Returns the folder object corresponding to the given name. which returns null. mail. Java EE (Web Applications – I) 102 Folder Class Folder class represents a folder for mail messages. an appropriate subclass of Message (e.  Message implements the Part interface. SEEN and DRAFT. void open(int mode) Mode can be READ_ONLY or READ_WRITE.  To send a message.g. void addRecipient ( Adds this recipient address to the Message. Message Class  This class models an email message. int getMode() Returns open mode of the folder. and the message is sent using the Transport. Message contains a set of attributes and "content".send method..RecipientType type. MimeMessage) is instantiated. Subclasses provide actual implementations. DELETED. This is an abstract class. Address address) Srikanth Technologies . Method Description Message[] getMessages() Gets all message objects.  A message may be set to any of the valid states such as ANSWERED. Messages within a folder also have a set of flags that describe its state within the folder. the attributes and content are filled in. Messages that have been received are retrieved from a folder named "INBOX".  Message objects are obtained either from a Folder or by constructing a new Message object of the appropriate subclass. Method Meaning void Adds these addresses to the addFrom(Address[] addlist) existing "From" attribute. int Returns total number of unread getUnreadMessageCount() messages. Subclasses such as IMAPFolder and POP3Folder implement protocol specific Folders. existing ones of the given type. boolean isOpen() Indicates whether folder is open. the existing ones of the given type.html 01: <html> 02: <head> 03: <title>Send Mail</title> 04: </head> 05: <body> 06: <h2>Send Mail </h2> 07: <form action="sendmail" method="post"> 08: To Address <br/> 09: <input type="text" name="toaddress" /> 10: <p/> Srikanth Technologies . void setSubject(String subject) Sets the subject of this message. void setSentDate(Date date) Sets the sent date of this message. Address[] addresses) void setReplyTo(Address[] Sets the addresses to which replies addlist) should be directed. Address[] getFrom() Returns the "From" addresses. (RecipientType type. Date getSentDate() Gets the date this message was sent. Flags getFlags() Returns a Flags object containing the flags for this message. Sendmail. void setFlags Sets the specified flags on this (Flags flag.Java EE (Web Applications – I) 103 void addRecipients Adds these recipient addresses to (RecipientType type. Address[] addresses) Address[] getAllRecipients() Gets all recipient addresses of message. Address[] getReplyTo() Gets the addresses to which replies should be directed. String getSubject() Gets the subject of this message. Folder getFolder() Gets the folder from which this message was obtained. void setRecipients Sets the recipient addresses. Date getReceivedDate() Gets the date this message was received.boolean set) message to the specified value. activation. 08: import javax. 13: urlPatterns = {"/sendmail"}) 14: public class SendMailServlet extends HttpServlet { 15: protected void doPost(HttpServletRequest request.getProperties(). 09: import javax.getParameter("subject").getWriter(). 02: import java.util.DataHandler.io. 24: String body = request.setContentType("text/html"). 16: HttpServletResponse response) 17: throws ServletException.servlet.getDefaultInstance(props. Srikanth Technologies . 19: PrintWriter out = response. 05: import javax. 06: import javax. 20: 21: String to = request. 04: import java.java 01: package servlets.getParameter("fromaddress").mail. 11: 12: @WebServlet(name = "SendMailServlet". 22: String from = request. IOException { 18: response. null).getParameter("toaddress").util.ServletException.PrintWriter.annotation.io.getParameter("body").http. 07: import java.Java EE (Web Applications – I) 104 11: From Address <br/> 12: <input type="text" name="fromaddress" /> 13: <p/> 14: Subject <br/> 15: <input type="text" name="subject" /> 16: <p/> 17: Body <br/> 18: <textarea name="body" rows="5" cols="80"> 19: </textarea> 20: <p/> 21: <input type="submit" value="Send Mail" /> 22: </form> 23: </body> 24: </html> SendMailServlet. 10: import javax. 26: Session session = Session. 03: import java.*.*.Date.servlet. 23: String subject = request. 25: Properties props = System.WebServlet.Properties.IOException.servlet. 06: import javax. 02: 03: import java.*. 13: 14: @WebServlet(name = "SendMailServlet".WebServlet.println("Error --> " + ex.setRecipient(Message. 31: msg.println("\nMail was sent successfully.annotation."). 12: import javax.setDataHandler( 34: new DataHandler(body. 22: 23: String to = "james@st. "text/html")).io. 35: msg. 33: msg.ServletException.DataHandler. 09: import javax. 11: import javax. 42: } 43: } 44: } SendMailAttachmentServlet.setFrom(new InternetAddress(from)).servlet.Properties. 30: msg. Srikanth Technologies . 04: import java.*.java 01: package servlets.setSubject(subject).activation. 08: import javax. 10: import javax. 07: import javax. 15: urlPatterns = {"/sendfile"}) 16: public class SendMailAttachmentServlet extends HttpServlet{ 17: protected void doGet(HttpServletRequest request. 39: } 40: catch(Exception ex){ 41: out.TO.com".setContentType("text/html").setSentDate(new Date()).send(msg).PrintWriter. // send message 38: out.getMessage()). 36: msg.servlet.activation. 05: import java.*.getWriter().RecipientType.servlet.io.http. 21: PrintWriter out = response.mail. IOException { 20: response. 18: HttpServletResponse response) 19: throws ServletException. 32: new InternetAddress(to)).Java EE (Web Applications – I) 105 27: try { 28: // construct the message 29: Message msg = new MimeMessage(session).util.IOException. 37: Transport.mail.FileDataSource. ..addBodyPart(mbp1).".null). 27: String filename = "ship. 25: String subject = "Ship".</h4>").getDefaultInstance(props.getRealPath(filename)). 28: 29: Properties props = System.println( 55: "<h4>Mail has been sent with attachment. 50: mp.. 30: Session session=Session.TO. 31: try { 32: MimeMessage msg = new MimeMessage(session).setFileName(fds. 45: // attach the file to the message 46: mbp2.setText(body). 48: // create the Multipart and its parts to it 49: Multipart mp = new MimeMultipart(). 39: mbp1. 36: msg. 37: // create and fill the first message part 38: MimeBodyPart mbp1 = new MimeBodyPart().com".jpg".getProperties(). 42: FileDataSource fds = 43: new FileDataSource( 44: getServletContext().addBodyPart(mbp2).getName()).printStackTrace(out). 35: new InternetAddress(to)).setFrom(new InternetAddress(from)).setContent(mp). 26: String body = "Here is a ship. 54: out.RecipientType.setRecipient(Message. 56: } catch (Exception ex) { 57: ex. 53: Transport. 34: msg. 58: } 59: } 60: } Srikanth Technologies .setDataHandler(new DataHandler(fds)). 51: mp. 47: mbp2. 40: // create the second message part 41: MimeBodyPart mbp2 = new MimeBodyPart(). 33: msg.Java EE (Web Applications – I) 106 24: String from = "[email protected](subject).send(msg). 52: msg. internet.Java EE (Web Applications – I) 107 Sendfromgmail.*.http. 08: import javax. 02: import java. 06: import javax.WebServlet.servlet.util.mail. 12: 13: @WebServlet(name = "SendFromGmailServlet".Properties.servlet.io.*.PrintWriter.mail. 11: import javax.Security.IOException.InternetAddress.annotation. 07: import javax.io.ServletException.mail. 03: import java.servlet. 04: import java. 14: urlPatterns = {"/sendfromgmail"}) 15: public class SendMailFromGmailServlet 16: extends HttpServlet { 17: protected void doPost(HttpServletRequest request.java 01: package servlets.MimeMessage. 10: import javax. 05: import java. 18: HttpServletResponse response) Srikanth Technologies .security.internet.html 01: <html> 02: <head> 03: <title>Send Mail</title> 04: </head> 05: <body> 06: <h2>Send Mail From Gmail</h2> 07: <form action="sendfromgmail" method="post"> 08: To Address <br/> 09: <input type="text" name="toaddress" /><p/> 10: Username <br/> 11: <input type="text" name="username" /><p/> 12: Password<br/> 13: <input type="password" name="password" /><p/> 14: Subject <br/> 15: <input type="text" name="subject" /> <p/> 16: Body <br/> 17: <textarea name="body" rows="5" cols="80"></textarea> 18: <p/> 19: <input type="submit" value="Send Mail" /> 20: </form> 21: </body> 22: </html> SendMailFromGmailServlet. 09: import javax. 26: final String password = request.setRecipient(Message. 28: String body = request.getParameter("password").smtp.SSLSocketFactory".getParameter("toaddress"). 51: msg. 38: props.gmail.net. "false").setText(body).smtp.put("mail.TO. 49: Message msg = new MimeMessage(session).ssl. 57: } catch (Exception ex) { 58: ex.mail.smtp.com". 41: props. 59: } 60: } 61: } Srikanth Technologies .socketFactory. 25: final String fromAddress=username + "@gmail. 22: String SMTP_PORT = "465".setContentType("text/html"). 43: new javax.internal.fallback".Provider()). 31: PrintWriter out = response.Java EE (Web Applications – I) 108 19: throws ServletException.put("mail.host". 47: } 48: }).smtp.Authenticator() { 44: protected PasswordAuthentication 45: getPasswordAuthentication(){ 46: return new PasswordAuthentication(username.put("mail.getParameter("subject"). 37: props.printStackTrace(out).getInstance(props. "true").ssl. IOException { 20: 21: String SMTP_HOST_NAME = "smtp.send(msg).println("<h4>Mail has been sent Successfully!</h4>").smtp.class". SSL_FACTORY).sun. SMTP_PORT). 30: response.getParameter("username"). 42: Session session = Session. 50: msg. 40: props.net.setSubject(subject).getParameter("body").port".socketFactory. 39: props.addProvider( 34: new com. // or use 567 23: String toAddress = request.getWriter(). SMTP_HOST_NAME).socketFactory. password). 29: String SSL_FACTORY = "javax.com". 52: new InternetAddress(toAddress)). 35: Properties props = new Properties().smtp. SMTP_PORT). 27: String subject = request.RecipientType. 32: try { 33: Security.setFrom(new InternetAddress(fromAddress)). 54: msg. 55: Transport. 56: out.put("mail. 53: msg. 24: final String username=request.auth".put("mail. 36: props.port".ssl.put("mail. Web Applications .II . var myObject = eval('(' + myJSONtext + ')'). array.  XML data is to be parsed and assigned to variables through tedious DOM APIs  Retrieving values is as easy as reading from an object property in your JavaScript code JSON Structures  A collection of name/value pairs  An ordered list of values  These are universal data structures supported by most modern programming languages  A JSON object is an unordered set of name/value pairs .” (comma) {"title":"Professional AJAX". Data is readily accessible as JSON objects in your JavaScript code.Java EE (Web Applications – II) 1 JSON (JavaScript Object Notation)  JavaScript Object Notation is a lightweight data-interchange format (Compared to XML)  Easy for humans to read and write  Easy for machines to parse and generate  JSON is a text format and it is programming language independent  JSON objects are typed while XML data is typeless . boolean whereas in XML data are all string  Native data form for JavaScript code. Srikanth Technologies .A JSON object begins with "{" and ends with "}". number. use the eval() function. Each name is followed by : (colon) and the name/value pairs are separated by “."price":399} The eval() function To convert a JSON text into a JSON object.JSON types are string. The eval() invokes the JavaScript compiler and creates an object from JSON string. Srikanth Technologies . JsonObject.0. builders. JsonGenerator Writes JSON data to a stream one element at a time. JsonString. JsonNumber JsonParser Represents an event-based parser that can read JSON data from a stream or from an object model. This API allows Java programmer to do the following:  Create JSON object using Object Model  Generate JSON object using Streaming API  Navigate JSON data using Object Model  Parse JSON data using Streaming API The following are the classes and interfaces related to JSON API in Java EE. and generator factory objects. JsonReader Reads JSON data from a stream and creates an object model in memory. support for JSON Processing is provided by Java. JsonWriter Writes an object model from memory to a stream. JsonValue. JsonArray.Java EE (Web Applications – II) 2 JSON Processing API Starting from Java EE 7. This class also contains methods to create parser. It is called as JSON Processing in Java EE (JSR-353). and generators. data. builder. Class or Interface Description Json Contains static methods to create instances of JSON parsers. Represent data types for elements in JSON JsonStructure. Create an object model or an array model in JsonArrayBuilder memory by adding elements from application code. JsonObjectBuilder. 14: } 15: } When you run the above program. 07: fw. "Director"). use the following code after you construct JsonObject: 01: // write JSON object to a file c:\java\person.txt 02: 03: FileWriter fw = new FileWriter("c:\\java\\person.createObjectBuilder().Java EE (Web Applications – II) 3 Note: Download implementation of JSON Processing API from jsonp.json. 05: fjw."occupation":"Director". 02: import javax.add("name". "Srikanth Technologies"). 10: builder.createWriter(fw). 04: JsonWriter fjw = Json.println(person).json.txt").java.out. 06: fjw.close(). 09: builder.add("company". Srikanth Technologies . "company":"Srikanth Technologies"} In case you want to write JSON object to a file.close().Json.build().JsonObjectBuilder. 01: import javax. 13: System. the following output is generated: {"name":"Srikanth".add("occupation".0.net Using JSON Processing API The following programs demonstrate how to use JSON API provided by Java EE 7. "Srikanth"). 08: builder.JsonObject.writeObject(person).json. 11: 12: JsonObject person = builder. 04: 05: public class CreateJsonObject { 06: public static void main(String[] args) { 07: JsonObjectBuilder builder = Json. 03: import javax. 08: person. 02: import javax.Java EE (Web Applications – II) 4 Creating JSON Array with Object Model You can write an object that contains an array as shown in the following example.com")."srikanthpragada@gmail. "emails":["srikanthpragda@yahoo. "occupation":"Director. Srikanth Technologies").JsonGenerator.com "]} Creating JSON Object using Generator The following program creates a JSON object using Generator. 01: import java.add("srikanthpragada@gmail. 09: person. "Srikanth"). 13: emails.com").json.createObjectBuilder().println(person.build()). It creates an array with the name contacts and adds two objects to it. 04: Srikanth Technologies . 02: import javax.add("srikanthpragda@yahoo. 03: import javax. emails).Json.out.io. 18: } 19: } The output JSON is as follows: {"name":"Srikanth".Json.add("emails". 11: 12: JsonArrayBuilder emails = Json. 03: import javax. 10: "Director.add("occupation". 04: 05: public class CreateJsonArray { 06: public static void main(String[] args) { 07: JsonObjectBuilder person = Json.json.JsonArrayBuilder. 15: 16: person.StringWriter. 14: emails. 17: System.Srikanth Technologies".json.createArrayBuilder().json.json.add("name". 01: import javax.com".stream.JsonObjectBuilder. 02: import javax.write("[email protected]() 10: .io.out.writeStartObject() 11: .close().StringWriter.println(writer).writeEnd() // for array 16: . "Director.json.write("mobile". 09: gen.toString()).writeStartArray("emails") 13: . 18: System.close(). 09: 10: gen. // for root object 17: gen.com") 15: .writeEnd().out.createGenerator(writer).write("name".com") 13: .com") 14: . 18: } 19: } Creating JSON Array using Generator The following program creates a JSON Array using Generator and writes JSON content into a file. 01: import java. "Srikanth") 11: ."9059057000") 14: . "srikanthpragada@yahoo. 17: System.stream.write("name".println(sw.write("srikanthpragada@yahoo. Srikanth Technologies") 12: .writeEnd().write("occupation". 03: import javax.write("email".Java EE (Web Applications – II) 5 05: public class UsingGenerator { 06: public static void main(String[] args) { 07: StringWriter sw = new StringWriter(). 08: JsonGenerator gen = Json. 04: 05: public class CreateJsonArrayWithGenerator { 06: public static void main(String[] args) { 07: StringWriter writer = new StringWriter(). 15: 16: gen.JsonGenerator.Json.json. 08: JsonGenerator gen = Json. 19: } 20: } Srikanth Technologies . "Srikanth Pragada") 12: .createGenerator(sw). 05: 06: public class ReadJsonObject { 07: public static void main(String[] args) throws Exception { 08: JsonReader reader = Json.co m"]} Read JSON Object using Object Model JSON API allows reading JSON objects either using JsonReader or with JsonParser. 10: JsonObject sale = reader.getInt("price")). 02: import javax. \"price\" : 1000}")).Json.JsonReader.com".Java EE (Web Applications – II) 6 {"name":"Srikanth". Srikanth Technologies".json. 01: import java.io. It is left to us to determine the type of the event and handle it accordingly. This example shows how to use JsonReader.json. "occupation":"Director. 03: import javax."[email protected]. 11: 12: System.json. Srikanth Technologies .println("Price : " + sale.readObject(). 14: } 15: } The output of the above program is as follows: Qty : 20 Price : 1000 Reading JSON Object using Streaming API The following program shows how to use JsonParser to parse JSON data and get one component at a time.getInt("qty")). 13: System. "emails":["[email protected] 09: (new StringReader("{ \"qty\" : 20. 04: import javax.out.println("Qty : " + sale. print(parser.JsonParser.getString() + " :").Event event = parser.Json. 18: } 19: } // while 20: } 21: } Srikanth Technologies . 15: case VALUE_NUMBER: 16: System. 11: switch (event) { 12: case KEY_NAME: 13: System.next(). \"price\" : 1000}")).out.json.out. 03: import javax.getInt()). 02: import javax.stream.json. 04: 05: public class ReadJsonObjectWithStreaming { 06: public static void main(String[] args) throws Exception { 07: JsonParser parser = Json.hasNext()) { 10: JsonParser. 09: while (parser.println(parser. 17: break.io.createParser 08: (new StringReader("{ \"qty\" : 20. 14: break.StringReader.Java EE (Web Applications – II) 7 01: import java. 0.  Used to make asynchronous request and response. but a new way to use existing standards  With AJAX you can create better. and DHTML  XMLHttpRequest object is the heart of AJAX What are the problems with web applications?  Too many round trips by client  Users have to wait for page refreshes  Loss of context  Client/Server (windows) applications provide superior user experience Advantages with AJAX  Asynchronous  Minimal data transfer  Responsiveness  Context is maintained  No plug-in/code to be downloaded  Several Toolkits and frameworks are available  Tremendous industry acceptance The XMLHttpRequest Object  First introduced by Microsoft in 1997. XML.  Adopted by all other major browsers.  No post back. faster. Used in Outlook Web Access and MSDN applications. Srikanth Technologies .  Used in IE 5.  Implemented as standard object in other browsers. and more user-friendly web applications  AJAX is a technology that uses JavaScript. DOM (Document Object Model). Implemented as ActiveX object in IE.Java EE (Web Applications – II) 8 AJAX  AJAX stands for Asynchronous JavaScript And XML  AJAX is a type of programming made popular in 2005 by Google (with Google Suggest)  AJAX is not a new programming language. no full refresh of the page. Response from server 3. Srikanth Technologies . Web pages and web services Web Server onreadystatechange event  Specifies the JavaScript function to be called when readyState property changes. Property Meaning readyState Indicates the state of the asynchronous request responseXML Contains XML document sent from server responseText Contains text sent from server Status Status code of the response statusText Status text sent by server Browser XMLHttpRequest 3 Callback Function Object 1. Asynchronous request 1 2 2. XMLHttpRequest calls callback.Java EE (Web Applications – II) 9  Contains methods and properties to make request synchronously or asynchronously and receive response. Properties of XMLHttpRequest object The following are the properties of XMLHttpRequest object.  Generally it examines readyState property before processing the response. getParameter("num2")). Method Meaning open(method. The values are passed to server in http post request. pwd) send(value) Sends the request with the given value. value) getResponseHeader Returns value of the specified response (name) header getAllResponseHeaders() Returns all response headers as a string abort() Aborts the current request add. 05: n2 = Integer.Java EE (Web Applications – II) 10 readyState property It contains a value that indicates the state of asynchronous request. Value Description 0 Object created but not initialized 1 open() method is called but not sent 2 send() is called but yet to receive response 3 Receiving response.parseInt(request. 06: out. 04: n1 = Integer.parseInt(request. Body is not yet received 4 Response has been completely received Methods The following are the methods of XMLHttpRequest object. n2.uname. 07: %> Srikanth Technologies .async.println(n1 + n2). Prepares an asynchronous request url.getParameter("num1")).jsp 01: <%@page contentType="text/plain"%> 02: <% 03: int n1. setRequestHeader Sets request header to the given value (name. 10: var num2 = document.true).getElementById("result").html 01: <html> 02: <head> 03: <script language="javascript"> 04: var xhr. 21: } 22: else 23: alert("Error : " + xhr.statusText). 13: xhr.jsp?num1=" +num1. // make GET request 15: } 16: function doUpdate() { 17: if (xhr. 20: result.value+"&num2=" + num2.onreadystatechange=doUpdate. 05: function create(){ 06: xhr = new XMLHttpRequest(). 11: var url="add.getElementById("num1"). 14: xhr.url.readyState == 4) 18: if (xhr.getElementById("num2").value. 24: } 25: </script> 26: </head> 27: <body onload="create()"> 29: <h2>Using AJAX to Add Numbers</h2> 30: <table> 31: <tr><td>First Number:</td> 32: <td><input type="text" id="num1"></td></tr> 33: <tr><td>Second Number:</td> 34: <td><input type="text" id="num2"></td></tr> 35: <tr><td>Result:</td><td><input type="text" 36: readonly id="result"></td></tr> 37: </table><br /> 38: <input type=button ID="Button1" onclick="updateTotal()" 39: value="Add Numbers" /> 41: </body> 42: </html> Srikanth Technologies .responseText.value= xhr.open("GET".status == 200){ 19: var result = document. 12: xhr.send(null). 07: } 08: function updateTotal(){ 09: var num1 = document.Java EE (Web Applications – II) 11 add. value = details.send(null).value = details. 16: xmlHttp.value = "". 26: empsal. 10: message = document. 27: message.innerHTML = details. 08: empname = document. which is processed using XML DOM and JavaScript in client.name. 28: } 29: else { // employee found 30: empname. empsal.error) { // employee id not found 25: empname.error.// JSON to Object 24: if (details.responseText. // make request 18: } 19: function doUpdate() { 20: if (xmlHttp. empdetails. true). 05: var empname.getElementById("empsal"). 14: var url = "empdetails_json.getElementById("empname"). 09: empsal = document. message.status === 200){ 22: var data = xmlHttp.getElementById("empid"). 15: xmlHttp.open("GET".value = "".onreadystatechange = doUpdate. 11: } // end of create 12: function getEmployeeDetails() { 13: var empid = document. The following example shows how to send XML from server and process it in client using XML DOM and JavaScript.getElementById("message"). 06: function create() { 07: xmlHttp = new XMLHttpRequest().readyState === 4 && 21: xmlHttp.salary.jsp?empid=" + empid.Java EE (Web Applications – II) 12 AJAX and XML Server-side script may send XML content to client. 32: } 33: } 34: } 35: </script> Srikanth Technologies .value. 17: xmlHttp. url. 31: empsal. 23: var details=eval("(" + data + ")").html 01: <html> 02: <head><title>AJAX and XML</title> 03: <script type ="text/javascript"> 04: var xmlHttp. jsp 01: <%@page import="java. 04: Class. 16: out.jdbc.getConnection 06: ("jdbc:oracle:thin:@localhost:1521:XE".next()) { // found 12: out.close().salary from employees where 10: employee_id=" + empid)."hr". con. 07: Statement st=con. 21: %> Srikanth Technologies .sql.println("<error>Employee ID Not Found </error>"). 20: rs.OracleDriver").println(rs.getString(1))."hr"). 17: } 18: else 19: out. 11: if (rs.createStatement().close().getParameter("empid").forName("oracle.println("</salary></employee>"). 15: out.println("<employee><name>").driver. 05: Connection con=DriverManager. 08: ResultSet rs=st.Java EE (Web Applications – II) 13 36: </head> 37: <body onload="create()"> 38: <h2>Employee Details</h2> 39: <table> 40: <tr><td>Employee ID : </td> 41: <td><input type="text" id="empid" size="10"/> 42: <input type="button" value="Get Details" 43: onclick="getEmployeeDetails()" /> 44: <span id="message" style="color:red" /> 45: </td></tr> 46: <tr><td>Employe Name : </td> 47: <td><input type="text" id="empname" 48: readonly size="30"/></td> 49: </tr> 50: <tr><td>Salary : </td> 51: <td><input type="text" id="empsal" 52: readonly size="30"/></td> 53: </tr> 54: </table> 55: </body> 56: </html> empdetails.println("</name><salary>"). 14: out.getInt(2)).executeQuery 09: ("select first_name.close(). 13: out.*" contentType="text/xml"%> 02: <% 03: String empid=request. st.println( rs. 07: empname = document. 04: var empname.responseText.status === 200){ 21: var data = xmlHttp.error) { // employee id not found 24: empname. 16: xmlHttp. 08: empsal = document.name.value = details.html 01: <html><head><title>AJAX and XML</title> 02: <script type ="text/javascript"> 03: var xmlHttp. empsal.send(null).innerHTML = details. 09: message = document. 27: } 28: else { // employee found 29: empname. 10: } // end of create 11: function getEmployeeDetails() { 12: var empid = document.value = "".getElementById("empid").getElementById("message").open("GET". url.value = details.salary. // make request 17: } 18: function doUpdate() { 19: if (xmlHttp. 14: xmlHttp. message. 25: empsal.error. 15: xmlHttp. 31: } 32: } 33: } 34: </script> 35: </head> 36: 37: <body onload="create()"> 39: <h2>Employee Details</h2> 40: <table><tr><td>Employee ID : </td> 41: <td><input type="text" id="empid" size="10"/> 42: <input type="button" value="Get Details" 43: onclick="getEmployeeDetails()" /> 44: <span id="message" style="color:red" /> Srikanth Technologies .value = "".getElementById("empname"). 26: message.// JSON to Object 23: if (details. 22: var details=eval("(" + data + ")").jsp?empid=" + empid.getElementById("empsal"). 30: empsal.onreadystatechange = doUpdate.Java EE (Web Applications – II) 14 empdetails_json.readyState === 4 && 20: xmlHttp.value. true). 13: var url = "empdetails_json. 05: function create() { 06: xmlHttp = new XMLHttpRequest(). *.javax.getString("first_name")).add("name".setString(1.add("salary".close().executeQuery().getConnection 06: ("jdbc:oracle:thin:@localhost:1521:XE". 22: rs.getInt("salary")). 14: // generate JSON 15: if (rs.*" 02: contentType="text/json"%> 03: <% 04: Class.sql. rs. "hr".getParameter("empid")).forName("oracle. 10: ps.build(). rs. 17: builder.driver.close().prepareStatement 08: ("select first_name.next()) { // found 16: builder. 11: ResultSet rs = ps.println(builder.jsp 01: <%@ page import="java. "hr"). request. con. 18: } else { 19: builder.add("error". 07: PreparedStatement ps = con.close().json.toString()).Java EE (Web Applications – II) 15 45: </td></tr> 46: <tr> 47: <td>Employe Name : </td> 48: <td><input type="text" id="empname" 49: readonly size="30"/> 50: </td> 51: </tr> 52: <tr> 53: <td>Salary : </td> 54: <td><input type="text" id="empsal" 55: readonly size="30"/> 56: </td> 57: </tr> 58: </table> 60: </body> 61: </html> empdetails_json. 23: %> Srikanth Technologies . 12: 13: JsonObjectBuilder builder = Json.jdbc. "Sorry! Employee Not Found!"). salary from employees 09: where employee_id = ?"). 05: Connection con = DriverManager.OracleDriver"). 20: } 21: out.createObjectBuilder(). ps.  It is a good practice to rename jquery-version.2. Srikanth Technologies .  AJAX needs code to be written in JavaScript.  Place jquery-1.js to jquery. 04: 05: }). Syntax The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).Java EE (Web Applications – II) 16 jQuery  JQuery is a JavaScript library developed by John Resig and his company. do more.  It greatly simplifies things that you handle with JavaScript. 01: $(document)..10. $(selector). So.  Many regard JQuery as the best JavaScript libraries of all.com. we can use JQuery to achieve the same.jquery.js in your web application’s root directory.  Download JQuery from www.. instead of using XMLHttpRequest object and other JavaScript construct to implement AJAX.write less.  Its tagline is .action()  A $ sign to define/access jQuery  A (selector) to "query (or find)" HTML elements  A jQuery action() to be performed on the element(s) The . of course with far less code to handle.js so that <script> tag need not change when version changes.ready(function(){ 02: 03: // jQuery methods go here.ready() function This function is used to execute code when the DOM is fully loaded. You can download either of the versions – compressed or development. Refer to JQuery from <script> tag in your pages. success(data. jQuery. get() The $.get( url [. textStatus.red") Selects items with css class red $("p.get() method requests data from the server with an HTTP GET request. Method Meaning load() The load() method loads data from a server and puts the returned data into the selected element. textStatus. jQuery.intro") Selects all <p> elements with class="intro" jQuery and AJAX The following examples show how to use jQuery to make AJAX request. dataType ] ) Srikanth Technologies .data. success(data. data ] [.  jQuery selectors are used to "find" (or select) HTML elements based on their id. data ] [.callback).Java EE (Web Applications – II) 17 Selectors  jQuery selectors allow you to select and manipulate HTML element(s). $(selector). Selector Example Meaning Element $("p") Selects all <p> elements $("[href]") Selects all elements with an href attribute $("p:first") Selects the first <p> element $("tr:even") Selects all even <tr> elements Id $("#output") Selects element with id output Class $(". classes. types. dataType ] ) post() The $.post( url [. jqXHR) ] [.  All selectors in jQuery start with the dollar sign and parentheses: $().post() method requests data from the server using an HTTP POST request. jqXHR) ] [.load(URL. attributes. values of attributes and much more. getJSON( url [.Java EE (Web Applications – II) 18 getJSON() Load JSON-encoded data from the server using a GET HTTP request.jsp with .val(response). jQuery. add.html) that takes two numbers from user and calls add.jsp". 06: num2 : $("#num2").js"></script> 03: <script type="text/javascript"> 04: function addNumbers(){ 05: $.get("add.val()}. data ] [.html 01: <html> 02: <script type="text/javascript" src="jquery. jqXHR)]) Create an HTML page (add.get() method of JQuery library. 11: } 12: } 13: </script> 14: <body> 16: <h2>Using AJAX to Add Numbers with Jquery</h2> 17: <table> 18: <tr><td>First Number : </td> 19: <td><input type="text" id="num1"></td></tr> 20: <tr><td>Second Number :</td> 21: <td><input type="text" id="num2" ></td></tr> 22: 23: <tr><td>Result:</td><td><input type="text" 24: readonly id="result"> 25: </td></tr> 26: </table> 27: <p /> 28: <input type="button" ID="Button1" onclick="addNumbers()" 29: value="Add Numbers" /> 31: </body> 32: </html> Srikanth Technologies .doUpdate). textStatus.val(). 07: } 08: function doUpdate(response) { 09: if (response) { 10: $("#result"). success(data.{num1 : $("#num1"). jsp". "hidden") 16: 17: if($(data).val() takes the value from the field that is with id num1.jsp. Apart from taking XML from server and parsing it.js using <script> tag  Use $.  Check whether response is available and then place it into text field with id result.val()}.  The expression $("#num1"). I have used clock. which is sum in this case. 01: <html> 02: <head> 03: <title>AJAX and XML with JQUERY </title> 04: <script src="jquery. "visible") 09: $. No need to use XMLHttpRequest directly.HTML. it also demonstrates how to show progress icon to user while request is in progress. Using XML with JQuery  The following is the code for EMPDETAILS. JQuery library takes care of it.jsp is same as what we used in AJAX example.find("error").text()!= "") // error 18: { Srikanth Technologies .  JSP empdetails.css("visibility"./empdetails. 10: {empid: $("#empid").  Make sure clock. 12: } 13: function displayResult(data) { 14: // hide clock image 15: $("#clock").get method to make an AJAX call to add.Java EE (Web Applications – II) 19 The following are important steps in the above program :  Include jquery.js"></script> 05: <script> 06: function getEmployeeDetails() { 07: // make clock image visible 08: $("#clock").  Function css is used to add CSS attributes to an element.  Call-back method (doUpdate) has a single parameter that contains the response from the server.css("visibility".gif for this.gif is placed in webpages folder. The last parameter to get() method is the call-back method. 11: displayResult)..get(". HTML page.gif" 48: style="visibility:hidden"/> 49: </body> 50: </html> Run EMPDETAILS.val($("salary".text()). you must see either details of employee in text fields or error message as alert.val($(data).Java EE (Web Applications – II) 20 19: // clear fields 20: $("#empname"). enter employee id and click on button.text()).find("error").text()) 28: } 29: } 30: </script> 31: </head> 32: <body> 33: <h2>Employee Details</h2> 34: <table><tr><td>Employee ID : </td> 35: <td><input type="text" id="empid" size="10"/> 36: <input type="button" value="Get Details" 37: onclick="getEmployeeDetails()" /> 38: </td></tr> 39: <tr><td>Employe Name : </td> 40: <td><input type="text" id="empname" 41: readonly size="30"/></td></tr> 42: <tr><td>Salary : </td> 43: <td><input type="text" id="empsal" 44: readonly size="30"/></td></tr> 45: </table> 46: <p/> 47: <img id="clock" src="clock.find("name"). data). Srikanth Technologies .val("") 21: $("#empsal").val("") 22: alert("Error : "+ $(data). 27: $("#empsal"). After a little while. 23: } 24: else // found employee and got details 25: { 26: $("#empname"). val("") // clear fields 13: $("#empsal"). empdetails_json. Let us create HTML page (empdetails_json. Display details 17: $("#empname"). 18: $("#empsal").Java EE (Web Applications – II) 21 Using JSON with JQuery Let us now see how JQuery is used to process JSON string that comes from server to client. The following example takes employee id and displays details of employee by getting those details from empdetails_json.jsp. which was used in AJAX example. 19: } 20: } 21: </script> 22: </head> 23: <body> 26: <h2>Employee Details</h2> 27: <table> 28: <tr> 29: <td>Employee ID : </td> 30: <td><input type="text" id="empid" size="10"/> Srikanth Technologies .val()}.html 01: <html> 02: <head> 03: <title>AJAX and JSON with JQUERY </title> 04: <script type="text/javascript" src="jquery.name).html) that uses JQuery to make AJAX call to EMPDETAILS_JSON.JSP.val("") 14: alert( data.salary).val( data. We will use getJSON() method to send request to server.error).{empid : 08: $("#empid"). The main advantage with this method is.val( data. displayResult). it parses the response string as JSON.getJSON( "empdetails_json. 15: } 16: else { // Found employee.js"></script> 05: <script language="javascript"> 06: function getEmployeeDetails(){ 07: $. The code is given below.jsp". 09: } 10: function displayResult(data) { 11: if ( data.error) { // emp not found 12: $("#empname"). function(index. Getting details of Employees based on selected Job The following example displays list of jobs in a listbox and allows user to select a job by double clicking on job to get the names of the employees who belong to the selected job.js"></script> 05: <script type="text/javascript" language="javascript"> 06: // this is done when page is loaded 07: $(function() { 08: $.each(data.{}.job){ 14: // add items to List box 15: $("#jobs").getJSON("jobs. jobs. you must see either details of employee in text fields or error message as alert. After a little while. 11: 12: function displayJobs(data) { 13: $.append("<option value='" + job.HTML page.Java EE (Web Applications – II) 22 31: <input type="button" value="Get Details" 32: onclick="getEmployeeDetails()" /> </td></tr> 33: <tr><td>Employee Name : </td> 34: <td><input type="text" id="empname" 35: readonly size="30"/></td> 36: </tr> 37: <tr><td>Salary : </td> 38: <td><input type="text" id="empsal" 39: readonly size="30"/></td> 40: </tr> 41: </table> 42: </form> 43: </body> 44: </html> Run EMPDETAILS_JSON.jsp".html 01: <html> 02: <head> 03: <title>Jobs and Employees</title> 04: <script type="text/javascript" src="jquery.displayJobs). Srikanth Technologies . enter employee id and click on button. 09: } 10: ).title + "</option>").id + "'>" 16: + job. function(index. 32: } // end of function 33: ). // clear options 23: $.each(data.remove().</b> 46: </td> 47: <td valign ="top" width="200px"> 48: <h3>Employees </h3> 49: <select id="employees" size="10" 50: style="width:200px"></select></td> </tr> 51: </table> 52: </form> 53: </body> 54: </html> Srikanth Technologies . // each 34: } 35: </script> 36: </head> 37: <body> 38: <form id="form1"> 39: <h2>Jobs and Employees</h2> 40: <table> 41: <tr> 42: <td valign="top" width="200px"> <h3>Jobs </h3> 43: <select id="jobs" size="10" 44: ondblclick="getEmployees()"></select><p/> 45: <b>Double click on Job to get Employees of that Job.jsp".Java EE (Web Applications – II) 23 17: } 18: ). 25: } 26: 27: function displayEmployees(data) { 28: $.name){ 29: // add names to List box 30: $("#employees"). 24: displayEmployees).append("<option>" + 31: name + "</option>"). 19: } 20: 21: function getEmployees() { 22: $("#employees").getJSON("employees.{jobid:$("#jobs").val()}.contents(). createArrayBuilder(). 14: 15: while (rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE").build(). 13: 14: 15: JsonArrayBuilder emps = Json.sql. 11: rs.setUsername("hr").setCommand("select * from jobs").setCommand("select first_name ||' '|| last_name 10: fullname from employees where job_id = ?").json. 09: rs. 23: out.setUrl("jdbc:oracle:thin:@localhost:1521:XE").*" 02: contentType="application/json"%> 03: <% 04: javax. 12: rs. rs.build()).toString()).getString("job_id")). 24: %> employees. 11: rs. 10: rs. 09: rs.setString(1. 18: job.createObjectBuilder().CachedRowSet rs = 05: new oracle.rowset.add(job. request.setPassword("hr").getString("job_title")). rs.sql. 20: } 21: 22: rs. 12: 13: JsonArrayBuilder jobs = Json.jdbc.jsp 01: <%@page import="javax.rowset.close().execute().jsp 01: <%@page import="javax.add("title".json.rowset. 17: job.getParameter("jobid")). 07: rs.createArrayBuilder().next()) { 16: JsonObjectBuilder job = Json.setPassword("hr").Java EE (Web Applications – II) 24 jobs.CachedRowSet rs = 06: new oracle.next()) { Srikanth Technologies .println(jobs.add("id".OracleCachedRowSet().OracleCachedRowSet(). 06: rs.execute(). 08: rs.*" 02: contentType="application/json"%> 03: 04: <% 05: javax. 08: rs.jdbc.rowset. 16: while (rs. 07: rs.setUsername("hr"). 19: jobs. 23: out.println( emps.getString("fullname")).Java EE (Web Applications – II) 25 17 emps.toString()). 24: %> Srikanth Technologies .add(rs. 21: } 22: rs.close().build(). Pattern.org/validator and place .Size. Some of the commonly used built-in annotations are listed below: @Min The annotated element must be a number whose value must be higher or equal to the specified minimum.Java EE (Web Applications – II) 26 BEAN VALIDATION  Bean validation (JSR 303) is a new feature that is available in Java EE 6. 03: import javax.NotNull.validation. Download Hibernate Validator from http://hibernate. or class of a JavaBean. 06: 07: public class User { Srikanth Technologies .Max.validation.validation.constraints package.constraints.constraints. 04: import javax.constraints. @Max The annotated element must be a number whose value must be lower or equal to the specified maximum.Min.validation.validation. method. we have to use Hibernate Validator. 02: import javax. @Size The annotated element must be between specified minimum and maximum boundaries. @Null The annotated element must be null.constraints.java 01: import javax.  The bean validation model is supported by constraints in the form of annotations placed on a field. User.constraints. @NotNull The annotated element must not be null. To use Bean Validation.  Several built-in annotations are available in the javax. @Pattern The annotated element must match the specified Java regular expression.jar files related to Hibernate Validator and their dependencies in classpath of our project.validation. which is one of the implementations of Bean Validation Specifications. 05: import javax. 28: } 29: public String getMobile() { 30: return mobile. 21: message = "Mobile number must be of 10 digits") 22: private String mobile. 43: } 44: public void setUname(String uname) { 45: this. we need to use Validation API to test whether data in the bean is valid as follows: Srikanth Technologies . 31: } 32: public void setMobile(String mobile) { 33: this. 34: } 35: public String getPassword() { 36: return password. 19: 20: @Pattern (regexp="^[0-9]{10}$".Java EE (Web Applications – II) 27 08: @NotNull(message="Username Required") 09: @Size(min=6. 15: 16: @Min( value=18 .mobile = mobile. 40: } 41: public String getUname() { 42: return uname. 37: } 38: public void setPassword(String password) { 39: this. 46: } 47: } Once Bean with validation annotations are created. max=10. 23: public int getAge() { 24: return age. message="Age must be <= 100") 18: private int age. message="Age must be >= 18") 17: @Max( value=100. 10: message="Username must be between 6 to 10 chars") 11: private String uname.password = password.uname = uname. 25: } 26: public void setAge(int age) { 27: this. 12: 13: @NotNull(message="Password Required") 14: private String password.age = age. 17: u.Set. 06: 07: public class ValidateUser { 08: public static void main(String[] args) { 09: ValidatorFactory factory = 10: Validation.validation.getValidator().util.Validation.setMobile("905905700").Validator. 18: 19: Set<ConstraintViolation<User>> errors = 20: validator.setUname("Gavin"). 16: u. 24: } 25: } When run.setAge(12).getMessage()).Java EE (Web Applications – II) 28 01: import java.setPassword("king"). 05: import javax. 04: import javax.println(v. 02: import javax. 12: 13: User u = new User(). 03: import javax.ConstraintViolation. 21: 22: for(ConstraintViolation<User> v: errors) 23: System. 11: Validator validator = factory.validation.ValidatorFactory.validation.buildDefaultValidatorFactory().validate(u). 14: u. above program outputs the following messages: Age must be >= 18 Mobile number must be of 10 digits Username must be between 6 to 10 chars Srikanth Technologies .validation.out. 15: u. classes.  The javax. interfaces. String msg) { } OnError Connection error @OnError public void error(Session session. EndpointConfig conf) { } OnMessage Message received @OnMessage public void message (Session session. and interfaces to create and configure server endpoints. you extend the Endpoint class and override its lifecycle methods. classes. Annotation Event Example OnOpen Connection @OnOpen opened public void open(Session session.  To create a programmatic endpoint.  The javax.websocket.  Client uses the endpoint’s URI to connect to the server  After the connection has been established.server package contains annotations.websocket package contains annotations. and exceptions that are common to client and server endpoints. Throwable error) { } OnClose Connection closed @OnClose public void close(Session session. the client and the server can send messages to each other at any time while the connection is open  Client and Server can close the connection at any time Java API for Web Socket  Java API for WebSocket (JSR-356) provides support for creating WebSocket applications.Java EE (Web Applications – II) 29 Web Sockets  WebSocket is an application protocol that provides full-duplex communications between client and server over the TCP protocol  Server publishes a WebSocket endpoint. you decorate a Java class and some of its methods with the annotations provided by the packages above.  To create an annotated endpoint. CloseReason reason) { } Srikanth Technologies . websocket.util. 18: session. 13: childThread = new Thread(new Runnable() { 14: public void run() { 15: while (true) { 16: try { 17: Thread.websocket.getBasicRemote(). 04: import javax.println("Opened connection for TimeEndPoint"). 05: import javax.server. 06: 07: @ServerEndpoint("/time") 08: public class TimeEndPoint { 09: Thread childThread.Date(). 26: } // openConnection() 27: } // TimeEndPoint Srikanth Technologies . 10: @OnOpen 11: public void openConnection(final Session session) { 12: System.start().websocket. 02: import javax.OnMessage.websocket.out.Session. 19: sendText(new java.java 01: package endpoints. 20: } catch (Exception ex) { 21: } 22: } // while 23: } // run() 24: }).sleep(5000).OnOpen. 25: childThread.ServerEndpoint.Java EE (Web Applications – II) 30 The process for creating and deploying a WebSocket endpoint is the following:  Create an endpoint class  Implement the lifecycle methods of the endpoint  Add your business logic to the endpoint  Deploy the endpoint inside a web application TimeEndPoint. 03: import javax.toString()). 12: sendText(message.println("message received :" + message).toUpperCase()). 05: var outputText. 11: session.getBasicRemote(). 10: outputText = document. 15: } 16: window. 17: </script> 18: </head> 19: <body> 20: <h2>Time Client</h2> 21: <div id="outputText"></div> 22: </body></html> Full duplex Web Socket The following example shows how to send data from client and receive data from server.*. 06: function connect() { 07: wsocket=new 08: WebSocket("ws://localhost:8888/websocketsdemo/time").server. 09: wsocket.getElementById("outputText"). 02: import javax. 04: 05: @ServerEndpoint("/upper") 06: public class UpperEndPoint { 07: @OnMessage 08: public void onMessage(Session session. connect).innerHTML = data.html 01: <!DOCTYPE html> 02: <html><head> 03: <script type="text/javascript"> 04: var wsocket.addEventListener("load".ServerEndpoint. UpperEndPoint. String message){ 09: try { 10: System.onmessage = onMessage.websocket.Java EE (Web Applications – II) 31 TimeClient. 13: } catch (Exception ex) { Srikanth Technologies .java 01: package endpoints. 03: import javax. 11: } 12: function onMessage(evt) { 13: var data = evt.out.data.websocket. 14: outputText. innerHTML = data.addEventListener("load".Java EE (Web Applications – II) 32 14: } 15: } 16: } UpperClient. 18: } 19: function sendText(){ 20: wsocket.send( inputText. 21: } 22: window.data. 13: outputText = document.getElementById("outputText"). 17: outputText. 14: } 15: function onMessage(evt) { 16: var data = evt. 08: function connect() { 09: wsocket = new WebSocket 10: ("ws://localhost:8888/websocketsdemo/upper"). connect). 23: </script> 24: </head> 25: <body> 26: Enter Text : <input type="text" id="inputText" 27: size="20"/> 28: <p/> 29: <input type="button" value="Send" 30: onclick="sendText()"/> 31: <p/> 32: <div id="outputText"></div> 33: </body></html> Srikanth Technologies .value). 11: wsocket.html 01: <!DOCTYPE html> 02: <html> 03: <head> 04: <script type="text/javascript"> 05: var wsocket. 06: var inputText.onmessage = onMessage. 12: inputText = document. 07: var outputText.getElementById("inputText"). Loosely Web services may add new methods and change the coupled business logic without affecting the client as long as it provides the old methods that clients are accessing.  Language and platform independent. a server application that implements the methods that are available for clients to call.Java EE (Web Applications – II) 33 What is Web Service?  Web service is a collection of methods that can be called by a remote client over the Internet. CORBA.  Websites like Amazon. is deployed on a server-side container. However.  Mainly used in B2B applications. and EBay are providing web services to third-party developers. XML and SOAP.  Based on industry standards such as Http. Simple It is easy to create a web service and make it available to all platforms. Scalable A client makes a request for a method in web Srikanth Technologies .  A way of building service-oriented architecture (SOA). Accessible Legacy assets & internal apps are exposed and accessible on the web. Google.  Web services can offer application components like currency conversion. compared with RMI. weather reports or even language translation as services. SOAP Request Web Service Web service Consumer SOAP Request Advantages of Web Service Web service is another way to develop distributed applications.  A Web service. web services provide the following key advantages. and DCOM. So the administrator need not configure Firewall to allow access to any specific port explicitly. an XML language defining a message architecture and message formats. Srikanth Technologies . which uses port Friendly number 80. The two types of web services discussed in this section can be distinguished as “big” web services and “RESTful” web services.  WSDL is an XML document. Allows connection across heterogeneous networks using ubiquitous web-based standards. This helps in scalability as web service can serve more number of clients easily. an XML language for defining interfaces syntactically.  Big web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard. written in the Web Services Description Language (WSDL). Types of Web Services On a technical level.  Project Metro implements JAX-WS. Interoperability  Interoperability allows service and client to be in different languages and platforms. Firewall Web services use HTTP protocol. Port number 80 is generally accessible through Firewall from outside the server. which describes a Web service in a standard way. “Big” Web Services  JAX-WS provides the functionality for “big” web services. web services can be implemented in various ways. SOAP defines standards for XML messaging and the mapping of data types.  Provides description of the operations offered by the service.  What makes this interoperability possible is support for SOAP and WSDL. Soap internally uses HTTP for transport and XML for messaging.Java EE (Web Applications – II) 34 service and receives the response and then connection between web service and client is closed.  Project Jersey is the production-ready reference implementation for the JAX-RS specification.  RESTful web services. Data is passed as XML  SOAP is simple and extensible  SOAP allows you to get around firewalls as it uses HTTP st que C# Client P Re SO A On Window nse Web service spo P Re In Java on SOA Unix SOAP Reque st SOAP Respo nse Java Client On Macintosh Srikanth Technologies . often better integrated with HTTP than SOAP-based services. SOAP protocol The following are the features of SOAP protocol:  SOAP stands for Simple Object Access Protocol  SOAP is a communication protocol  SOAP is for communication between applications  SOAP is a format for sending messages  SOAP is designed to communicate via Internet  It uses HTTP protocol to send request and response  SOAP is based on XML. ad hoc integration scenarios.Java EE (Web Applications – II) 35 RESTful Web Services  JAX-RS provides the functionality for Representational State Transfer (RESTful) web services. do not require XML messages or WSDL service–API definitions.  REST is well suited for basic. SOAP Building Blocks A SOAP message is an ordinary XML document containing the following elements:  A required Envelope element that identifies the XML document as a SOAP message  An optional Header element that contains header information  A required Body element that contains call and response information  An optional Fault element that provides information about errors that occurred while processing the message Srikanth Technologies . The SOAP Envelope in turn is then made of header and body. SOAP attachment allows the SOAP message to contain not only the XML data but also non-XML data such as binary graphics file.Java EE (Web Applications – II) 36 SOAP message is made of SOAP Envelope and zero or more attachments. And it uses the MIME multipart as container for these non-XML data. The SOAP specification defines the envelope structure. Makes a request for WSDL Document Tool to Web service generate Proxy WSDL Document Generates Proxy Proxy What is JAX-WS?  JAX-WS stands for Java API for XML Web Services.Java EE (Web Applications – II) 37 What is WSDL?  A Web service can make itself available to potential clients by describing itself in a Web Services Description Language (WSDL) document. the parameters for those operations. including its name. a web service operation invocation is represented by an XML-based protocol such as SOAP. and the location of where to send requests. It was earlier called as JAX-RPC (Java API for XML Remote Procedure Call).  A consumer (Web client) can use the WSDL document to discover what the service offers and how to access it. encoding rules.  In JAX-WS. and conventions for representing web service invocations and responses.  A WSDL description is an XML document that gives all the pertinent information about a Web service. Web services are defined as a set of endpoints operating on messages.  These calls and responses are transmitted as SOAP messages (XML files) over HTTP.  Under J2EE context.  JAX-WS allows developers to write message-oriented as well as RPC-oriented web services. the operations that can be called on it.  JAX-WS is a technology for building web services and clients that communicate using XML. Srikanth Technologies .  An SEI is not required when building a JAX-WS endpoint. A client creates a proxy (a local object representing the service) and then simply invokes methods on the proxy. Client Service JAX-WS Runtime SOAP Message JAX-WS Runtime JAX-WS Endpoint  The Web Service annotation defines the class as a web service endpoint. the developer does not generate or parse SOAP messages.  Another aspect to note is that a Web service is described in WSDL document and this service description can be published to a registry.  These endpoints are operating within a container. the JAX-WS API hides this complexity from the application developer. which provides Web services runtime environment in the same way EJB container provides runtime environment for EJB beans. The web service implementation class implicitly defines an SEI.  What this means is that the WSDL document is the only thing that is needed between web service user and service provider in order to communicate.  With JAX-WS. Srikanth Technologies .  It is the JAX-WS runtime system that converts the API calls and responses to and from SOAP messages.  Client programs are also easy to code. How does JAX-WS work?  Although SOAP messages are complex.Java EE (Web Applications – II) 38  The endpoints receive request messages and then send back response messages.  A service endpoint interface (SEI) is a Java interface that declares the methods that a client can invoke on the service.  The implementing class may explicitly reference an SEI through the endpointInterface element of the @WebService annotation.  Implementing class must not be declared final and must not be abstract.  The @PostConstruct method is called by the container before the implementing class begins responding to web service clients. and must not be declared static or final.  Business methods that are exposed to web service clients must be annotated with WebMethod.  The implementing class must have a default public constructor. Srikanth Technologies .  The business methods of the implementing class must be public.  Business methods that are exposed to web service clients must have JAX-B-compatible parameters and return types. but is not required to do so.Java EE (Web Applications – II) 39  The implementing class must be annotated with either the WebService or WebServiceProvider annotation. JAX-WS Implementations The following are the implementations of JAX-WS:  Metro Project in GlassFish  Apache CXF  Apache Axis2  JBossWS in JBoss  IBM WebSphere Jax-Ws in WebSphere  Oracle Weblogic We need to use one of the above implementations to create web service. an SEI is implicitly defined for the implementing class.  The @PreDestroy method is called by the container before the endpoint is removed from operation.  The implementing class may use the PostConstruct or PreDestroy annotations on its methods for lifecycle event callbacks.  If no endpointInterface is specified in @WebService. org/xml/ns/javaee/web-app_3_1.0" encoding="UTF-8"?> 02: <endpoints 03: xmlns="http://java.jcp. WEB-INF/web.ws.ws.servlet.org/xml/ns/javaee" 03: xmlns:xsi="http://www.org/2001/XMLSchema-instance" 04: xsi:schemaLocation="http://xmlns.xml.1" 02: xmlns="http://xmlns.jar files) and configure other components.xml – which provides information about web services in the current project.sun.Java EE (Web Applications – II) 40 In order to use any implementation.w3.xml.http. we need to download appropriate libraries (.sun. 11: WSServletContextListener 12: </listener-class> 13: </listener> 14: <servlet> 15: <servlet-name>metro-servlet</servlet-name> 16: <servlet-class> 17: com.jcp. 01: <?xml version="1.WSServlet 18: </servlet-class> 19: <load-on-startup>1</load-on-startup> 20: </servlet> 21: <servlet-mapping> 22: <servlet-name>metro-servlet</servlet-name> 23: <url-pattern>/services/*</url-pattern> 24: </servlet-mapping> 25: </web-app> We need to create another XML file – sun-jaxws.com/xml/ns/jax-ws/ri/runtime" 04: version="2.org/xml/ns/javaee 05: http://xmlns. In order to use Metro. we need to download metro JAR files and configure web application to use a Servlet and Listener as shown below.xsd"> 06: 07: <display-name>Metro Services Demo</display-name> 08: <listener> 09: <listener-class> 10: com.0"> Srikanth Technologies .http.servlet.xml 01: <web-app version="3.transport.sun.transport.jcp. util.Date. It can be hosted on any server that supports Java EE web services.WebMethod.jws. 05: 06: @WebService 07: public class HelloService { 08: @WebMethod 09: public Date getCurrentDate() { 10: return new Date(). Annotation WebMethod is used to create web method. Use the following URL to test our web service: http://localhost:8888/metrowebservice/services/hello You will get the following details regarding web service: Srikanth Technologies . 04: import javax. 02: import java. which can be called from consumer of the web service. 15: } 16: } Annotation WebService specifies the class HelloService is a web service.WebService. 01: package metro. 03: import javax." + name.Java EE (Web Applications – II) 41 05: <endpoint name="HelloService" 06: implementation="metro.HelloService" 07: url-pattern="/services/hello" /> 08: </endpoints> A simple web service The following is a simple web service with a single method.jws. 11: } 12: @WebMethod 13: public String getMessage(String name) { 14: return "Hello . it can be consumed from any other application irrespective of language. Consuming Web Service In order to consume a web service.  Select src folder and right click. we have to create a web service proxy using the following procedure in Eclipse.  Create a new Java Project.  Select Web Services and Web Service Client option under that. Once Web Service is published to Tomcat.Java EE (Web Applications – II) 42 Click on WSDL link to get WSDL generated for this web service. technology and platform. From popup menu select Other. Srikanth Technologies . The following window is displayed. Srikanth Technologies .  Click on Finish to generate classes related to proxy. The following classes (shown in Project Explorer) are generated for proxy to access HelloService web service. Eclipse automatically adds required JAR files (as you can see in screenshot) to consume Web Service.Java EE (Web Applications – II) 43  Enter WSDL url (http://localhost:8888/metrowebservice/services/hello?wsdl) in the given textbox as shown in the following diagram. 03: public class HelloClient { 04: public static void main(String[] args) throws Exception { 05: HelloServiceProxy proxy = new HelloServiceProxy(). 02: import metro.getMessage("Srikanth")).HelloServiceProxy.println(proxy.Java EE (Web Applications – II) 44 Here is the code for HelloClient. 07: } 08: } Srikanth Technologies . 06: System. 01: package metroclient.out. which uses proxy to call getMessage() method of the Web Service. Srikanth Technologies . the parameter is pulled from a message header rather than the message body. the targetNamespace is used for the namespace for the wsdl:portType (and associated XML elements). serviceName The service name of the Web Service. Attribute Meaning boolean header If true. Method is not required to throw java. @WebParam Customizes the mapping of an individual parameter to a Web Service message part and XML element.targetNamespace annotation is on a service endpoint interface.RemoteException. name The name of the Web Service. targetNamespace If the @WebService. @WebMethod It customizes a method that is exposed as a Web Service operation. String Name of the wsdl:operation matching this operationName method.rmi. Attribute Meaning String action The action for this operation. portName The port name of the Web Service. Attribute Meaning endpointInterface The complete name of the service endpoint interface defining the service’s abstract Web Service contract.Java EE (Web Applications – II) 45 @WebService Marks a Java class as implementing a Web Service. or a Java interface as defining a Web Service interface. wsdlLocation The location of a pre-defined WSDL. boolean exclude Marks a method to NOT be exposed as a web method. 08: } 09: public void setId(String id) { 10: this. String name Name of the parameter. Employee. String The XML namespace for the return value. Attribute Meaning boolean header If true. OUT. 06: public String getId() { 07: return id. name.Mode The direction in which the parameter is flowing mode (One of IN. String The XML namespace for the parameter. String partName The name of the wsdl:part representing this return value. 02: 03: public class Employee { 04: private String id. targetNamespace A web service to provide details of an Employee The following web service provides details of employees by accessing Oracle database. the result is pulled from a message header rather than the message body. targetNamespace @WebResult It customizes the mapping of the return value to a WSDL part and XML element. or INOUT).Java EE (Web Applications – II) 46 WebParam. 05: private double salary.java 01: package metro. String partName The name of the wsdl:part representing this parameter.id = id. 11: } 12: public String getName() { Srikanth Technologies . String name Name of return value. 13: rs. 15: rs.rowset. 06: @WebService(serviceName = "EmployeeService") 07: public class EmployeeService { 08: @WebMethod 09: public ArrayList<Employee> getEmployees() { 10: try (CachedRowSet rs = new OracleCachedRowSet()) { 11: rs. 23: } 24: } Employees.CachedRowSet.next()) { 18: Employee e = new Employee(). 22: el. 28: } 29: } Srikanth Technologies .setUrl("jdbc:oracle:thin:@localhost:1521:XE"). 05: import oracle.out. 16: ArrayList<Employee> el = new ArrayList<>(). 02: import java.setUsername("hr").salary = salary.jdbc. 25: } catch (Exception ex) { 26: System. 17: } 18: public double getSalary() { 19: return salary. 23: } 24: return el.name = name. 12: rs.setPassword("hr"). 21: e.add(e).util.jws. 14: } 15: public void setName(String name) { 16: this.Java EE (Web Applications – II) 47 13: return name.*.OracleCachedRowSet.setCommand("select * from employees"). 19: e. 04: import javax.println(ex.rowset.getString("first_name")). 03: import javax.getMessage()).execute(). 17: while (rs. 14: rs. 20: } 21: public void setSalary(double salary) { 22: this.setId(rs. 20: e.java 01: package metro. 27: return null.getString("employee_id")).setSalary(rs.sql.getDouble("salary")).ArrayList.setName(rs. 04: public class EmployeeClient { 05: public static void main(String[] args) throws Exception { 06: EmployeeServiceProxy proxy = new EmployeeServiceProxy(). empid).getMessage()). 38: rs.execute(). 44: e.out.setString(1.out. 13: } 14: } Srikanth Technologies . 37: rs.println(ex. 41: rs.setId(rs.EmployeeServiceProxy.setName(rs. 02: import metro. 42: if (rs.setPassword("hr").setCommand 39: ("select * from employees where employee_id=?").getString("first_name")). 08: for(Employee e : list) 09: System. 47: return e. 50: } 51: } catch (Exception ex) { 52: System.getDetails("111").out. 40: rs. 12: System. 45: e.getName()).println(e.getString("employee_id")).getEmployees().getName()). 46: e.println(e.getDouble("salary")).setSalary(rs.Java EE (Web Applications – II) 48 30: 31: @WebMethod 32: public Employee getDetails 33: (@WebParam(name = "empid") String empid) { 34: try (CachedRowSet rs = new OracleCachedRowSet()) { 35: rs. 54: } 55: } // getDetails() 56: } // EmployeeService EmployeeClient.Employee. 53: return null. 48: } else { 49: return null. 10: 11: Employee e = proxy. 36: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE"). 07: Employee list [] = proxy. 03: import metro.setUsername("hr").next()) { 43: Employee e = new Employee().java 01: package metroclient. Date xs:dateTime javax.namespace.QName xs:QName java.datatype.util.awt.xml.String xs:string java.Source xs:base64Binary java.DataHandler xs:base64Binary javax.datatype.transform.Image xs:base64Binary javax.math.lang.xml.Calendar xs:dateTime java.URI xs:string javax.BigInteger xs:integer java.BigDecimal xs:decimal java.Duration xs:duration java. Java Class XML Data Type java.xml.UUID xs:string Srikanth Technologies .net.Object xs:anyType java.lang.xml.XMLGregorianCalendar xs:anySimpleType javax.util. but they should be aware that not every class in the Java language can be used as a method parameter or return type in JAX-WS.math. Application developers don't need to know the details of these mappings.Java EE (Web Applications – II) 49 JAXB (Java API for XML Binding) JAX-WS delegates the mapping of Java programming language types to and from XML definitions to JAXB.util.activation. 0 only allows validation at unmarshal and marshal time.  Marshalling provides a client application the ability to convert a JAXB-derived Java object tree back into XML data.  Client applications are not required to validate the Java content tree before marshalling.  JAXB 2. Validation  Validation is the process of verifying that an XML document meets all the constraints expressed in the schema. To meet that model. There is also no requirement that the Java content tree be valid with respect to its original schema in order to marshal it back into XML data. validation was added to marshal time.  JAXB 1.  By default.0 provided validation at unmarshal time and also enabled on-demand validation on a JAXB content tree. so that one could confirm that they did not invalidate the XML document when modifying the document in JAXB form.Java EE (Web Applications – II) 50 Unmarshalling  Unmarshlling provides a client application the ability to convert XML data into JAXB-derived Java objects. A web service processing model is to be lax in reading data and strict on writing it out. the Marshaller uses UTF-8 encoding when generating XML data. Srikanth Technologies . typically links on the Web. They just need to access URL and receive the response sent by URL.  It is possible to cache result of RESTful web service  Highly interoperable as clients don’t need any toolkit (to create proxy). and modifiability. The response could be XML. the reference implementation of JAX-RS. that if applied to a web service.  In the REST architectural style. which enable services to work best on the Web. making it easy for developers to build RESTful web services by using the Java programming language. @POST. scalability. implements support for the annotations defined in JSR 311.  It is simple to create RESTful services  They scale well to large number of clients  Enables transfer of data in streams of unlimited size and type. What are RESTful Web Services?  RESTful web services are built to work best on the Web. such as performance.Java EE (Web Applications – II) 51 RESTful Web Services Jersey. @PUT. or @DELETE. such as @GET. mainly compared with SOAP web services. Advantages of RESTful Services The following are considered as advantages of Restful services. data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs). such as the uniform interface. induce desirable properties.  Representational State Transfer (REST) is an architectural style that specifies constraints. Creating a RESTful Root Resource Class Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator. JSON or plain text. Srikanth Technologies . Java EE (Web Applications – II) 52 Resource methods are methods of a resource class annotated with a request method designator. Developing RESTful Web Services with JAX-RS  JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture.  The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services.  Developers decorate Java programming language class files with JAX-RS annotations to define resources and the actions that can be performed on those resources. JAX-RS annotations are runtime annotations; therefore, runtime reflection will generate the helper classes and artifacts for the resource.  A Java EE application archive containing JAX-RS resource classes will have the resources configured, the helper classes and artifacts generated, and the resource exposed to clients by deploying the archive to a Java EE server. Hello.java 01: package rest; 02: import javax.ws.rs.GET; 03: import javax.ws.rs.Path; 04: import javax.ws.rs.Produces; 05: import javax.ws.rs.core.MediaType; 06: 07: @Path("/hello") 08: public class Hello { 09: @GET 10: public String getMessage() { 11: return "Hello Restful Services"; 12: } 13: } URLHelloClient.java 01: import java.net.URL; 02: import java.util.Scanner; 03: public class UrlHelloClient { 04: public static void main(String[] args) throws Exception { 05: String BASE_URI = 06: "http://localhost:8888/jersey/rest/hello"; Srikanth Technologies Java EE (Web Applications – II) 53 07: URL u = new URL(BASE_URI); 08: Scanner s = new Scanner(u.openStream()); 09: System.out.println(s.nextLine()); 10: } 11: } The following Restful service takes a name from user and sends message along with the given user name. HelloUser.java 01: package rest; 02: import javax.ws.rs.PathParam; 03: import javax.ws.rs.Path; 04: import javax.ws.rs.GET; 05: import javax.ws.rs.Produces; 06: 07: // whatever is given after /hello/ is treated as name 08: @Path("/hello/{name}") 09: public class Hello{ 10: @GET 11: @Produces("text/plain") 12: //Name passed after /hello/ is copied into name param 13: public String getMessage( 14: (@PathParam("name") String name) { 15: return "Hello, " + name; 16: } 17: } The following are the annotations related to restful web services. Annotation Description @Path The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted: for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user and pass it to the application as a variable in the URI:/helloworld/{username}. @GET The @GET annotation is a request method designator Srikanth Technologies Java EE (Web Applications – II) 54 and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. @POST The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding. @PathParam The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. @QueryParam The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters. @Consumes The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. @Produces The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client: for example, "text/plain". Srikanth Technologies Java EE (Web Applications – II) 55 The @Path Annotation and URI Path Templates  The @Path annotation identifies the URI path template to which the resource responds and is specified at the class or method level of a resource.  The @Path annotation’s value is a partial URI path template relative to the base URI of the server on which the resource is deployed, the context root of the application, and the URL pattern to which the JAX-RS runtime responds.  RI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by braces ({and}). URI Path Template URI After Substitution /{name1}/{name2} /james/joe /{question}/{question}/{question} /why/why/why /maps/{location} /maps/Vizag /{name3}/home //home Responding to HTTP Resources The behavior of a resource is determined by the HTTP methods (typically, GET, POST, PUT, DELETE) to which the resource is responding. The @Produces Annotation  The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client.  If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If applied at the method level, the annotation overrides any @Produces annotations applied at the class level.  If no methods in a resource are able to produce the MIME type in a client request, the JAX-RS runtime sends back an HTTP “406 Not Acceptable” error. Srikanth Technologies Java EE (Web Applications – II) 56 The value of @Produces is an array of String of MIME types. For example: @Produces({"image/jpeg,image/png"}) The following example shows how to apply @Produces at both the class and method levels: 01: @Path("/myResource") 02: @Produces("text/plain") 03: public class SomeResource { 04: @GET 05: public String doGetAsPlainText() { ... } 06: @GET 07: @Produces("text/html") 08: public String doGetAsHtml() { ... } 09: } If a resource class is capable of producing more than one MIME media type, the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically, the Accept header of the HTTP request declares what is most acceptable. For example, if Accept header is Accept: text/plain, the doGetAsPlainText method will be invoked. Alternatively, if Accept header is Accept: text/plain, text/html, which declares that the client can accept media types of text/plain and text/html but prefers the latter, the doGetAsHtml method will be invoked. More than one media type may be declared in the same @Produces declaration. The following code example shows how this is done: @Produces({"application/xml", "application/json"}) public String doGetAsXmlOrJson() { ... } Srikanth Technologies ws.ArrayList. 05: import javax. 07: this. Srikanth Technologies .rs.rs. 08: import javax. 12: } 13: public void setTitle(String title) { 14: this.rs.99)).Path. 18: } 19: public void setPrice(double price) { 20: this. 04: double price. 05: public Book(String title.title = title.util.price = price.PathParam. 09: } 10: public String getTitle() { 11: return title.ws. 06: import javax.util.List.Java EE (Web Applications – II) 57 Restful Web service and JavaScript Client using JQuery The following is a Restful web service that takes department number and returns details of employees in the form of JSON. 09: 10: @Path("/books") 11: public class Books { 12: List<Book> books = new ArrayList<>().ws.rs.MediaType.GET. 03: import java. 01: package rest. 08: this. 21: } 22: } 01: package rest. double price) { 06: super().title = title.add(new Book("C Language For Beginners". 02: public class Book { 03: String title.ws.core. 15: } 16: public double getPrice() { 17: return price.price = price. 02: import java. 13: public Books() { 14: books.ws. 07: import javax.rs. 04: import javax.Produces. 149)).get(id). 30: } 31: } JavaScript Client The following code invokes restful web service and displays the data in the client using JavaScript. BooksClient.add(new Book("Oracle Database 12c 16: for Beginners". 15: return.APPLICATION_JSON) 22: Public List<Book> getFirstBook() { 23: return books. 10: } 11: function displayResult(data) { 12: if (data. 16: } Srikanth Technologies .add( new Book("Java SE Course Material". 17: books.149)).add( new Book("Java EE Course Material".html("").com and include it in this project.149)). 09: {}.html("Sorry! No Books found!"). 24: } 25: @GET 26: @Path("/{id}") 27: @Produces(MediaType. So make sure you download jQuery from jquery.Java EE (Web Applications – II) 58 15: books.length == 0) { 13: $("#error").getJSON("http://localhost:8888/jersey/rest/books".html 01: <html> 02: <head> 03: <title>Books Client </title> 04: <script language="javascript" src="jquery.js"></script> 05: <script language="javascript"> 06: function getBooks() 07: { 08: $. 18: books. 19: } 20: @GET 21: @Produces(MediaType. 14: $("#books").APPLICATION_JSON) 28: public Book getOneBook(@PathParam("id") int id) { 29: return books. displayResult). It uses JQuery to make an Ajax call to web services and process the Json returned by web service. length. i < data. i++) { 21: out += '<li>'+ data[i].price +"</li>". 25: } 26: 27: getBooks().html(""). // get all books as page is loaded 28: </script> 29: </head> 30: <body> 31: <h2>Books List</h2> 32: 33: <ul id="books"></ul> 34: <div style="color:red. 23: } 24: $("#books").html(out). 20: for (var i = 0. 19: var out = ''.' + 22: data[i].font-weight:bold" id="error"></div> 35: </body> 36: </html> Srikanth Technologies .title + ' .Java EE (Web Applications – II) 59 17: 18: $("#error"). which are lightweight container- managed objects (POJOs) with minimal requirements.xml file)  Optionally. such as a faces-config.  A web deployment descriptor (web. which can be used to define page navigation rules and configure beans and other custom objects.xml file. lifecycle callbacks and interceptors. They support a small set of basic services. such as custom components Srikanth Technologies . such as resource injection.Java EE (Web Applications – II) 60 What is JSF?  JavaServer Faces technology is a server-side user interface component framework for Java technology-based web applications  It is a set of UIComponent classes for specifying the state and behavior of UI components  Its rendering model defines how to render the components in various ways  It defines an event and listener model that defines how to handle component events  Its conversion model defines how to register data converters onto a component  Its validation model defines how to register validators onto a component Components of JSF The following are the important components of JSF:  A set of web pages in which components are laid out  A set of tags to add components to the web page  A set of managed beans. one or more application configuration resource files. and many others.2 was release in May.2 (JSR 344) was released in April. Oracle.Java EE (Web Applications – II) 61  Optionally. the final version. 2006. or listeners. JSF 1. BEA Systems. JSF 1. was released on March-2004. a set of custom objects. IBM.  The companies and organizations (other than Sun) involved in developing Faces include the Apache Software Foundation. validators. converters. and handling events  Easy to use  Extensible Component and Rendering architecture  Standard .  Get more information at https://javaserverfaces.java.0.0  Huge vendor and industry support  APIs are layered directly on top of the Servlet API  Provides in-built support for AJAX  Provides template mechanism to reuse components across pages  Integrates Bean validation  Supports HTML 5 using Pass through attributes  Supports Flow through Faces Flow Srikanth Technologies . 2013. created by the application developer  A set of custom tags for representing custom objects on the page JSF Versions  JSF was introduced as Java Specification Request (JSR) 127 by Sun in May 2001.0 (JSR 314) is part of Java EE 6. It offers a clean separation between behaviour and presentation  Provides a rich architecture for managing component state.net Advantages of JSF The following are the important reasons to use JSF:  MVC (Model View Controller) for web applications.0.part of Java EE 7. processing component data.  JSF 2.1 arrived on May. 2004. Macromedia. which can include custom components. and JSF 1. validating user input.  JSF 2.dev. Borland Software.  JSF Reference Implementation (RI) called as Mojarra  Apache MyFaces  JBoss RichFaces Steps in the Development Process Developing a simple JavaServer Faces application usually requires these tasks:  Mapping the FacesServlet instance.FacesServlet 04: </servlet-class> 05: <load-on-startup>1</load-on-startup> 06: </servlet> 07: <servlet-mapping> 08: <servlet-name>Faces Servlet</servlet-name> 09: <url-pattern>/faces/*</url-pattern> 10: </servlet-mapping> Srikanth Technologies . Mapping the FacesServlet Instance  All JavaServer Faces applications must include a mapping to the FacesServlet instance in their deployment descriptors.  Developing the Managed beans.faces.Java EE (Web Applications – II) 62 JSF Implementations JSF is a set of specifications. web. and initializes resources.  Creating the pages using the UI component and core tags. passes them to the life cycle for processing.webapp.  The FacesServlet instance accepts incoming requests.xml 01: <servlet> 02: <servlet-name>Faces Servlet</servlet-name> 03: <servlet-class>javax. Anyone can implement these specifications to provide JSF support. The following are some of the popular implementations of JSF. message}</h3> 26: </h:form> 27: </h:body> 28: </html> Developing Managed Bean  Managed bean is a lightweight container-managed object  It contains properties that are associated with components of the page  The @ManagedBean annotation registers the managed bean as a resource with the JavaServer Faces implementation Srikanth Technologies . Starting from JSF 2.0.w3. perfect.0 Transitional//EN" 03: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.xhtml 01: <!DOCTYPE html PUBLIC 02: "-//W3C//DTD XHTML 1.sun. Facelet is the default presentation language.org/1999/xhtml" 05: xmlns:h="http://java.dtd"> 04: <html xmlns="http://www.com/jsf/html" 06: xmlns:f="http://java.check}" type="submit" /> 24: <p/> 25: <h3>#{perfectBean.com/jsf/core"> 07: <h:head> 08: <title>Perfect Number</title> 09: </h:head> 10: 11: <h:body> 12: <h1>Perfect Number</h1> 13: <h:form id="form1"> 14: Enter a number : 15: <h:inputText id="number" value="#{perfectBean.number}" 16: required="true" 17: requiredMessage="Please enter a number!" 18: validatorMessage="Number must be between 1 and 100"> 19: <f:validateLongRange minimum="1" maximum="100" /> 20: </h:inputText> 21: <h:message id="error" for="number" /> <p/> 22: <h:commandButton value="Submit" 23: actionListener="#{perfectBean.sun.Java EE (Web Applications – II) 63 Creating JSF Pages JSF pages could be either JSPs or XHTML documents called Facelets. RequestScoped. 32: } else { 33: message = "Not a Perfect Number".faces.event. 02: import javax. 19: } 20: public void setNumber(int number) { 21: this.bean. 09: private String message. 05: @ManagedBean 06: @RequestScoped 07: public class PerfectBean { 08: private int number.faces. 04: import javax. 28: } 29: } 30: if (sum == number) { 31: message = "Perfect Number". 22: } 23: public void check(ActionEvent evt) { 24: int sum = 0. 10: public String getMessage() { 11: return message. 15: } 16: 17: public int getNumber() { 18: return number.ManagedBean. 34: } 35: } 36: } Srikanth Technologies . 25: for (int i = 1.faces. i++) { 26: if (number % i == 0) { 27: sum += i. 03: import javax.Java EE (Web Applications – II) 64 PerfectBean.number = number. 12: } 13: public void setMessage(String message) { 14: this.java 01: package beans. i <= number / 2.bean.message = message.ActionEvent. sun. web pages built with XHTML have an .com/jsf/core f Tags for JavaServer Faces custom actions that are independent of any particular render kit Srikanth Technologies .org/jsf/core http://java.sun.2 namespace http://java.sun.com/jsf/facelets http://xmlns.com/jsf/facelets ui Tags for templating http://java.jcp.sun.com/jsp/jstl/core http://xmlns.org/jsf/html http://java.sun.sun.jcp.sun.jcp.jcp.sun.com/jsp/jstl/functions http://xmlns.com/jsf/core http://xmlns. Java EE (Web Applications – II) 65 Facelets  The term Facelets refers to the view declaration language for JSF technology  JSP technology is considered to be a deprecated presentation technology for JavaServer Faces  Facelets is a powerful but lightweight page declaration language that is used to build JSF views using HTML style templates and to build component trees  Use XHTML for creating web pages  Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries  Support for Expression Language (EL)  Provide templating for components and pages  By convention. Facelets uses XML namespace declarations Old namespace JSF 2.org/jsp/jstl/functions URI Prefix Contents http://java.com/jsf/html http://xmlns.jcp.com/jsf/html h JavaServer Faces component tags for all UIComponent objects http://java.org/jsf/facelets http://java.org/jsp/jstl/core http://java.xhtml extension  To support the JavaServer Faces tag library mechanism. id Uniquely identifies the component.sun. Attribute Description binding Identifies a bean property and binds the component instance to it. in the form of a value expression. value Specifies the value of the component.accepts one line of text with no spaces and displays it as a set of asterisks as it is typed Srikanth Technologies . rendered Specifies a condition under which the component should be rendered. style Specifies a Cascading Style Sheet (CSS) style for the tag. indicates that any events. the component is not rendered. styleClass Specifies a CSS class that contains definitions of the styles.com/jsp/jstl/functions fn JSTL 1.com/jsp/jstl/core c JSTL 1. immediate If set to true.2 Core Tags http://java. validations. Tag Function h:inputHidden Allows a page author to include a hidden variable in a page h:inputSecret The standard password field .2 Functions Tags Common attributes for UI components The following attributes are supported by many UI components. Using Text Components The following are the tags related to components that take text from user. If the condition is not satisfied. Java EE (Web Applications – II) 66 http://java. and conversion associated with the component should happen when request parameter values are applied.sun. meaning right- to-left. required Takes a boolean value that indicates whether the user must enter a value in this component. requiredMessage Specifies an error message to display when the user does not enter a value into the component. meaning left-to-right. validator Identifies a method expression pointing to a managed bean method that performs validation on the component’s data.accepts a one-line text string h:inputTextarea The standard text area . Acceptable values are LTR. dir Specifies the direction of the text displayed by this component. Srikanth Technologies . and RTL. label Specifies a name that can be used to identify this component in error messages. converterMessage Specifies an error message to display when the converter registered on the component fails. validatorMessage Specifies an error message to display when the validator registered on the component fails to validate the component’s local value.Java EE (Web Applications – II) 67 h:inputText The standard text field . Attribute Description converter Identifies a converter that will be used to convert the component’s local data.accepts multiple lines of text The following are important attributes of input elements. valueChangeListener Points to a managed bean method that handles the event of entering a value in this component. the logical outcome String is used to determine what page to access when the command component tag is activated.displays a component as a label for a specified input field h:outputLink Displays an <a href> tag that links to another page without generating an action event h:outputText Displays a one-line text string Command Components  The button and hyperlink component tags are used to perform actions. These tags are called command component tags because they perform an action when activated. such as submitting a form.  The h:commandButton tag is rendered as a button. Srikanth Technologies . Attribute Description action Is either a logical outcome String or a method expression pointing to a bean method that returns a logical outcome String. and for navigating to another page. In either case.  The h:commandLink tag is rendered as a hyperlink. actionListener Is a method expression pointing to a bean method that processes an action event fired by the command component tag.Java EE (Web Applications – II) 68 Output Elements The following are output related elements: Element Meaning h:outputFormat Displays a localized message h:outputLabel The standard read-only label . shippingOption}"> 03: <f:selectItem itemValue="1" itemLabel="Train"/> 04: <f:selectItem itemValue="2" itemLabel="Road"/> 05: <f:selectItem itemValue="3" itemLabel="Ship"/> 06: </h:selectOneMenu> Srikanth Technologies . with a scrollable list h:selectOneListbox displayed as a list box. A panel is rendered as a HTML table.columnClasses. whether it is the only value available or one of a set of choices. panelClass. which represents a Boolean state h:selectOneRadio displayed as a set of radio buttons h:selectOneMenu displayed as a drop-down menu. Tag Attributes Function h:panelGrid columns. The most common tags for this kind of component are as follows: Component Description h:selectBooleanCheckbox displayed as a check box.headerClass.Java EE (Web Applications – II) 69 h:panelGrid and h:panelGroup Tags In a JavaServer Faces application. Displays a table footerClass. with an unscrollable list 01: <h:selectOneMenu id="shippingOption" required="true" 02: value="#{cashier. rowClasses h:panelGroup layout Groups a set of components under one parent Components for Selecting One Value Another commonly used component is one that allows a user to select one value. you use a panel as a layout container for a set of other components. newsletterItems}"/> 04: </h:selectManyCheckbox> Conversion Model A JavaServer Faces application can optionally associate a component with server-side object data.Date might be represented as a text string in the format mm/dd/yy or as a set of three text strings. For example.  The presentation view. The JavaServer Faces implementation automatically converts component data between these two views when the bean property associated with the component is of one of the types supported by the component’s data. in which data is represented as data types.Java EE (Web Applications – II) 70 Components for Selecting Multiple Values In some cases. you need to allow your users to select multiple values rather than just one value from a list of choices. This object is a JavaBeans component. a java. You can do this using one of the following component tags: Tag Description h:selectManyCheckbox Displayed as a set of check boxes h:selectManyMenu Displayed as a drop-down menu h:selectManyListbox Displayed as a list box 01: <h:selectManyCheckbox id="newslettercheckbox" 02: value="#{cashier. in which data is represented in a manner that can be read or modified by the user. When a component is bound to an object.newsletters}"> 03: <f:selectItems value="#{cashier. An application gets and sets the object data for a component by calling the appropriate object properties for that component. such as int or long. the application has two views of the component’s data:  The model view.util. Srikanth Technologies . such as a backing bean. pattern (DecimalFormat). h:commandButton with logout or cancel operation.date. locale. dateStyle. short.number. long.  Define bean properties to be simple standard types – int. timeStyle - default. timeZone Validation Model JavaServer Faces technology supports a mechanism for validating the local data of editable components (such as text fields). medium. For ex. The following tags are used to specify explicit conversion. percentage f:convertDateTime type .lang.groupingUsed. max(min)FractionDigits. full. pattern (SimpleDateFormat).Java EE (Web Applications – II) 71 Some component data must be bound to properties of a particular type. For example.Boolean. form is redisplayed and error message is stored  You can also add required attribute to any input element to indicate that empty values are errors  Use <h:message> to display error messages. locale.. integerOnly. double. Srikanth Technologies . Tag Attributes f:convertNumber currencyCode. long. type . max(min)IntegerDigits. both.  System attempts to convert automatically to required type  If there is conversion error. a UISelectBoolean component must be bound to a property of type boolean or java. It returns empty string if there is no message  Add immediate attribute to bypass validation. This validation occurs before the corresponding model data is updated to match the local value. time. currencySymbol . char etc. currency. boolean. validateRequired Ensures that the local value is not empty on an EditableValueHolder component. the validator’s error message will display on the page. validateRegEx Checks whether the local value pattern of a component is a match against a regular expression from the java. validateLongRange Checks whether the local value minimum. If you have registered one of these validators onto a component on your page. of a component is within a maximum certain range. Srikanth Technologies . The value must be floating-point or convertible to floating-point. of a component is within a maximum certain range. and the validator is unable to validate the component’s value.util.Java EE (Web Applications – II) 72 Tag Function Attributes validateBean Registers a bean validator for validationGroups the component. Each of these validators has one or more standard error messages associated with it. component’s local value is maximum within a certain range. validateLength Checks whether the length of a minimum. The value must be a String.regex package. The value must be any numeric type or String that can be converted to a long. validateDoubleRange Checks whether the local value minimum. 01: package beans. the {1} substitution parameter is replaced by the component’s label or id. the error message that is displayed when the component’s value exceeds the maximum value allowed by LongRangeValidator is as follows: {1}: Validation Error: Value is greater than allowable maximum of "{0}" In this case.max=10. 25: } 26: public void setMessage(String message) { Srikanth Technologies .uname = uname.Java EE (Web Applications – II) 73 For example. 08: @Size(min=4. 04: 05: @ManagedBean 06: public class User { 07: private String uname. 03: import javax. Integrating Bean Validation and JSF The following example shows how to integrate Bean Validation with JSF.password. message.message="Username must be 09: 4 to 10 chars") 10: public String getUname() { 11: return uname. message="Password is required!") 17: public String getPassword() { 18: return password.password = password. 22: } 23: public String getMessage() { 24: return message.ManagedBean. and the {0} substitution parameter is replaced with the maximum value allowed by the validator.constraints. 19: } 20: public void setPassword(String password) { 21: this. 12: } 13: public void setUname(String uname) { 14: this.bean.Size. 15: } 16: @Size ( min=1. 02: import javax.validation.faces. message}</h3> 29: </h:form> 30: </h:body> 31: </html> Srikanth Technologies .org/jsf/core"> 08: <h:head> 09: <title>Login</title> 10: </h:head> 11: <h:body> 12: <h:form> 13: <h2>Login</h2> 14: Username <br/> 15: <h:inputText id="uname" value="#{user.0 Transitional//EN" 04: "http://www.org/1999/xhtml" 06: xmlns:h="http://xmlns.jcp.org/TR/xhtml1/DTD/xhtml1-transitional.equals("admin") && password.uname}"> 16: <f:validateBean /> 17: </h:inputText> 18: <h:message for="uname" /> 19: <p/> 20: Password <br/> 21: <h:inputSecret id="password" value="#{user. 34: return "login".login}" value="Login"/> 27: <p/> 28: <h3>#{user.0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1. 35: } 36: } 37: } login.w3. 28: } 29: public String login() { 30: if ( uname.dtd"> 05: <html xmlns="http://www.org/jsf/html" 07: xmlns:f="http://xmlns.Java EE (Web Applications – II) 74 27: this.xhtml 01: <?xml version='1.password}"> 22: <f:validateBean /> 23: </h:inputSecret> 24: <h:message for="password" /> 25: <p/> 26: <h:commandButton action="#{user. 32: else { 33: message = "Sorry! Invalid Login!".w3.message = message.jcp.equals("admin")) 31: return "home". xhtml</to-view-id> 06: </navigation-case> 07: <navigation-case> 08: <from-outcome>failure</from-outcome> 09: <to-view-id>/loginfail. If a view matching the action outcome is found.Java EE (Web Applications – II) 75 Navigation  Navigation in JSF may be either implicit or explicit.xhtml</to-view-id> 10: </navigation-case> 11: </navigation-rule> Srikanth Technologies . 01: <navigation-rule> 02: <from-view-id>/login. 01: @ManagedBean(name="registerBean") 02: public class RegisterBean { 03: private String email.xml.  JSF 2. // calls failure.  Explicit navigation is specified using elements in faces- config. message.xhtml 09: } 10: } Here is an example for explicit navigation using faces-config. phone. the navigation handler checks to see whether the action outcome corresponds to a view id.xml. // calls success. 04: public String register() { 05: if (done) 06: return "success".0 introduced simple navigation defaults that reduce navigation-related process.  If no matching navigation case is found after checking all available rules.xhtml</from-view-id> 03: <navigation-case> 04: <from-outcome>success</from-outcome> 05: <to-view-id>/home.xhtml 07: else 08: return "failure". an implicit navigation to the matching view occurs. PersonBean.xhtml 01:<?xml version='1.Java EE (Web Applications – II) 76 Pass-through Attributes  JSF 2.org/jsf/passthrough and associate attributes with this namespace to pass them to client.RequestScoped.org/1999/xhtml" 06: xmlns:h="http://xmlns.  Pass-through attributes make it possible to render HTML5 attributes (or any other attributes) which are not natively supported by the component.  Define a namespace http://xmlns.faces.context.org/jsf/passthrough"> 09: <h:head> 10: <title>Pass-through Attributes</title> 11: </h:head> 12: <h:body> 13: <h:form> 14: <h2>User Registration</h2> 15: FullName : 16: <h:inputText value="#{personBean.jcp. 02: import javax. 03: import javax. 08: private int age.ManagedBean.dtd"> 05: <html xmlns="http://www. 04: @ManagedBean 05: @RequestScoped 06: public class PersonBean { 07: private String name.mobile.jcp.bean.0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1.w3.2 introduces the so-called pass-through attributes to support new and modified attributes defined in HTML5.name}" 17: p:placeholder="Fullname" p:required="required"/> 18: <p/> Srikanth Technologies .w3.enterprise. 10: // getter and setter methods 11: } Person. email.org/jsf/html" 07: xmlns:f="http://xmlns.java 01: package beans.org/jsf/core" 08: xmlns:p="http://xmlns.jcp.0 Transitional//EN" 04: "http://www.org/TR/xhtml1/DTD/xhtml1-transitional. 09: private String message.jcp. clicking on the button etc. 01: <h:inputText id="email" value="#{bean.  Events on the client such as user selecting an option in drop- down listbox. Object> with f:passThroughAttributes.. can be associated with methods that run on the server.  So events on the client are handled on the server.age}"> 29: <f:passThroughAttribute name="min" value="10"/> 30: <f:passThroughAttribute name="type" value="range"/> 31: </h:inputText> <p/> 32: <h:commandButton value="Submit" /> 33: </h:form> 34: </h:body> 35: </html> There is one more! You can also add pass-through attributes coming from a managed bean property of type Map<String. Action controllers  Handle main form submission  Fire after bean has been populated  Fire after validation logic  Return strings that directly affect page navigation Srikanth Technologies .mobile}" 25: title="10 digits mobile number" 26: p:pattern="^[0-9]{10}$" p:required="required" /><p/> 27: Age : 28: <h:inputText value="#{personBean.Java EE (Web Applications – II) 77 19: Email : 20: <h:inputText value="#{personBean.email}"> 02: <f:passThroughAttributes value="#{bean.attributes}"/> 03: </h:inputText> Event and Listener Model  One of the key advantages of JSF is its support for events.email}" 21: p:placeholder="Email Address" 22: p:required="required" p:type="email" /> <p/> 23: Mobile : 24: <h:inputText value="#{personBean. An example is selecting a check box. an action that results in the component’s value changing to true. checkbox. textfield etc.  Occurs before bean properties are populated  Can register a ValueChangeListener implementation on a component that implements EditableValueHolder by nesting an f:valueChangeListener tag within the component’s tag on the page  ValueChangeListener is attached to combobox. so we need to add JavaScript to submit the form using onclick="submit()" or onchange="submit()"  Takes a ValueChangeEvent as an argument  Useful ValueChangeEvent methods  getComponent  getOldValue (previous value)  getNewValue (current value)  Value for checkbox is of type Boolean Srikanth Technologies . These components include buttons and hyperlinks. radiobutton.Java EE (Web Applications – II) 78  An action event occurs when the user activates a component that implements ActionSource. listbox.  Form is not automatically submitted. String actionControllerMethod() { } ActionListener  We can register an ActionListener implementation on a command component by nesting an f:actionListener tag within the component’s tag on the page  Supports both the type and binding attributes void actionListenerMethod(ActionEvent evt) { } ValueChangeListener  A value-change event occurs when the user changes the value of a component represented by UIInput or one of its subclasses. w3.org/1999/xhtml" 02: xmlns:h="http://java.calculatePrice}" 26: onchange="submit()"> 27: <f:selectItem itemLabel="Thinking in Java" 28: itemValue="500"/> 29: <f:selectItem itemLabel="JSF In Action" 30: itemValue="450"/> 31: <f:selectItem itemLabel="Struts 2 In Action" 32: itemValue="550"/> 33: </h:selectOneMenu> 34: 35: <h:selectOneMenu id="dotnetbooks" 36: valueChangeListener= Srikanth Technologies .category}" 12: valueChangeListener="#{booksBean.net" /> 17: </h:selectOneRadio> 18: </td> 19: </tr> 20: <tr> 21: <td>Select A Book : </td> 22: <td><h:selectOneMenu id="javabooks" 23: rendered='#{booksBean.com/jsf/html" 03: xmlns:f="http://java.Java EE (Web Applications – II) 79  Value for radiobutton or TextField corresponds to request parameter void valueChangeListenerMethod(ValueChangeEvent evt) { } books.xhtml 01: <html xmlns="http://www.process}"> 13: <f:selectItem itemLabel="Java Books" 14: itemValue="java" /> 15: <f:selectItem itemLabel="MS.Net Books" 16: itemValue=".category == "java"}' 24: valueChangeListener= 25: "#{booksBean.sun.sun.com/jsf/core"> 04: <h:head> <title>Books</title></h:head> 05: <h:body> 06: <h:form id="form1"> 07: <h2>Books Catalog </h2> 08: <table cellpadding="5px"> 09: <tr><td>Select Category :</td> 10: <td><h:selectOneRadio onclick="submit()" 11: id="category" value="#{booksBean. bean. 05: 06: @ManagedBean 07: @SessionScoped 08: public class BooksBean { 09: private String category = "java".bean.price}" /> </td> 54: </tr> 55: </table> 56: </h:form> 57: </h:body> 58: </html> BooksBean.0" 43: itemValue="700"/> 44: <f:selectItem itemLabel="LINQ in Action" 45: itemValue="500"/> 46: </h:selectOneMenu> 47: </td> 48: </tr> 49: <tr style="text-align: center.faces.event.price != ""}' 53: value="Price : #{booksBean.java 01: package beans. 04: import javax. 12: } 13: public void setCategory(String category) { 14: this.NET 4. 18: } 19: public void setPrice(String price) { Srikanth Technologies .SessionScoped.ManagedBean.font-weight:700"> 50: <td colspan="2"> 51: <h:outputText 52: rendered='#{booksBean.faces. 10: public String getCategory() { 11: return category. 02: import javax.faces. price ="".calculatePrice}" 38: onchange="submit()" 39: rendered='#{booksBean.category==".Java EE (Web Applications – II) 80 37: "#{booksBean. 03: import javax.category = category.net"}'> 40: <f:selectItem itemLabel="C# Comp Ref." 41: itemValue="400"/> 42: <f:selectItem itemLabel="ASP. 15: } 16: public String getPrice() { 17: return price.ValueChangeEvent. and the server responds with the page translated to HTML.  When the life cycle handles an initial request. Conversely. JSF page life cycle is split up into multiple phases in order to support the sophisticated UI component model. validations.Java EE (Web Applications – II) 81 20: this.toString(). which requires component data to be converted and validated. 21: } 22: public void process(ValueChangeEvent e) { 23: category = e. component events to be handled. 25: } 26: public void calculatePrice(ValueChangeEvent e) { 27: price = e.  However. he or she is requesting the page for the first time. When a user makes an initial request for a page. and model updates. when the life cycle handles a postback. it executes all of the phases. it only executes the restore view and renders response phases because there is no user input or action to process. 24: price = "". Srikanth Technologies . 28: } 29: } Life Cycle of JSF page  The life cycle of a JavaServer Faces page is somewhat similar to that of a JSP page: The client makes a HTTP request for the page.toString().  JSF implementation handles the request and automatically goes through the phases in the lifecycle to perform any necessary conversions. and to generate the response. and component data to be propagated to beans in an orderly fashion. Postback  The life cycle handles both kinds of requests: initial request and postback. Initial request vs.getNewValue(). he or she submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request.price = price. When a user executes a postback.getNewValue(). JSF builds the view of the Faces page and wires the event handlers and validators to the components. which is determined by the name of the JSF page. Srikanth Technologies . If the view already exists. Restore View  A view represents all the components of the page. Invoke Application Calls registered listeners. Apply Request Updates the value of local components to Values equal ones sent in the request. In this case. JSF advances directly to the render response phase. the view corresponding to the page already exists.  In the case of an initial view (the first time a page is loaded). so it only needs to be restored.  FacesServlet examines the request and extracts the view ID.  The JSF framework controller uses the view ID to look up the components for the current view. the JSF controller creates it.Java EE (Web Applications – II) 82 Lifecycle Phase Description Restore View Finds or creates a tree of components for the request. Update Model Updates properties in Managed bean with Values values of components. the JSF controller uses it. JSF uses the existing view's state information to reconstruct its state.  In the case of a new view. The view is saved in a FacesContext object. From an initial view. JSF creates an empty view.  In the case of a postback. Process Validations Asks each component to validate itself. The empty view is populated as the JSF page is processed. Render Response Displays the selected view using rendering technology. If the view doesn't already exist. Java EE (Web Applications – II) 83 Srikanth Technologies . Java EE (Web Applications – II) 84 Apply Request Values  Components take values from request parameters and decode them. Process Validations  Conversion and validation normally happen in this phase.  At the end of this phase. along with any other validation errors.  Only the properties pointed at by an input component’s value attribute are updated. the JavaServer Faces implementation adds an error message to the FacesContext instance.  If the value conversion or value validation fails.  If the local value is invalid. then the validation. and events associated with these components will be processed during this phase. component generates value-change event. an error message is generated and queued in the FacesContext.  If local value changes. the components are set to their new values. Srikanth Technologies . where it will be displayed during the render response phase. Invoke Application  JSF broadcasts events for this phase to any registered listeners. Update Model Values  It can walk the component tree and set the corresponding bean properties to the component’s local values.  JSF sends action listener to any registered action listeners of the component. and the life cycle advances directly to the render response phase so that the page is rendered again with the error messages displayed. conversion.  If some components on the page have their immediate attributes set to true.  Output messages using normal expression language constructs - #{variable.title}</h2> 16: </f:view> 17: </h:body> 18: </html> Srikanth Technologies .0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1. Working with Properties Files and Internationalization Take the following steps to use properties files that contain messages related to web application:  Create a .org/jsf/core" 07: xmlns:h="http://xmlns.request.w3.0 Transitional//EN" 04: "http://www.jcp.  Saves the state of the view so that it can be restored.properties file in/under WEB-INF/classes.xhtml 01: <?xml version='1.jcp.Java EE (Web Applications – II) 85 Render Response  Component values are updated from bean properties.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 05: <html xmlns="http://www.locale}"> 14: <f:loadBundle basename="messages" var="msgs"/> 15: <h2>#{msgs.keyName} i18ndemo. It contains simple keyName=value pairs.w3.  Values are converted to string for display purpose.  Load file with f:loadBundle – basename gives base file name and var gives scoped variable (Map) that will hold results.org/jsf/html"> 08: <h:head> 09: <title>Internationalisation Demo</title> 10: </h:head> 11: <h:body> 12: <f:view 13: locale="#{facesContext.  Sends response back to user.org/1999/xhtml" 06: xmlns:f="http://xmlns.externalContext. These parts include headers.faces.ResultSet object  A javax. the styles are applied to the columns or rows in the order that the styles are listed in the attribute  The attribute value could be any of the following:  A list of beans  An array of beans  A single bean  A javax. starting with the first row. you would set first to 2 and rows to 9  If columnClasses or rowClasses specify more than one style.properties title=srikanth Tecnologías Using <h:dataTable> component  You provide one row definition for dataTable and JSF repeats for each row from the data source  Each entry in the data source contains data corresponding to a table row  Turns a collection into a HTML table  Each column is defined using <h:column> component  Element <f:facet> is used for header and footer  To display a subset of the data.model.sql.Java EE (Web Applications – II) 86 /WEB-INF/classes/messages.servlet.Result object Srikanth Technologies .jstl. to be displayed.jsp. you use the optional first and rows attributes  The h:dataTable and h:column tags use facets to represent parts of the table that are not repeated or updated.properties title=Srikanth Technologies /WEB-INF/classes/messages_es. if you wanted to display records 2 through 10 of the underlying data. The rows attribute specifies the number of rows. so an h:panelGroup tag is needed if you want to group more than one component within an f:facet  The first attribute specifies the first row to be displayed.DataModel object  A java. footers. and captions  Facets can have only one child. For example.sql. font-size:14pt. 10: font-family:verdana.background-color:blue.colhead {color:white. 08: font-family:arial.w3.background-color:gray. 12: font-family:arial.background-color:red.oddrow { background-color:silver} 14: .rightjustify {text-align:right} 17: .head{color:white. font-size:12pt.font-weight:700} 09: .RowSet object  Attribute var contains each element of the collection.Java EE (Web Applications – II) 87  A javax.leftjustify {text-align:left} 18: </style> 19: </h:head> 20: <h:body> 21: <h:form> 22: <h:dataTable value="#{jobsBean. font-size:20pt. Attribute Defines Styles for captionClass Table caption columnClasses All the columns footerClass Footer headerClass Header rowClasses Rows styleClass The entire table The following example retrieves data from JOBS table of Oracle database and displays as a HTML table using <h:dataTable> and <h:column> elements.com/jsf/core"> 04: <h:head> 05: <title>Jobs</title> 06: <style> 07: .rows { font-family:verdana} 16: .sql.com/jsf/html" 03: xmlns:f="http://java.jobs}" var="job" border="1" 23: footerClass="foot" captionClass="head" Srikanth Technologies . Properties of object can be accessed using JSF expression language.font-weight:700} 13: .font-weight:700} 11: .evenrow { background-color:white} 15: .org/1999/xhtml" 02: xmlns:h="http://java.sun.sun. 01: <html xmlns="http://www.foot { color:white. 13: } 14: public RowSet getJobs() { 15: try { 16: CachedRowSet rs = new OracleCachedRowSet().faces.rightjustify" 25: styleClass="rows" headerClass="colhead" 26: rowClasses="evenrow.faces. 06: import oracle.bean. Srikanth Technologies .rowset. 05: import javax.OracleCachedRowSet.sql. 04: import javax.RequestScoped.count} 43: </center> 44: </f:facet> 45: </h:dataTable> 46: </h:form> 47: </h:body> 48: </html> JobsBean. 07: @ManagedBean 08: @RequestScoped 09: public class JobsBean { 10: private int count.java 01: package beans. 11: public int getCount() { 12: return count.min_salary} 34: </h:column> 35: <h:column> 36: <f:facet name="header">Max Salary</f:facet> 37: #{job.rowset. 03: import javax.oddrow"> 27: <h:column> 28: <f:facet name="header">Job Title</f:facet> 29: #{job.job_title} 30: </h:column> 31: <h:column> 32: <f:facet name="header">Min Salary</f:facet> 33: #{job.CachedRowSet.bean.max_salary} 38: </h:column> 39: 40: <f:facet name="caption" class="head">Jobs List</f:facet> 41: <f:facet name="footer" class="foot"> 42: <center> Total Number of Jobs : #{jobsBean. 02: import javax.sql.ManagedBean.jdbc.Java EE (Web Applications – II) 88 24: columnClasses="leftjustify.RowSet.rightjustify. and step Srikanth Technologies .sql. size.getMessage()).setUrl("jdbc:oracle:thin:@localhost:1521:XE"). value The name of a collection of items that this tag iterates over. end.last(). 24: count = rs.setCommand("select * from jobs"). 25: rs. 21: rs.ResultSet. java.beforeFirst().println(ex. If the collection is null.execute().setUsername("hr"). The collection may be a List. 29: return null. 22: // count number of rows 23: rs. this tag does nothing. 26: return rs. or an individual java Object.setPassword("hr").Java EE (Web Applications – II) 89 17: rs.out. array. 30: } 31: } 32: } <ui:repeat>  Allows you to display the given content repeatedly for each item in the collection  Output is not confined to HTML table as in the case of <h:dataTable> 01: <ui:repeat var="var" value="collection"> 02: Content 03: </ui:repeat> Attribute Meaning var String giving the local variable name that will refer to each element in the collection.getRow(). varStatus String giving a variable name that will refer to status object. This has the following properties : begin. 19: rs. 27: } catch (Exception ex) { 28: System. 18: rs. step : values of offset. 20: rs. 11: } 12: public void setAge(int age) { 13: this.the current index (int) first/last.java 01: package beans. step Specifies how far to jump down the collection after each item.Java EE (Web Applications – II) 90 attributes index.name. 01: <ul> 02: <ui:repeat value="#{personsBean.name = name. Default is the end of the collection.persons}" var="person" 03: offset="2" size="4"> 04: <li> 05: #{person.age = age. int age) { 06: this. Default 0. 02: public class Person { 03: private String name. 07: this.is this the first/last iteration? (boolean) even/odd. 14: } 15: public String getName() { 16: return name. Default is 1. 05: public Person(String name. Srikanth Technologies .age} 06: #{person.length() > 15}"> 08: Big Name 09: </ui:fragment> 10: </li> 11: </ui:repeat> 12: </ul> Person.age = age.name} : #{person. size Specifies how far down the collection to go.age lt 30 ? "Young" : "Middle Aged"} 07: <ui:fragment rendered ="#{person. 08: } 09: public int getAge() { 10: return age.is this even/odd iteration? (boolean) (1st iteration is 0: even) offset Specifies how far into the collection to start. 04: private int age. Scott Mitchell".38)). If this tag is nested within a single component. 09: persons. 05: @ManagedBean 06: public class PersonsBean { 07: public List<Person> getPersons() { 08: ArrayList<Person> persons = new ArrayList().0 supports integrated Ajax using <f:ajax> tag.java 01: package beans. it will associate an Ajax action with that component. the default event is determined for the component. 20: } 21: } PersonsBean.add( new Person("Mr. The default event is Srikanth Technologies . 12: persons. If not specified.32)).faces.add( new Person("Mr.Joe Stagner".42)). 14: } 15: } AJAX Support using <f:ajax>  JSF 2. 13: return persons.add( new Person("Mr. If this tag is placed around a group of components it will associate an Ajax action with all components that support the event attribute. 04: import javax.Java EE (Web Applications – II) 91 17: } 18: public void setName(String name) { 19: this.  The presence of the <f:ajax> tag triggers the Ajax request. it must be one of the events supported by the component the Ajax behavior is being applied to. If specified.List.41)). 11: persons.John Resig". Attribute Description event A String identifying the type of event the Ajax action will apply to.  This tag serves two roles depending on its placement.bean.ManagedBean. 10: persons.ArrayList.add( new Person("Mr. 02: import java.name = name. 03: import java.  This allows Ajax requests to be issued without requiring the page author to write any JavaScript code.util.util.Rod Johnson". listener The name of the listener method that is called when an AjaxBehaviorEvent has been broadcast for the listener.Java EE (Web Applications – II) 92 “action” for ActionSource components and “valueChange” for EditableValueHolder components. then @none is the default.The enclosing form If not specified. If a ValueExpression is specified. render A Collection that identifies a list of components to be rendered on the client. execute If a literal is specified. 01: <h:commandButton id="submit" value="Submit"> 02: <f:ajax event="click" /> 03: </h:commandButton> Using the listener Attribute  The listener attribute refers to a method expression that is executed on the server side in response to an Ajax action on the client. it must refer to a property that returns a Collection of Strings.No identifiers @this .All component identifiers @none . It has the same options as execute attribute. Srikanth Technologies . If not specified.The element that triggered the request @form . then @this is the default. it must be a space delimited String of component identifiers and/or one of the keywords given below. onevent The name of a JavaScript function that will handle events. @all . If a ValueExpression is specified. onerror The name of a JavaScript function that will handle errors. it must refer to a property that returns a Collection of Strings. org/1999/xhtml" 03: xmlns:h="http://java.name}" /> 11: <p/> 12: <h:commandButton actionListener="#{directoryBean.sun.0' encoding='UTF-8' ?> 02: <html xmlns="http://www.email}" id="email"/> 20: </h:form> 21: </h:body> 22: </html> Srikanth Technologies .w3.sun.search}" 13: value="Search"> 14: <f:ajax execute="name" render="phone email"/> 15: </h:commandButton> 16: <p/> 17: <h:outputText value="#{directoryBean.phone}" id="phone"/> 18: <p/> 19: <h:outputText value="#{directoryBean.Java EE (Web Applications – II) 93  The listener's processAjaxBehavior method is called once during the Invoke Application phase of the lifecycle.com/jsf/html" 04: xmlns:f="http://java.someaction}" render="somecomponent" /> The following code represents the someaction method in mybean. <f:ajax listener="#{mybean. 03: } phonedirectory.xhtml 01: <?xml version='1.com/jsf/core" > 05: <h:head></h:head> 06: <h:body> 07: <h:form id="directoryForm"> 08: <h2>Search Phone Directory</h2> 09: Enter person name : 10: <h:inputText id="name" value="#{directoryBean. 01: public void someaction(AjaxBehaviorEvent event) { 02: dosomething. 15: } 16: public String getName() { return name."9000099999:resig@yahoo. 23: } 24: public void search(ActionEvent evt) { 25: String details = directory.bean. 02: import javax. 34: } 35: } 36: public String getEmail() { 37: return email.faces.ManagedBean. 32: phone = parts[0].event.split(":"). 03: import javax.phone = phone.RequestScoped.ActionEvent.} 21: public void setPhone(String phone) { 22: this.put("Resig". 04: import javax.faces.phone.Java EE (Web Applications – II) 94 DirectoryBean. 41: } 42: } Srikanth Technologies .java 01: import java.com"). "9000011111:[email protected]. } 17: public void setName(String name) { 18: this. 11: private String name. 05: 06: @ManagedBean(name="directoryBean") 07: @RequestScoped 08: public class DirectoryBean { 09: private TreeMap<String. 29: } 30: else { 31: String parts[] = details.faces. 28: email = "". 12: public DirectoryBean() { 13: directory. 26: if ( details == null) { 27: phone = "Sorry! Name not found".String>(). 19: } 20: public String getPhone() { return phone. email.String>directory 10: = new TreeMap<String.email = email.name = name.TreeMap.get(name). 14: directory. 33: email = parts[1].put("John".com"). 38: } 39: public void setEmail(String email) { 40: this.bean. sun. usually referred to as client pages.com/jsf/facelets"> 08: <h:head> Srikanth Technologies . you can reuse code and avoid recreating similarly constructed pages.dtd"> 05: <html xmlns="http://www. Content outside this tag is ignored.  A template page is used as a template for other pages. template. Tag Function ui:component Defines a component that is created and added to the component tree. ui:define Defines content that is inserted into a page by a template. ui:param Used to pass parameters to an included file.com/jsf/html" 07: xmlns:ui="http://java. such as c:forEach or h:dataTable. ui:insert Inserts content into a template. ui:include Encapsulates and reuses content for multiple pages. ui:remove Removes content from a page.w3.  Templates in JSF are similar to Tiles in Struts. ui:fragment Similar to the component tag but does not disregard content outside this tag.org/TR/xhtml1/DTD/xhtml1-transitional.  By using templates. for the other pages in an application. Templating also helps in maintaining a standard look and feel in an application with a large number of pages.w3.Java EE (Web Applications – II) 95 Templates  JSF provides the tools to implement user interfaces that are easy to extend and reuse.0 Transitional//EN" 04: "http://www.org/1999/xhtml" 06: xmlns:h="http://java.sun. Templating is a useful Facelets feature that allows you to create a page that will act as the base.xhtml 01: <?xml version='1. ui:repeat Used as an alternative for loop tags. or template. ui:composition Defines a page composition that optionally uses a template.0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1. sun. 17: <a href="second.head {background-color:yellow.css"/> 11: </h:head> 12: <h:body> 13: <ui:include src="header.Java EE (Web Applications – II) 96 09: <title><ui:insert name="title">Title</ui:insert></title> 10: <h:outputStylesheet library="css" name="default.com/jsf/facelets" 03: template="/template.} 02: .html <h1>Templates Demo</h1> first. 04: font-weight:700.main { background-color:red.} 06: body {background-color: silver.xhtml">First Page </a> 16: &nbsp.w3.xhtml">Second Page </a> 18: </div> 19: <div class="main"> 20: <div class="title"> 21: <ui:insert name="title"></ui:insert> 22: </div> 23: <ui:insert name="body">Content Page</ui:insert> 24: </div> 25: </h:body> 26: </html> WEB-CONTENT/resources/css/default.xhtml"> 04: <ui:define name="title">First Page</ui:define> 05: <ui:define name="body"> 06: First Page Content! 07: </ui:define> 08: </ui:composition> Srikanth Technologies .&nbsp.org/1999/xhtml" 02: xmlns:ui="http://java.} Header.} 05: .} 03: .font-size:20pt.font-weight:700.xhtml 01: <ui:composition xmlns="http://www.html"></ui:include> 14: <div class="links"> 15: <a href="first.links{ background-color:white.css 01: .title{font-size:16pt. org/jsf/html"> 09: <h:head> 10: <title>Word Count</title> 11: </h:head> 12: <h:body> 13: <h2>Word Count</h2> 14: <h:form enctype="multipart/form-data"> 15: Select File : 16: <h:inputFile id="file" value="#{fileBean.com/jsf/facelets" 03: template="/template.Java EE (Web Applications – II) 97 second.sun.org/1999/xhtml" 02: xmlns:ui="http://java.xhtml"> 04: <ui:define name="title">Second Page</ui:define> 05: <ui:define name="body"> Second Page Content!</ui:define> 06: </ui:composition> Uploading File with inputFile element  The <h:inputFile> is used to upload a file from client to server.  The upload is stored in a bean property of type javax.count}" /> 24: </c:if> 25: </h:form> 26: </h:body> Srikanth Technologies .dtd"> 05: <html xmlns="http://www.servlet. of words in the document are : 23: <h:outputText value="#{fileBean.org/jsf/core" 08: xmlns:h="http://xmlns.w3.  The form submit encoding must be set to multipart/form- data in the enctype attribute of the enclosing h:form.w3.sun.Part referenced in the value attribute.file}"/> 17: <p/> 18: <h:commandButton value="Upload" 19: actionListener="#{fileBean.w3.0 Transitional//EN" 04: "http://www.org/TR/xhtml1/DTD/xhtml1-transitional. countwords.xhtml 01: <ui:composition xmlns="http://www.jcp.http.0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1.com/jsp/jstl/core" 07: xmlns:f="http://xmlns.upload}" /> 20: <p/> 21: <c:if test="#{fileBean.jcp.org/1999/xhtml" 06: xmlns:c="http://java.xhtml 01: <?xml version='1.count gt 0}"> 22: No. Java EE (Web Applications – II) 98 27: </html> FileBean.println("Error -->" + ex. 37: } catch (Exception ex) { 38: System.count = count.faces.getMessage()).readLine().* 04: import javax.http.ActionEvent. 34: line = br. 03: import javax. 12: public Part getFile() { 13: return file.faces. 29: String line = br.getInputStream())).readLine(). 14: } 15: public void setFile(Part file) { 16: this.split("[^A-Za-z0-9-]+"). 31: while (line != null) { 32: String words[] = line.out. 02: import java.bean. 17: } 18: public int getCount() { 19: return count.file = file.java 01: package beans.servlet.close(). 39: } 40: } Srikanth Technologies .event. 30: count = 0. 05: import javax.Part. 33: count += words. 06: 07: @ManagedBean 08: @RequestScoped 09: public class FileBean { 10: private Part file.*. 35: } 36: br. 23: } 24: public void upload(ActionEvent evt) { 25: // read the contents of the file and count number of words 26: try { 27: BufferedReader br = new BufferedReader( 28: new InputStreamReader(file.length.io. 20: } 21: public void setCount(int count) { 22: this. 11: private int count. This allows the view action to be incorporated into the JavaServer Faces lifecycle on both non- faces (initial) and faces (postback) requests. 18: } 19: public void setName(String name) { 20: this. the viewAction component supports declarative navigation as well. 10: public String getMessage() { 11: return message. So you can write a navigation rule that is consulted before the page is rendered. 05: 06: @ManagedBean 07: @RequestScoped 08: public class WishBean { 09: private String name.util. 03: import javax. 15: } 16: public String getName() { 17: return name. WishBean.  A view action operates like a button command (UICommand) component. 02: import java.context.  By default.java 01: package beans. 12: } 13: public void setMessage(String message) { 14: this.Calendar.bean.faces. 21: } 22: public String wish() { Srikanth Technologies .  Like other UICommand components. message.name = name. 04: import javax. it is executed during the Invoke Application phase in response to an initial request.RequestScoped.2 extends GET processing further by allowing you to take action using viewAction component.enterprise.  The viewAction component is declared as a child of the metadata facet (<f:metadata>).Java EE (Web Applications – II) 99 41: } The <viewAction> and <viewParam> components  JSF 2.ManagedBean.message = message. wish}" /> 12: </f:metadata> 13: <h:head> 14: <title>ViewAction Demo</title> 15: </h:head> 16: <h:body> 17: <h2> #{wishBean.com/jsf/html" 07: xmlns:f="http://java.xhtml 01: <?xml version='1.com/jsf/core"> 08: <f:view> 09: <f:metadata> 10: <f:viewParam name="name" value="#{wishBean. 32: } 33: return null.w3. 28: } else if (hour < 17) { 29: message += "Good Afternoon".0' encoding='UTF-8' ?> 02: <!DOCTYPE html PUBLIC 03: "-//W3C//DTD XHTML 1.sun. 24: int hour = c.get(Calendar.getInstance().HOUR_OF_DAY). 26: if (hour < 12) { 27: message += "Good Morning".name}"/> 11: <f:viewAction action="#{wishBean.0 Transitional//EN" 04: http://www.dtd"> 05: <html xmlns="http://www.org/TR/xhtml1/DTD/xhtml1-transitional. ".sun.org/1999/xhtml" 06: xmlns:h="http://java. 30: } else { 31: message += "Good Evening".Java EE (Web Applications – II) 100 23: Calendar c = Calendar. 25: message = name + ". 34: } 35: } wish.message} </h2> 18: </h:body> 19: </f:view> 20: </html> Srikanth Technologies .w3. first_name} 19: </h:column> 20: <h:column> 21: <f:facet name="header">Salary</f:facet> 22: #{employee.xhtml 01: <html xmlns="http://www.jobs}"/> 11: </h:selectOneMenu> 12: <p/> 13: <h:dataTable rendered='#{employeeBean.sun.job != null}' 14: value="#{employeeBean.job}" 09: onchange="submit()"> 10: <f:selectItems value="#{employeeBean.sun.hire_date} 27: </h:column> 28: </h:dataTable> 29: </h:form> 30: </f:view> 31: </h:body> 32: </html> Srikanth Technologies .employees}" 15: var="employee" border="1"> 16: <h:column> 17: <f:facet name="header">First Name</f:facet> 18: #{employee.org/1999/xhtml" 02: xmlns:h="http://java.Java EE (Web Applications – II) 101 Displaying employees based on selected job The following example shows how to display a dropdown list with job titles and display the list of employees for the selected job.com/jsf/core"> 04: <h:body> 05: <h2>Employees List By Job </h2> 06: <f:view> 07: <h:form id="employeesForm">Select Job 08: <h:selectOneMenu id="job" value="#{employeeBean. employees.com/jsf/html" 03: xmlns:f="http://java.w3.salary} 23: </h:column> 24: <h:column> 25: <f:facet name="header">Hire Date</f:facet> 26: #{employee. 06: import javax.bean. 20: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE"). 30: } 31: rs. 22: rs.setUsername("hr").out.close().util. 33: } catch (Exception e) { 34: System.getString("job_id"). 42: rs.job = job.faces. Srikanth Technologies .setCommand("select * from jobs").Java EE (Web Applications – II) 102 EmployeeBean. 37: } 38: } 39: public RowSet getEmployees() { 40: try { 41: CachedRowSet rs = new OracleCachedRowSet(). 43: rs.jdbc. 32: return al.setUrl("jdbc:oracle:thin:@localhost:1521:XE").ArrayList.add(new SelectItem(rs.faces.model. 05: import javax.getString("job_title"))). 29: rs.java 01: package beans. 24: rs. 16: } 17: public ArrayList<SelectItem> getJobs() { 18: try { 19: CachedRowSet rs = new OracleCachedRowSet().setPassword("hr").ManagedBean. 03: import javax.next()) { 28: al.rowset. 23: rs. 08: @ManagedBean 09: public class EmployeeBean { 10: private String job.sql.rowset.RowSet.OracleCachedRowSet. 27: while (rs.println("Error In getJobs() -->" + 35: e. 02: import java.execute().getMessage()).setUsername("hr"). 21: rs. 11: public String getJob() { 12: return job. 04: import javax.CachedRowSet.SelectItem.sql. 07: import oracle. 36: return null. 25: ArrayList<SelectItem> al = 26: new ArrayList<SelectItem>(). 13: } 14: public void setJob(String job) { 15: this. 53: } 54: } // getEmployees 55: } Srikanth Technologies .println(e). 52: return (null). 47: rs. 50: } catch (Exception e) { 51: System. job).Java EE (Web Applications – II) 103 44: rs. 45: rs.out. 48: rs.setPassword("hr"). 49: return rs.execute().setCommand 46: ("select * from employees where job_id = ?").setString(1.
Copyright © 2024 DOKUMEN.SITE Inc.