Você está na página 1de 262

Java EE

Course 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


srikanthpragada@yahoo.com.

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 srikanthpragada@yahoo.com.

Alternatively you can visit my website


www.srikanthtechnologies.com/feedback.aspx and provide
feedback there.

Srikanth Technologies
JDBC
JDBC 1
Getting Started With Oracle11g Express Edition
Oracle11g express edition provides HR account by default. But this
account is locked by default. So you must log in as SYSTEM (DBA)
to unlock this account. The password of this account is expired by
default, so you have to reset password as well.

Steps to unlock HR Account:

1. StartAll ProgramsOracle Database 11g Express EditionRun


SQL Command Line.
2. Use CONNECT command at SQL> prompt to connect to Oracle
using SYSTEM account.

SQL>connect SYSTEM

3. When prompted to enter password, enter password that you


gave at the time of installing Oracle.
4. Unlock HR account and reset password by giving following two
commands at the SQL> prompt.

SQL>alter user hr account unlock;


SQL>alter user hr identified by hr;

5. Then connect Oracle as HR by using CONNECT command as


follows:

SQL>Connect hr/hr
SQL>select * from tab;
SQL>select * from jobs;

Note: HR account comes with a set of tables like EMPLOYEES, JOBS,


DEPARTMENTS etc.

Srikanth Technologies
JDBC 2
The following are some of the tables that come with HR account.
The following are the tables we use in Java programs.

SQL> desc jobs


Name Null? Type
---------------------------------- -------- ------------ 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
---------------------------------- -------- --------------
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,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)

SQL> desc departments


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
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. 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.x API is divided into two packages: java.sql and
javax.sql. 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, you need a JDBC
technology-based driver to access database
Driver must support at least ANSI SQL-2 Entry Level (1992)

Srikanth Technologies
JDBC 4
JDBC Components
JDBC provides the following components as part of the JDK.

JDBC driver The JDBC driver manager is the backbone of the


manager JDBC architecture. It actually is quite small and
simple; its primary function is to connect Java
applications to the correct JDBC driver and then
get out of the way.
JDBC-ODBC The JDBC-ODBC bridge allows ODBC drivers to be
bridge used as JDBC drivers. It provides a way to access
less popular DBMS if JDBC driver is not
implemented for it.

Important Interfaces
The following are the interfaces provided with JDBC API. These
interfaces are implemented by driver. A driver contains a collection
of classes to implement these interfaces.

Interface Meaning
CallableStatement The interface used to execute SQL stored
procedures.
Connection A connection (session) with a specific
database.
DatabaseMetaData Comprehensive information about the database
as a whole.
Driver The interface that every driver class must
implement.
PreparedStatement An object that represents a precompiled SQL
statement.
ResultSet A ResultSet provides access to a table of data.
ResultSetMetaData An object that can be used to find out about
the types and properties of the columns in a
ResultSet.

Srikanth Technologies
JDBC 5
Statement The object used for executing a static SQL
statement and obtaining the results produced
by it.

Important Classes
The following are the classes provided by JDBC API. These classes
are provided in addition to interfaces mentioned above.

Class Description
Date A thin wrapper around a millisecond value that
allows JDBC to identify this as SQL DATE.
DriverManager The basic service for managing a set of JDBC
drivers.
DriverPropertyInfo Driver properties for making a connection.
Time A thin wrapper around java.util.Date that allows
JDBC to identify this as SQL TIME value.
Timestamp This class is a thin wrapper around
java.util.Date that allows JDBC to identify this
as SQL TIMESTAMP value.
Types The class that defines constants that are used
to identify generic SQL types, called JDBC
types.

DriverManager Class
Part of java.sql package, used to manage JDBC drivers.
Sits between the application programs and the drivers.
Keeps track of the drivers that are available and handles
establishing a connection between a database and the
appropriate driver.

Srikanth Technologies
JDBC 6
Method Meaning
Connection getConnection Establishes a connection with the
(String url, String un, specified database.
String pwd)
Driver getDriver(String url) Returns a driver that can understand
the URL.
Enumeration getDrivers() Returns the drivers that are currently
loaded.
void registerDriver (Driver Registers the given driver.
driver)

Driver Interface
This is the interface that every driver has to implement.
Each driver should supply a class that implements the Driver
interface.

Method Meaning
boolean Returns true if the driver thinks that it can
acceptsURL(String url) open a connection to the given URL.
Connection Connects to a database and returns
connect(String url, connection object.
Properties info)
int getMajorVersion() Returns major version number.
int getMinorVersion() Returns minor version number.

Srikanth Technologies
JDBC 7

Connection interface
Represents a connection to specific database.
SQL statements are executed and results are returned within the
context of a connection.

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, which can be
used to get information about the
database
boolean isClosed() Returns true if connection is closed

Srikanth Technologies
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.jar file in classpath of the application
Load jdbc driver for Oracle using Class.forName() method
Starting from Jdbc 4.0, loading driver class is optional
Establish a connection to database by using
DriverManager.getConnection() with required connection
string, username and password.

01: import java.sql.Connection;


02: import java.sql.DriverManager;
03:
04: public class OracleOCIConnection {
05: public static void main(String args[]) {
06: try {
07: Class.forName("oracle.jdbc.driver.OracleDriver");
08: Connection con = DriverManager.getConnection
09: ("jdbc:oracle:oci8:@","hr","hr");
10: System.out.println("Connected Using OCI driver");
11: con.close();
12: }
13: catch(Exception ex) {
14: ex.printStackTrace();
15: }
16: } // end of main
17: } // class

Srikanth Technologies
JDBC 9
Using Oracles Thin driver
Thin driver provided by Oracle belongs to Type 4 category of
JDBC drivers.
This accesses oracles TNS listener on the server.
Connection string contains host, port number of listener, oracle
instance name, username and password.

01: import java.sql.Connection;


02: import java.sql.DriverManager;
03:
04: public class OracleThinConnection {
05: public static void main(String args[]) {
06: try (Connection con =
07: DriverManager.getConnection
08: ("jdbc:oracle:thin:@localhost:1521:XE",
09: "hr", "hr")) {
10: System.out.println("Connected Using Thin Driver");
11: }
12: catch (Exception ex) {
13: ex.printStackTrace();
14: }
15: } // end of main
16: } // end of OracleThinConnection

Srikanth Technologies
JDBC 10
DataSource
Datasource objects can provide connection pooling and
distributed transactions.
For convenience and portability, datasources can be bound to
Java Naming and Directory Interface (JNDI) entities, so that you
can access databases by logical names.
The datasource facility provides a complete replacement for the
previous JDBC DriverManager facility.
You can use both facilities in the same application, but it is
recommended that you use datasources.
Method setConnectionCachingEnabled(true) is used to turn on
connection pooling.

The DataSource interface is implemented by a driver vendor. 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.
A DataSource implementation that supports connection pooling
produces Connection objects that participate in connection
pooling, that is, connections that can be recycled.
A DataSource implementation that supports distributed
transactions produces Connection objects that can be used in a
distributed transaction, that is, a transaction that accesses two or
more DBMS servers.

Srikanth Technologies
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. Default is 0.
MaxLimit Sets the maximum number of connection instances
the cache can hold. The default value is
Integer.MAX_VALUE, meaning that there is no limit
enforced by the connection cache, so that the number
of connections is limited only by the number of
database sessions configured for the database.
MinLimit Sets the minimum number of connections the cache
maintains. This guarantees that the cache will not
shrink below this minimum limit. Default is 0.

1: import java.sql.Connection;
2: import oracle.jdbc.pool.OracleDataSource;
3:
4: public class OracleDatasourceConnection {
5:
6: public static void main(String[] args)
7: throws Exception {
8: OracleDataSource ods = new OracleDataSource();
9: ods.setURL("jdbc:oracle:thin:@localhost:1521:xe");
10: ods.setUser("hr");
11: ods.setPassword("hr");
12:
13: try (Connection con = ods.getConnection()) {
14: System.out.println
15: ("Connected To Oracle using DataSource");
16: }
17: } // main()
18: }

Srikanth Technologies
JDBC 12
The following program enables connection pooling and sets
connection pool settings:

1: import java.sql.Connection;
2: import java.util.Properties;
3: import java.util.Scanner;
4: import oracle.jdbc.pool.OracleDataSource;
5:
6: public class OracleDatasourceWithCP {
7: public static void main(String[] args)
8: throws Exception{
9: OracleDataSource ods = new OracleDataSource();
10: ods.setURL("jdbc:oracle:thin:@localhost:1521:xe");
11: ods.setUser("hr");
12: ods.setPassword("hr");
13: ods.setConnectionCachingEnabled(true);
14:
15: Properties prop = new Properties();
16: prop.setProperty("MinLimit", "5");
17: prop.setProperty("MaxLimit", "25");
18: prop.setProperty("InitialLimit", "5");
19: ods.setConnectionCacheProperties(prop);
20:
21: try (Connection con = ods.getConnection()) {
22: System.out.println
23: ("Connected To Oracle using DataSource");
24: }
25: }
26: }

Srikanth Technologies
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.sql.Connection;
2: import java.sql.DriverManager;
3: import java.sql.Statement;
4:
5: public class ExecuteUpdate {
6: public static void main(String args[]){
7: try (Connection con =
8: DriverManager.getConnection
9: ("jdbc:oracle:thin:@localhost:1521:XE",
10: "hr", "hr");
11: Statement st = con.createStatement()) {
12:
13: int count = st.executeUpdate("update employees
14: set salary=salary*1.1 where employee_id=120");
15:
16: if (count == 1)
17: System.out.println("Updation is successful");
18: else
19: System.out.println("Updation is unsuccessful");
20: } catch (Exception ex) {
21: ex.printStackTrace();
22: }
23: } // end of main
24: } // end of ExecuteUpdate

Srikanth Technologies
JDBC 14
Statement Interface
Is used to execute an SQL command.
At the time of creating Statement we have to specify what type
of ResultSet is to be created from this Statement.
Only one ResultSet per a statement can be opened at a time.

Method Meaning
ResultSet Executes the query in the statement
executeQuery(String) and returns ResultSet.
int executeUpdate(String) Executes DML command and returns
the no. of rows updated.
boolean execute(String) Executes SQL command and returns
true if query is executed.
Connection getConnection() Returns the connection object that
produced this statement.
ResultSet getResultSet() Returns current ResultSet.
int getUpdateCount() Returns update count of most
recently executed command.
void close() Enables the resources to be released.

ResultSet Interface
Provides access to a set of rows.
Contains a cursor that points to a particular record in the
ResultSet.
This cursor is positioned initially before the first row.
You can retrieve values of columns using get<type>() methods.
Columns can be referred either by column number or name.
Columns are numbered from 1.
A ResultSet may be either scrollable or forward only. It may be
either updatable or read-only.

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.
Srikanth Technologies
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_FORWARD_ONLY The type for a ResultSet object whose
cursor may move only forward.
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.
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.

ResultSet

Record Pointer

Srikanth Technologies
JDBC 16
Method Meaning
type get<type> Returns the value of the column identified
(int index) by index.
type get<type> Returns the value of the column identified
(String name) by name.
ResultSetMetaData Returns metadata of the ResultSet.
getMetaData()
boolean next() Moves cursor to next row and returns true if
next row is valid.
boolean wasNull() Returns true when the last columns read
was null.
void close() Closes ResultSet.
boolean Moves the cursor to the given row.
absolute(int row)
void Cancels the updates made to a row.
cancelRowUpdates()
int Maps the given ResultSet column name to
findColumn(columnName) its ResultSet column index.
int getRow() Returns current row number. Row number
starts with 1.
boolean first () Moves to first record. Returns true on
success.
boolean last() Moves to the last record. Returns true on
success.
boolean previous() Moves to the previous record.
void beforeFirst() Moves to immediately before first record.
void afterLast() Moves to immediately after the last record.
boolean relative(int) Moves forward or backward by specified
number of rows.
boolean isLast() Returns true if cursor is on the last record.
boolean isFirst() Returns true if cursor is on the first record.
boolean isAfterLast() Returns true if cursor is after the last
record.
boolean isBeforeFirst() Returns true if cursor is before the first
Srikanth Technologies
JDBC 17
record.
void refreshRow() Refreshes current row with its most recent
values in the database.
void update<type>(int, Changes the existing data.
value)
void Cancels the updates made to a row.
cancelRowUpdates()
void Creates a new blank row.
moveToInsertRow()
void insertRow() Appends the new row to the table.
void deleteRow() Deletes the current row of the ResultSet
from the table.
void updateRow() Updates the database with the new contents
of the current row.

1: import java.sql.Connection;
2: import java.sql.DriverManager;
3: import java.sql.ResultSet;
4: import java.sql.Statement;
5: public class EmployeeList {
6: public static void main(String args[]) {
7: try (Connection con =
8: DriverManager.getConnection(
9: "jdbc:oracle:thin:@localhost:1521:XE","hr", "hr");
10: Statement st = con.createStatement();
11: ResultSet rs =
12: st.executeQuery
13: ("select employee_id,first_name from
14: employees where employee_id <= 110")) {
15: while (rs.next()) {
16: System.out.println(rs.getInt(1) + " - " +
17: rs.getString("first_name"));
18: } // end of while
19: } // end of try
20: catch (Exception ex) {

Srikanth Technologies
JDBC 18
21: ex.printStackTrace();
22: }
23: } // end of main
24: } // end of EmployeeList

Modifying Rows in ResultSet


In order to update a ResultSet, first the Statement object is to be
created as follows:

Statement st= con.createStatement


(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

First parameter specifies scrollable nature of the ResultSet. The


second parameter of createStatement() specifies whether ResultSet
created from this Statement is updatable or read-only.

1: import java.sql.Connection;
2: import java.sql.DriverManager;
3: import java.sql.ResultSet;
4: import java.sql.Statement;
5: public class UpdateResultSet {
6: public static void main(String[] args)
7: throws Exception {
8: try (Connection con = DriverManager.getConnection(
9: "jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
10: Statement st = con.createStatement
11: (ResultSet.TYPE_SCROLL_INSENSITIVE,
12: ResultSet.CONCUR_UPDATABLE);
13: ResultSet rs = st.executeQuery(
14: "select job_id,job_title, min_salary
15: from jobs")){
16: // goto last row
17: rs.last();
18: // values before change
19: System.out.println(rs.getString(2));
20: System.out.println(rs.getString(3));
Srikanth Technologies
JDBC 19
21: // update minimum salary
22: rs.updateInt(3, rs.getInt(3) + 1000);
23: rs.updateRow(); // update database
24:
25: // values after change
26: System.out.println(rs.getString(2));
27: System.out.println(rs.getString(3));
28: } catch (Exception ex) {
29: System.out.println(ex);
30: }
31: }
32: }

PreparedStatement Interface
Contains a precompiled SQL statement. Command can be
executed efficiently for multiple times.
Extends Statement interface. Obtained using
prepareStatement() method of Connection interface.

Method Meaning
void clearParameter() Clears values of all parameters.
void set<type>(int , Sets the given value to the parameter at the
value) specified index.

1: import java.sql.Connection;
2: import java.sql.DriverManager;
3: import java.sql.PreparedStatement;
4:
5: public class ChangeName {
6: public static void main(String args[]) {
7: try (Connection con =
8: DriverManager.getConnection
9: ("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
10: PreparedStatement ps = con.prepareStatement
11: ("update employees set first_name = ?
12: where employee_id = ? ")) {
Srikanth Technologies
JDBC 20
13: ps.setString(1, "SMITH");
14: ps.setInt(2, 100);
15: int rows = ps.executeUpdate();
16: if (rows == 1)
17: System.out.println("Updation is successful");
18: else
19: System.out.println("Updation is unsuccessful");
20: } catch (Exception ex) {
21: ex.printStackTrace();
22: }
23: } // end of main
24: }

CallableStatement Interface
Used to execute a stored procedure or function.
It extends PreparedStatement interface.

To call a function:
{?=call<function-name>[<arg1>,<arg2>, ...]}
To call a procedure:
{call <procedure-name>[<arg1>,<arg2>, ...]}

Method Meaning
type get<type> Returns the value of the given parameter.
(int index)
void Registers an OUT parameter at the specified
registerOutParameter parameter index to the SQLType.
(int index,int type)
boolean wasNull() Returns true if last OUT parameter read has
SQL NULL.

Srikanth Technologies
JDBC 21
UPDATESALARY procedure
1:create or replace procedure UpdateSalary(p_empid number,
2: p_sal number) is
3: begin
4: update employees set salary = p_sal
5: where employee_id = p_empid;
6: commit;
7: end;

1: import java.sql.CallableStatement;
2: import java.sql.Connection;
3: import java.sql.DriverManager;
4: public class CSExample {
5: public static void main(String args[]) {
6: try (Connection con = DriverManager.getConnection
7: ("jdbc:oracle:thin:@localhost:1521:XE",
8: "hr", "hr");
9: CallableStatement cs=
10: con.prepareCall("{call UpdateSalary(?,?)}");){
11:
12: // set employee number
13: cs.setInt(1, 100);
14: // set salary
15: cs.setInt(2, 6000);
16: // execute update command
17: cs.execute();
18: } catch (Exception ex) {
19: System.out.println("Error : " + ex);
20: }
21: } // end of main
22: }

Srikanth Technologies
JDBC 22
ResultSetMetaData Interface
It contains the properties of columns in the ResultSet.

Method Meaning
int getColumnCount() Returns the no. of columns in the
ResultSet.
String getColumnName(int) Returns the name of the column.
int getColumnType(int) Returns column's SQL type.
String getTableName(int) Returns the table name for the
given column.
boolean isNullable(int) Returns true if column can contain
null.
int getColumnDisplaySize(int) Indicates the column's normal max
width in chars.
String Retrieves a column's database-
getColumnTypeName(int) specific type name.
int getPrecision(int) Gets a column's number of decimal
digits.
int getScale(int column) Gets a column's number of digits to
right of the decimal point.

Note: Use getMetaData() method of ResultSet to get


ResultSetMetaData object.

DatabaseMetaData Interface
It provides information about the database. We can find out the
features supported by database and objects available in database.

Method Meaning
String Returns the name of this database
getDatabaseProductName() product.
String Returns the version of this database
getDatabaseProductVersion() product.

Srikanth Technologies
JDBC 23
ResultSet getSchemas() Returns the list of schemas of the
database.
ResultSet getTables (String Returns the list of tables that match
catalog, String schema, the criteria.
String table, String
tabletype[])
ResultSet getColumns Gets a description of table columns
(String catalog, available in the specified catalog.
String schemaPattern,
String tableNamePattern,
String columnNamePattern)

Note: Use getMetaData() method of Connection object to get


DatabaseMetaData object.

JDBC Interfaces vs. Oracle Driver


JDBC is a collection of interfaces and a few classes. Jdbc driver is a
collection of classes that implements JDBC interfaces. For example,
JDBC driver for Oracle is a collection of classes provided in a single
jar file ojdbc6.jar.

The following picture shows the relationship between JDBC interface


and classes in Oracle driver.
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.

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.
Requires the ODBC driver to be present on the client.

Srikanth Technologies
JDBC 25

Java Application

Type 1 JDBC Driver

ODBC Driver

Database

Using JDBC-ODBC Bridge Driver


In order to use ODBC driver, first we have to create DSN (Data
Source Name) using ODBC administrator (steps are given below)
and then use DSN in connection URL.

Steps to create Data Source Name (DSN):

1. Invoke Control Panel.


2. Select Administrative tools.
3. Select Data Sources (ODBC). It displays ODBC Data Source
Administrator window.
4. Go to User DSN tab and click on Add button.
5. Select Oracle In XE from List of Drivers and click on Finish.
6. In the next dialog box enter Data Source name oraclejava
and other information such as username and password.
7. In case you access Oracle from a remote client then enter Oracle
service name in Server field.
8. Click on Ok button. Now oraclejava must appear in the list of
DSNs.

Srikanth Technologies
JDBC 26

Note: The above process lists steps in Windows 7 or above. Change


the steps regarding ODBC Administrator in case you use another
operating system.

1: import java.sql.Connection;
2: import java.sql.DriverManager;
3: public class OracleODBCConnection {
4: public static void main(String args[]) {
5: try (Connection con = DriverManager.getConnection
6: ("jdbc:odbc:oraclejava", "hr", "hr")) {
7: System.out.println("Connected using ODBC driver");
8: }
9: catch (Exception ex) {
10: ex.printStackTrace();
11: }
12: }
13: }

Srikanth Technologies
JDBC 27
Native API partly Java driver
Converts JDBC calls into calls on the client API for Oracle,
Sybase, Informix, DB2, or other DBMS.
Requires that some binary code be loaded on each client
machine.
Oracles OCI driver is an example for this.

Java Application

Type 2 JDBC Driver

Native API

Database

Network Protocol Pure Java driver


Translates JDBC calls into a DBMS-independent net protocol,
which is then translated to a DBMS protocol by a server.
This driver is provided by middleware (application server)
vendor.
Fusion Middleware is an example for middleware.
Clients need not have any binary code.

Java Application

Type 3 JDBC Driver

Middleware

API Database

Srikanth Technologies
JDBC 28
Native-protocol Pure Java driver
This kind of driver converts JDBC calls into the network protocol
used by DBMS directly.
Oracle Thin driver is an example for this.

Java Application

Type 4 JDBC Driver

Database

Note: Eventually, driver categories 3 and 4 will be the preferred


way to access databases from JDBC.

Transaction Management
A transaction consists of one or more statements that have been
executed, completed, and then either committed or rolled back.
When the method commit or rollback is called, the current
transaction ends and another one begins.
A new connection is in auto-commit mode by default, meaning
that when a statement is completed, the method commit will be
called on that statement automatically.

Method Meaning
void setAutoCommit(boolean) Turns on/off auto commit mode.
boolean getAutoCommit() Returns the current auto commit
mode.
void commit() Makes all changes since previous
commit point permanent.

Srikanth Technologies
JDBC 29
void rollback() Drops all changes made since the
previous commit/rollback.
void rollback(Savepoint) Rolls back changes made from the
given savepoint.
Savepoint Sets a savepoint in the current
setSavepoint(name) transaction.
void releaseSavepoint(sp) Releases savepoint from current
transaction.

con.setAutoCommit(false);
try {
st.executeUpdate(cmd1);
st.executeUpdate(cmd2);
con.commit();
}
catch(Exception ex) {
con.rollback();
}

Savepoints
Savepoint is a point within a transaction to which you can roll
back. Connection interface provides setSavepoint () method to
set savepoint.
Method releaseSavepoint(savepoint) releases savepoint from
the current transaction.

Statement stmt = conn.createStatement();


int rows = stmt.executeUpdate( sqlcommand );
Savepoint savepoint1 = conn.setSavepoint("SAVEPOINT1");
rows = stmt.executeUpdate(sqlcommand);
...
if ( rows > 5 )
conn.rollback(svpt1);
...
conn.commit();

Srikanth Technologies
JDBC 30
Batch Updates
It allows multiple DML statements to be executed in a single
request.
Reduces overhead on database server as it has to execute only
one command.
Improves performance when large number of statements are
executed.

01: import java.sql.BatchUpdateException;


02: import java.sql.Connection;
03: import java.sql.DriverManager;
04: import java.sql.Statement;
05: public class BatchUpdateDemo {
06: public static void main(String args[]) {
07: try (Connection con = DriverManager.getConnection
08: ("jdbc:oracle:thin:@localhost:1521:xe","hr","hr")) {
09: con.setAutoCommit(false);
10: Statement stmt = con.createStatement();
11: try {
12: stmt.addBatch("update employees set
13: salary=salary+2000 where salary>10000");
14: stmt.addBatch("update employees set
15: salary=salary+1000 where salary<10000");
16:
17: int[] uc = stmt.executeBatch();//execute batch
18: con.commit();
19:
20: for (int i = 0; i < uc.length; i++) {
21: System.out.println(i + ":" + uc[i]);
22: } // end of for loop
23: }
24: catch (BatchUpdateException ex) {
25: System.out.println("Batch Update Exception :" +
26: ex.getMessage());
27: con.rollback();
28: }

Srikanth Technologies
JDBC 31
29: } // outer try
30: catch (Exception ex) {
31: ex.printStackTrace();
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.
RowSets support component-based development models like
JavaBeans, with a standard set of properties and an event
notification mechanism.
A rowset's properties include its command, type, data source
name, url, user name, password etc.

The following are different types of rowsets offered by Oracle.

CachedRowSet
JDBCRowSet
WebRowSet
FilteredRowSet
JoinRowSet

Srikanth Technologies
JDBC 32
RowSet Events
The following types of events are supported by the RowSet
interface.

cursorMoved This event is generated whenever there is a cursor


movement. For example, when the next or
previous method is called.
rowChanged This event is generated when a row is inserted,
updated, or deleted from the RowSet.
rowSetChanged This event is generated when the whole RowSet is
created or changed. For example, when the
execute method is called.

Application components, which are interested in these events, must


implement the standard javax.sql.RowSetListener interface and
register such listener objects with a RowSet object.

A listener can be registered using the RowSet.addRowSetListener


method and unregistered using the RowSet.removeRowSetListener
method.

rowset.addRowSetListener(new OracleRowSetListenerAdapter () {
public void rowSetChanged(RowSetEvent event) {
}
}
);

The javax.sql.RowSet interface extends the java.sql.ResultSet


interface.

Srikanth Technologies
JDBC 33
The following are important methods of RowSet.

Method Description
void clearParameters() Clears the parameters set for
this RowSet object's command.

void execute() Fills this RowSet object with


data.

void setCommand(String cmd) Sets this RowSet object's


command property to the given
SQL query.

void setType(int parameterIndex, Sets the value to the given


Type value) parameter identified by index.

void setType(String columnName, Sets the value to the given


Type value) parameter identified by
columname.

void Sets the concurrency of


setConcurrency(int concurrency) this RowSet object to the given
concurrency level.

void Sets the data source name


setDataSourceName(String name) property for this RowSet object
to the given String.

void setUrl(String url) Sets the URL this RowSet object


will use when it uses
the DriverManager to create a
connection.

void Sets the database password for


setPassword(String password) this RowSet object to the
given String.

Srikanth Technologies
JDBC 34
void setUsername(String name) Sets the username property for
this RowSet object to the
given String.

CachedRowSet
A CachedRowSet is a RowSet in which the rows are cached and the
RowSet is disconnected, that is, it does not maintain an active
connection to the database.

The following are important methods of CachedRowSet:

Method Description
void acceptChanges() Propagates row update, insert and delete
changes made to this CachedRowSet
object to the underlying data source.
boolean Indicates whether the designated column
columnUpdated(int idx) in the current row of this CachedRowSet
object has been updated.
boolean Indicates whether the designated column
columnUpdated(String in the current row of this CachedRowSet
columnName) object has been updated.

void commit() Each CachedRowSet object's SyncProvide


contains a Connection object from
the ResultSet or JDBC properties passed
to its constructors.
CachedRowSet Creates a RowSet object that is a deep
createCopy() copy of the data in
this CachedRowSet object.
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.

Srikanth Technologies
JDBC 35
ResultSet getOriginal() Returns a ResultSet object containing the
original value of
this CachedRowSet object.
ResultSet Returns a ResultSet object containing the
getOriginalRow() original value for the current row only of
this CachedRowSet object.
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.
void rollback() Each CachedRowSet object's SyncProvider
contains a Connection object from the
original ResultSet or JDBC properties
passed to it.
int size() Returns the number of rows in
this CachedRowSet object.
Collection<?> Converts this CachedRowSet object to
toCollection() a Collection object that contains all of
this CachedRowSet object's data.
void undoDelete() Cancels the deletion of the current row
and notifies listeners that a row has
changed.
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.
void undoUpdate() Immediately reverses the last update
operation if the row has been modified.

Srikanth Technologies
JDBC 36

1: import javax.sql.rowset.CachedRowSet;
2: import oracle.jdbc.rowset.OracleCachedRowSet;
3: public class CachedRowSetDemo {
4: public static void main(String[] args)
5: throws Exception {
6: CachedRowSet crs = new OracleCachedRowSet();
7: crs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
8: crs.setUsername("hr");
9: crs.setPassword("hr");
10: crs.setCommand("select * from jobs");
11: crs.execute();
12: while ( crs.next()) {
13: System.out.println
14: (crs.getString(2) + ":" + crs.getInt(3));
15: }
16: crs.absolute(1);
17:
18: crs.updateInt(3, crs.getInt(3) + 1000);
19: crs.updateRow();
20:
21: crs.beforeFirst();
22: while ( crs.next()) {
23: System.out.println
24: (crs.getString(2) + ":" + crs.getInt(3));
25: }
26: crs.acceptChanges();
27: }
28: }

Srikanth Technologies
JDBC 37
JDBCRowSet
A JDBCRowSet is a RowSet that wraps around a ResultSet object. It
is a connected RowSet that provides JDBC interfaces in the form of a
JavaBean interface.

The Oracle implementation of JDBCRowSet is OracleJDBCRowSet.

WebRowSet
A WebRowSet is an extension to CachedRowSet. 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. The Oracle implementation of
WebRowSet is OracleWebRowSet.

public void writeXml(java.io.Writer writer)


public void readXml(java.io.Reader reader)

1: import java.sql.*;
2: import javax.sql.*;
3: import oracle.jdbc.rowset.*;
4: import java.io.*;
5: public class WebRowSetDemo {
6: public static void main(String[] args)
7: throws Exception{
8: OracleWebRowSet rs = new OracleWebRowSet();
9: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
10: rs.setUsername("hr");
11: rs.setPassword("hr");
12: rs.setCommand("select * from jobs");
13: rs.execute();
14: // write to XML
15: FileWriter fw = new FileWriter("c:\\jobs.xml");
16: rs.writeXml(fw);
17: rs.close();
18: }
19: }

Srikanth Technologies
JDBC 38
FilteredRowSet
A FilteredRowSet is an extension to WebRowSet that provides
programmatic support for filtering its content. Oracle
implementation of FilteredRowSet is OracleFilteredRowSet.

The following are methods related to FilteredRowSet:

Method Description
Predicate getFilter() Retrieves the active filter for this
FilteredRowSet object.
void setFilter(Predicate p) Applies the given Predicate object to this
FilteredRowSet object. Null clears the
current filter.

Predicate Interface
Allows applications to define the filter they wish to apply to filter
rows.
A FilteredRowSet object enforces the filter constraints in a bi-
directional manner: It outputs only rows that are within the
constraints of the filter; and conversely, it inserts, modifies, or
updates only rows that are within the constraints of the filter.

Method Description
boolean This method is called by a FilteredRowSet
evaluate(Object value, object to check whether the value lies
int column) between the filtering criterion set using the
setFilter().
boolean Called by the FilteredRowSet object to
evaluate(Object value, check whether the value lies between the
String columnName) filtering criteria set using the setFilter().
boolean This method is typically called
Srikanth Technologies
JDBC 39
evaluate(RowSet rs) as FilteredRowSet object internal methods
(not public) that control the RowSet
object's cursor from row to the next.

1: import java.sql.SQLException;
2: import javax.sql.RowSet;
3: import javax.sql.rowset.FilteredRowSet;
4: import javax.sql.rowset.Predicate;
5: import oracle.jdbc.rowset.OracleFilteredRowSet;
6: public class FilteredRowSetDemo {
7: public static void main(String[] args) throws
8: Exception{
9: FilteredRowSet rs = new OracleFilteredRowSet();
10: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
11: rs.setUsername("hr");
12: rs.setPassword("hr");
13: rs.setCommand("select * from jobs");
14: rs.execute();
15:
16: System.out.println("Jobs with MinSalary > 10000");
17: rs.setFilter(new MinSalaryPredicate());
18:
19: while (rs.next()) {
20: System.out.println(rs.getString("job_title")
21: + ":" + rs.getString("min_salary"));
22: }
23: System.out.println("Jobs with Length(Title) >15");
24: rs.setFilter(new TitlePredicate());
25: rs.execute();
26: while (rs.next()) {
27: System.out.println(rs.getString("job_title")
28: + ":" + rs.getString("min_salary"));
29: }
30: rs.close();
31: }
32: }
33: class MinSalaryPredicate implements Predicate {
34: @Override
35: public boolean evaluate(Object o, int i)
Srikanth Technologies
JDBC 40
36: throws SQLException {
37: return true;
38: }
39: @Override
40: public boolean evaluate(Object o, String string)
41: throws SQLException {
42: return true;
43: }
44: @Override
45: public boolean evaluate(RowSet rs) {
46: try {
47: Integer minsal = rs.getInt(3);
48: if (minsal > 10000) {
49: return true;
50: } else {
51: return false;
52: }
53:
54: } catch (Exception ex) {
55: return false;
56: }
57: }
58: }
59:
60: class TitlePredicate implements Predicate {
61: @Override
62: public boolean evaluate(Object o, int i)
63: throws SQLException {
64: return true;
65: }
66:
67: @Override
68: public boolean evaluate(Object o, String string)
69: throws SQLException {
69: return true;
70: }
71: @Override
72: public boolean evaluate(RowSet rs) {
73: try {
74: String title = rs.getString(2);
75: if (title.length() > 15) {
Srikanth Technologies
JDBC 41
76: return true;
77: } else {
78: return false;
79: }
80:
81: } catch (Exception ex) {
82: return false;
83: }
84: }
85: }

JoinRowSet
There is no standard way to establish a SQL JOIN between
disconnected RowSets without connecting to the data source. A
JoinRowSet addresses this issue. The Oracle implementation of
JoinRowSet is the oracle.jdbc.rowset.OracleJoinRowSet class.

1: import javax.sql.rowset.CachedRowSet;
2: import javax.sql.rowset.JoinRowSet;
3: import oracle.jdbc.rowset.OracleCachedRowSet;
4: import oracle.jdbc.rowset.OracleJoinRowSet;
5: public class JoinRowSetDemo {
6: public static void main(String[] args)
7: throws Exception {
8: CachedRowSet crs1 = new OracleCachedRowSet();
9: crs1.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
10: crs1.setUsername("hr");
11: crs1.setPassword("hr");
12: crs1.setCommand("select job_id,job_title from jobs");
13: from jobs");
14: crs1.execute();
15: CachedRowSet crs2 = new OracleCachedRowSet();
16: crs2.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17: crs2.setUsername("hr");
18: crs2.setPassword("hr");
19: crs2.setCommand
20: ("select job_id,first_name,salary from employees");
Srikanth Technologies
JDBC 42
21: from employees");
22: crs2.execute();
23: JoinRowSet jrs = new OracleJoinRowSet();
24: jrs.addRowSet(crs1,"job_id"); // join column
25: jrs.addRowSet(crs2,"job_id"); // join column
26:
27: // get values using column number. 1. for job_id,
28: 2.job_title, 3.first_name, 4. salary
29: while (jrs.next()) {
30: if ( jrs.getInt(4) > 10000) // salary > 10000
31: System.out.printf("Employee [%s] is [%s]\n",
32: jrs.getString(3), jrs.getString(2));
33: } // while
34: }
35:}

Writing a picture into BLOB of Oracle


The following example shows how to write into a BLOB column in
Oracle. Create a table called PLAYERS as follows:

1: create table players


2: ( name varchar2(20) primary key,
3: photo blob
4: );

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.

Srikanth Technologies
JDBC 43

1: import java.io.File;
2: import java.io.FileInputStream;
3: import java.sql.Connection;
4: import java.sql.DriverManager;
5: import java.sql.PreparedStatement;
6: import java.util.Scanner;
7: public class AddPlayer {
8: public static void main(String args[]) {
9: try(Connection con = DriverManager.getConnection
10: ("jdbc:oracle:thin:@localhost:1521:xe",
11: "hr","hr")) {
12: // Take input from user
13: Scanner s = new Scanner(System.in);
14: System.out.print("Enter player name :");
15: String playername = s.nextLine();
16: System.out.print("Enter Photo filename :");
17: String photofilename = s.nextLine();
18:
19: con.setAutoCommit(false);
20: PreparedStatement ps =
21: con.prepareStatement("insert into players
22: values(?,?)");
23: File picfile = new File(photofilename);
24: FileInputStream is =
25: new FileInputStream(picfile);
26: ps.setString(1, playername);
27:
28: ps.setBinaryStream(2, is,
29: (int) picfile.length());
30: ps.executeUpdate();
31: con.commit();
32: ps.close();
33: }
34: catch (Exception ex) {
35: ex.printStackTrace();
36: }
37: }
38: }

Srikanth Technologies
JDBC 44
Reading data from CLOB column
The following code is used to read data from CLOB column. It prints
data taken from a CLOB column.

Create table applicants


( id number(5),
resume clob
);

Statement st = con.createStatement();
ResultSet rs = st.executeQuery
("select resume from applicants where id = 1");
rs.next();
Clob clob = rs.getClob(1); //get lob from second column

// get stream to read data from lob


InputStream is = clob.getAsciiStream();
int ch;

while( (ch=is.read()) != -1)


System.out.print( (char) ch);

Srikanth Technologies
Web
Applications - I
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.

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) 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
Java EE (Web Applications I) 7
Attributes related to validation

Required, Pattern, Novalidate(Form), 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,}" />
11: <p />
12: <input type="submit" value="Login" />
13: <input type="submit" value="Cancel"
14: formaction="cancel"
15: formnovalidate="formnovalidate" />
16: </form>

Srikanth Technologies
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, 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, onMouseMove etc.

Where to put JavaScript?


JavaScript is placed using <script> tag as follows or script can be
taken from a file, which typically contains extension .js.

<script ="text/javascript">

</script>

<script type="text/javascript" src="events.js">


</script>

Srikanth Technologies
Java EE (Web Applications I) 9
Variable Declaration
Though variables need not be declared, it can be done using var
keyword as follows:

var amount, name;


Amount = 1000;
Name = Srikanth;

A variable declared inside the function can be accessed only from


that function.
A variable declared outside all functions can be accessed from
any function.
Variable life time begins with declaration (or assignment) and
ends when page is unloaded.

Operators
The following table lists operators in different categories in
JavaScript.

Arithmetic Relational Logical Miscellaneous


+ == && + (Concatenation)
- != || instanceof
* > ! this
/ < typeof
% >= new
++ <=
-- ===
!==

/* === checks for same data types also */


x=5
y="5"
x==y returns true
x===y returns false

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; break
case 2: code; break
default: code;
}

for loop
for (var=startvalue;var<=endvalue;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) 11
Events
Events represent actions that JavaScript can react to. Event
handlers are JavaScript functions that handle events.

Event The event occurs when...


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
Java EE (Web Applications I) 12
js1.html
1: <html><head>
2: <script type="text/javascript"
3: language="javascript">
4: function check() {
5: if (txtname.value == "") {
6: alert("Please enter your name");
7: txtname.focus();
8: }
9: }
10: function fun() {
11: var res = confirm("Do you want to continue?");
12: if ( res == true)
13: alert("Thank you");
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. They are
provided by global object.

isNaN(expr)
parseFloat(string)
parseInt(string)
eval(expr)

Srikanth Technologies
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.

var mycars=new Array()


mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
var mycars=new Array("Saab","Volvo","BMW")
document.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. 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
Java EE (Web Applications I) 14
1: <html><head>
2: <script type="text/javascript">
3: var a = new Array();
4: a[0] = "M.S.Dhoni";
5: a[1] = "Suresh Raina"
6: a[2] = "Yuvraj Singh";
7: a.sort();
8: document.write(a);
9: for ( var n in a)
10: document.write("<br>" + a[n] +":"+ a[n].length);
11:
12: var b = new Array();
13: b[0] = "Dhoni";
14: b[1] = "Yuvraj";
15: b.push("Virat");
16: document.write("<p>" + a.concat(b));
17: </script>
18: </head>
19: <body></body>
20: </html>

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. The Document object is
part of the Window object and is accessed through the
window.document property.

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) 16
writeln() Identical to the write() method, with the
addition of writing a new line character
after each expression.

Window object
The Window object is the top level object in the JavaScript
hierarchy. The Window object represents a browser window.

frames[] collection represents frames in 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,lang) number of milliseconds
clearTimeout() Clears timeout set earlier
setInterval Will wait for specified number of milliseconds,
(code, ms) and then execute function, and it will continue
to execute the function, once at every given
time-interval.

Srikanth Technologies
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.

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. These URLs are the URLs the user
has visited within a browser window.

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.

Srikanth Technologies
Java EE (Web Applications I) 18
Register.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.

1: <html>
2: <head>
3: <title>Registration</title>
4: <script type="text/javascript">
5: function validate() {
6: var pwd = document.getElementById("pwd");
7: var pwd2 = document.getElementById("pwd2");
8:
9: if ( pwd.value != pwd2.value){
10: alert("Password and Re-entered password
11: do not match!");
12: pwd2.focus();
13: return false;
14: }
15: return true; // everything is fine
16: }
17: </script>
18: </head>
19: <body style="background-color:#eeeeee">
20: <form action="register.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
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. Web is
consisting of Web Server and Web Client.
Client makes a request to server and server then processes the
request and sends response back to client.
When the script (code) is executed on the server, it is called as
server-side scripting. If script is executed on the client, it is
called as client-side scripting.
Server-side scripting is done using Java Servlets and JSP. Client-
side script is done using JavaScript.

Http Request

Web Browser Web Server


Http Response

What is web server?


It is the software that takes request from Web client (Browser),
processes the request and sends response to client. It also
provides the framework and runtime environment.
They are also called as Web Containers.
Some of the examples for Web Servers are Tomcat, Apache Web
Server, and WebLogic Server.
Java EE (Java Enterprise Edition) provides specifications for Web
Containers.

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.
Internet Explorer, Mozilla Firefox and Netscape Navigator are
widely used Web Browsers.
Browser is also responsible for running client-side scripting
written in JavaScript.

Srikanth Technologies
Java EE (Web Applications I) 21
Internet vs. Intranet Application
When a web application runs in Internet, it is called as Internet
application.
When a web application runs inside local area network (LAN), it
is called as Intranet application.
Internet applications are used by client from different parts of
the world, whereas Intranet applications are used only by users
of the intranet.

Http Protocol
HTTP is an application protocol implemented on TCP/IP.
It is a request and response protocol.
Client sends a request to receive information from server or
invoke a process on the server.
It is stateless protocol client and server do not maintain
information about each other.

JavaServer Pages
Standard Tag Library (JSTL)
JavaServer Faces
JavaServer Pages

JavaServlet

Srikanth Technologies
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.
Java Servlet is a Java class that is loaded into memory of web
server. Its methods are called by web server.
Java Servlets are java programs that reside on Web Server and
get executed on web server.
Just like an Applet a Servlet is a Java class that is executed by
Web Server upon a request from client.
Servlets form server-side scripting. Servlets are platform
independent server-side programs that allow you to build web
applications.
Servlets are totally managed by Web Server and run inside JVM
of the Web Server. They are invoked by client using a URL.
demo

.html and .jsp files

WEB-INF

classes

.class files
and packages

lib

.jar files

web.xml

Web Containers
A web container is a Java Runtime providing an implementation of
Java Servlet API and JSP. The web container is responsible for
initializing, invoking and managing the life cycle of Java Servlets and
Java Server Pages.

The following are different types of Web Containers:


Srikanth Technologies
Java EE (Web Applications I) 23
Web Container in J2EE Application Server
Commercial Java EE application server such as Weblogic Server,
Glassfish, JBoss and WebSphere application server include web
container built in.

Web container built into web server


In this a web server contains web container. This is the case with
Apache TomCat etc.

Web container in a separate runtime


This is the case with non-Java EE world. Web container (JVM) is
plugged into a web server that otherwise doesnt support java. Web
server such as IIS (Internet Information Server) from Microsoft
requires this type of web container to run Servlets.

Creating a Servlet
Creating a servlet is creating a class and annotating it with
@WebServlet.

01: package servlets;


02: import java.io.IOException;
03: import java.io.PrintWriter;
04: import java.util.Date;
05: import javax.servlet.ServletException;
06: import javax.servlet.annotation.WebServlet;
07: import javax.servlet.http.*;
08:
09: @WebServlet(name="DateTimeServlet",
10: urlPatterns={"/datetime"})
11: public class DateTimeServlet extends HttpServlet {
12: @Override
13: protected void doGet(HttpServletRequest request,
14: HttpServletResponse response)
15: throws ServletException, IOException {
16: response.setContentType("text/html");
17: PrintWriter pw = response.getWriter();
18: pw.println( new Date().toString());
19: }
20: }

Srikanth Technologies
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. 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.

localhostName of the system on which web server is running.


8888 The port number at which server is running. This can
vary depending on your web server.
webdemo The name of the application.
datetime The URL Pattern related to servlet.

Srikanth Technologies
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. The following is
the structure of the HTTP request.
Http Request Requested URI
Method

GET URI HTTP/1.1


Headers
Header: value sent by
Header: value Browser
Blank line
separating headers
from body Body

Request Body

Get request vs. Post request


An http request could be either of type GET or POST.
In case of GET request, data passed from HTML form is passed
along with URL of the request.
The following URL contains data passed from client using GET
request.

http://localhost:8888/webdemo/list?price=500&qty=10

As data is passed along with URL, the amount of data that can be
passed is limited. Also confidential data cannot be passed as it
becomes visible to others.
In case of POST request, data is passed along with body of HTTP
request.
The default http request is GET request.

Srikanth Technologies
Java EE (Web Applications I) 26
You can specify which type of request you want using method
attribute of <form> tag.

Http Response
The response sent from server to client is called HTTP response. It
typically contains status, headers and HTML to be displayed by
browser.

Status Code
Brief description

HTTP/1.1 200 OK
Headers
Header: value sent to
Header: value Browser by
Blank line
Server
separating headers
from body Body

Response Body

currency.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
Java EE (Web Applications I) 27

CurrencyServlet.java
01: package servlets;
02:
03: import java.io.IOException;
04: import java.io.PrintWriter;
05: import javax.servlet.ServletException;
06: import javax.servlet.annotation.WebServlet;
07: import javax.servlet.http.*;
08:
09: @WebServlet(name = "CurrencyServlet",
10: urlPatterns = {"/currency"})
11: public class CurrencyServlet extends HttpServlet {
12: public static double RATE = 66;
13: protected void doGet(HttpServletRequest request,
14: HttpServletResponse response)
15: throws ServletException, IOException {
16: response.setContentType("text/html;charset=UTF-8");
17: PrintWriter out = response.getWriter();
18: String samount = request.getParameter("amount");
19: if (samount != null) {
20: double amount = Double.parseDouble(samount);
21: double usd = amount / RATE;
22: out.println(" USD = " + usd);
23: } else {
24: out.println("<h3>Amount is required!</h3>");
25: }
26: }
27: }

Note: You must call currency.html first and NOT CurrencyServlet


using /currency URL pattern. CurrencyServlet expects request
parameters which are provided by currency.html page.

Srikanth Technologies
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. When a request is mapped to a servlet,
the container performs the following steps.

If an instance of the servlet does not exist, the web container


Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init()
method.
Invokes the service() method, passing request and response
objects.
When container wants to remove servlet from memory, it calls
destroy() method.

Initializing a Servlet
After the web container loads and instantiates the servlet class and
before it delivers requests from clients, the web container initializes
the servlet. You can override the init method of the Servlet
interface. A servlet that cannot complete its initialization process
should throw UnavailableException.

Writing Service Methods


The service provided by a servlet is implemented in the service
method of a GenericServlet, in the doMethod methods (where
method can take the value Get, Delete, Options, Post, Put, or
Trace) of an HttpServlet object.
For HTTP servlets, the correct procedure for populating the
response is to first retrieve an output stream from the response,
then fill in the response headers, and finally write any body
content to the output stream.
Response headers must always be set before the response has
been committed. Any attempt to set or add headers after the
response has been committed will be ignored by the web
container.

Srikanth Technologies
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.
Each Servlet must directly or indirectly implement this interface.

Method Meaning
void init It is invoked by web container after the
(ServletConfig config) servlet is instantiated.
void service This is called whenever a request is
(ServletRequest req, made by client for this servlet. This
ServletResponse res) method in turn may call other methods
such as doPost and doGet in
HttpServlet.
void destroy() This method is called before removing
a servlet from web container.
ServletConfig This returns the ServletConfig that was
getServletConfig() passed to the servlet during init()
method.

GenericServlet Class
It provides the basic implementation of Servlet interface. This is an
abstract class. All sub classes of this class must implement Service
method. It has the following additional methods in addition to
Servlet interface that it implements.

void init()
void log(String message)

Srikanth Technologies
Java EE (Web Applications I) 30
HttpServlet class
This class extends GenericServlet class and provides Http-specific
implementation of the Servlet interface. This class provides the
following methods that you most likely override:

void doGet(HttpServletRequest req, HttpServletResponse res)


void doPost(HttpServletRequest req,HttpServletResponse res)
<<Interface>>
GenericServlet
Servlet

HttpServlet

SimpleHttpServlet

ServletRequest Interface
An object of this interface is passed when web container calls
service() method.

Method Description
Object getAttribute Returns value of the given attribute
(String name) or null, if attribute is not present.
Enumeration Returns the names of all attributes
getAttributeNames() contained in the request.
void setAttribute Sets the named attribute to the
(String name,Object value) given value.
void removeAttribute Removes the named attribute from
(String name) the list of attributes.
String getParameter Returns the value of the named
(String name) parameter. The name is case
sensitive.
Srikanth Technologies
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, or null if the
parameter does not exist.
String getRemoteAddr() Returns the address of the client
making the request.
String getRemoteHost() Returns the name of the server from
where client is making the request.
RequestDispatcher Returns an object of
getRequestDispatcher RequestDispatcher for the given
(String path) path. Using request dispatcher you
can forward request to the required
path.

HttpServletRequest Interface
This interface extends ServletRequest and adds methods related to
Http protocol.

Method Description
Cookie[] Returns all cookies passed from client along
getCookies() with the request.
String getHeader Returns the value of the given header field.
(String name)
Enumeration Returns names of all the header fields of the
getHeaderNames() request.
String getMethod() Returns the type of HTTP request made - GET,
POST etc.
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.
HttpSession Returns the session associated with the
getSession(boolean) request. It creates a new session if one
doesn't exist when the parameter is true.
StringBuffer Reconstructs the URL the client used to make
getRequestURL() the request.
Srikanth Technologies
Java EE (Web Applications I) 32

01: // get the list of request headers along with values


02: Enumeration e = request.getHeaderNames();
03: String name,value;
04: while ( e.hasMoreElements()) {
05: name = (String) e.nextElement();
06: value = request.getHeader(name);
07: out.println(name + " : " + value + "<br/>");
08: }

ServletResponse interface
Provides means for servlet to send response to client.

Method Description
void flushBuffer() Forces any content in the buffer to be
written to the client.
void reset() Clears any data that exists in the buffer as
well as the status code and headers.
void resetBuffer() Clears the content of the underlying buffer
in the response without clearing headers or
status code.
void setContentType Sets the content type of the response
(String type) being sent to the client.
PrintWriter getWriter() Returns writer, which can be used to write
to client.

HttpServletResponse Interface
Extends the ServletResponse interface to provide HTTP-specific
functionality in sending a response. For example, it has methods to
access HTTP headers and cookies.

Method Description
void addCookie (Cookie) Adds the specified cookie to the
response.
void addHeader Adds a response header with the given
(String name,String value) name and value.
boolean containsHeader Returns a boolean indicating whether

Srikanth Technologies
Java EE (Web Applications I) 33
(String name) the named header is already set.
void sendError (int sc) Sends an error response to the client
using the specified status code and
clearing the buffer.
void sendRedirect Sends a redirect response to the client
(String location) using the specified URL.
void setHeader Sets a response header with the given
(String name,String value) name and value.
void setStatus(int sc) Sets the status code for this response.

The following table shows some of the common status codes and
their meaning.

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. This means that there
is always a round trip to the client side. To pass information
between the original servlet and the next request, you normally
pass the information as a query string appended to the destination
URL.

Srikanth Technologies
Java EE (Web Applications I) 34

ServletConfig Interface
It contains methods that provide information about Servlet
configuration such as initialization parameters.

This interface is implemented by GenericServlet. 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.

Method Meaning
String getInitParameter Returns the value of the initialization
(String name) parameter whose name is supplied.
Initialization parameters are supplied
through web.xml.
Enumeration Returns the names of all initialization
getInitParameterNames() parameters.
ServletContext Returns ServletContext object associated
getServletContext() with the web application. Each servlet
belongs to an application and each
application is associated with a servlet
context.

Srikanth Technologies
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
Java EE (Web Applications I) 40
Session Tracking
Many applications require that a series of requests from a client be
associated with one another. Web-based applications are responsible
for maintaining such state, called a session, because HTTP is
stateless. You can associate object-valued attributes with a session
by name. You can use any of the following mechanisms to maintain
a session.

Cookies
URL rewriting
Hidden form fields

All of the above involve passing an identifier between the client and
the server. The identifier can be maintained on the client as a
cookie, or the web component can include the identifier in every URL
that is returned to the client.

Sessions are represented by an HttpSession object. You access a


session by calling the getSession() method of a request object.

If your application uses session objects, you must ensure that


session tracking is enabled by having the application rewrite URLs
whenever the client turns off cookies. You do this by calling the
responses encodeURL(URL) method on all URLs returned by a
servlet. This method includes the session ID in the URL only if
cookies are disabled; otherwise, it returns the URL unchanged.

out.println("<ahref=" +
response.encodeURL(request.getContextPath()+"/list") +
">List</a>");

Srikanth Technologies
Java EE (Web Applications I) 41

HttpSession Interface
Provides methods to access session object and manipulate 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.
Enumeration Returns Enumeration of String objects
getAttributeNames() containing the names of all the objects
bound to this session.
long getCreationTime() Returns the time when this session was
created, measured in milliseconds since
midnight January 1, 1970 GMT.
String getId() Returns a string containing the unique
identifier assigned to this session.
ServletContext Returns the ServletContext to which this
getServletContext() session belongs.
void invalidate() Invalidates this session then unbinds any
objects bound to it.
void removeAttribute Removes the object bound with the
(String name) specified name from this session.
void setAttribute Binds an object to this session, using the
(String name,Object val) name specified.
void Specifies the time, in seconds, between
Srikanth Technologies
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
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.
In case of forward(), if output exists in the response buffer that
has not been committed, the buffer must be cleared before the
target servlet's service method is called.
In case of include(), the included servlet cannot set headers or
call any method that affects the header of the response.

Srikanth Technologies
Java EE (Web Applications I) 48

FirstServlet 1
Code
2
rd.include()
6 Client
Code
3 4
SecondServlet
5

1. Client Request for FirstServlet


2. FirstServlet sends some response to Client
3. FirstServlet calls SecondServlet
4. SecondServlet response goes to client
5. Control returns to FirstServlet
6. Response from FirstServlet goes to Client

Request Dispatching vs. sendRedirect()


The following are the differences between sendRedirect() and
request dispatching.

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 doesnt change in browser
Request data is transferred from caller to called

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. To use these listener objects you must define and
specify the listener class, which implements a listener interface.

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) 50
SessionsCountListener.java
01: package listeners;
02: import javax.servlet.ServletContext;
03: import javax.servlet.ServletContextEvent;
04: import javax.servlet.ServletContextListener;
05: import javax.servlet.annotation.WebListener;
06: import javax.servlet.http.HttpSessionEvent;
07: import javax.servlet.http.HttpSessionListener;
08:
09: @WebListener
10: public class SessionCountListener implements
11: ServletContextListener, HttpSessionListener {
12: @Override
13: public void contextInitialized(ServletContextEvent sce) {
14: ServletContext ctx = sce.getServletContext();
15: ctx.setAttribute("count", 0); // 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.getSession().getServletContext();
25: Integer count = (Integer) ctx.getAttribute("count");
26: ctx.setAttribute("count", count + 1);
27: }
28:
29: @Override
30: public void sessionDestroyed(HttpSessionEvent se) {
31: ServletContext ctx =
32: se.getSession().getServletContext();
33: Integer count = (Integer) ctx.getAttribute("count");
34: ctx.setAttribute("count", count - 1);
35: }
36: }

Srikanth Technologies
Java EE (Web Applications I) 51
DisplaySessionsCountServlet.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 = "DisplaySessionsCountServlet",
07: urlPatterns = {"/sessionscount"})
08: public class DisplaySesssionsCountServlet
09: extends HttpServlet {
10: @Override
11: protected void doGet(HttpServletRequest request,
12: HttpServletResponse response)
13: throws ServletException, IOException {
14: response.setContentType("text/html;charset=UTF-8");
15: PrintWriter out = response.getWriter();
16: Integer obj = (Integer) request.getSession().
17: getServletContext().getAttribute("count");
18: out.println("<h1>Session Count:"+obj.intValue()+"</h1>");
19: out.close();
20: }
21: }

Srikanth Technologies
Java EE (Web Applications I) 52
Filters
Filter enables you to intercept a request before it reaches a
resource. A filter gives you access to the HttpServletRequest
and the HttpServletResponse objects before they are passed in
to a servlet.
You can write a filter that records all incoming requests and logs
the IP addresses of the computers from which the requests
originate. You also can use a filter as an encryption and
decryption device. Other uses include user authentication, data
compression, user input validation, and so on.

Filter Interface
It must be implemented by every filter. The life cycle of a filter is
represented by this interface's three methods:

public void init(FilterConfig filterConfig)


public void doFilter(HttpServletRequest reqest,
HttpServletResponse res,FilterChain chain)
public void destroy()

FilterConfig Interface
It is passed as parameter to init() method in Filter.

Srikanth Technologies
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, or, if the filter is the last in the chain, to invoke the next
resource (Servlet).

void doFilter (HttpServletRequest req, HttpServletResponse res)

LogFilter.java
01: package filters;
02: import java.io.IOException;
03: import javax.servlet.*;
04: import javax.servlet.annotation.WebFilter;
05:
06: @WebFilter(filterName = "LogFilter", 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,
17: ServletResponse response,FilterChain chain)
18: throws IOException, ServletException {
19: System.out.println(request.getRemoteHost());
20: chain.doFilter(request, response);
21: }
22: }

Srikanth Technologies
Java EE (Web Applications I) 54
Dynamically adding Servlet
Starting from Servlets 3.0, it is possible to add a servlet
dynamically.
Method addServlet() in ServletContext interface is used to add
a servlet dynamically.
Method addServlet() returns ServletRegistration object, which
contains addMapping() method to associate mapping with
servlet.

The following methods of ServletContext are used to add servlet or


filter dynamically.

addServlet(String servletName,
Class <? extends Servlet>servletClass)
addFilter(String filterName,
Class <? extends Filter> filterClass)

The following code shows how to add a servlet dynamically. First


create a class (servlet), which is neither declared in web.xml nor
associated with annotation.

01: package servlets;


02: import java.io.*;
03: import javax.servlet.ServletException;
04: import javax.servlet.http.*;
05: public class DynamicServlet extends HttpServlet {
06: protected void doGet(HttpServletRequest request,
07: HttpServletResponse response)
08: throws ServletException, IOException {
09: response.setContentType("text/html");
10: PrintWriter out = response.getWriter();
11: out.println("<h1>Dynamic Servlet</h1>");
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.

Srikanth Technologies
Java EE (Web Applications I) 55
AddServletListener.java
01: import javax.servlet.*;
02: import javax.servlet.annotation.WebListener;
03: import javax.servlet.http.HttpSessionEvent;
04: import javax.servlet.http.HttpSessionListener;
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"};
11: ServletContext context = sce.getServletContext();
12: ServletRegistration sr = context.addServlet
13: ("DynamicServlet","servlets.DynamicServlet");
14: sr.addMapping(urlPatterns);
15: }
16: public void contextDestroyed(ServletContextEvent sce){}
17: }

Srikanth Technologies
Java EE (Web Applications I) 56
Web Fragments
In previous versions of Java EE, web.xml is not modular. All the
configuration details about one particular application are included
in one single web.xml file. When one or more frameworks are
used, there is no way but to edit the web.xml.
Servlet 3.0 specification addresses this issue by introducing web
fragments.
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.xml in the META-INF
directory of the jar file. During the application startup, it is the
responsibility of the Container to scan the information that is
found in the /META-INF/web-fragment.xml file available in the
application's classpath.
A web fragment can be considered as one of the segments of the
whole web.xml and it can be imagined that one or more web
fragments constitute a single web.xml file. A web-fragment can
include all the possible elements that are applicable for the
web.xml. Consider a sample web-fragment file.

web-fragment.xml
01: <web-fragment>
02: <servlet>
03: <servlet-name>myFrameworkSpecificServlet</servlet-name>
04: <servlet-class>myFramework.myServlet </servlet-class>
05: </servlet>
06: <listener>
07: <listener-class>myFramework.myListener</listener-class>
08: </listener>
09: </web-fragment>

Srikanth Technologies
Java EE (Web Applications I) 57
Uploading Files
Starting from Servlets 3.0, if a request is of type multipart/form-
data and if the servlet handling the request is annotated using the
@MultipartConfig, the HttpServletRequest can make available the
various parts of the multipart request via the following methods.

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.

upload.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
Java EE (Web Applications I) 58
UploadServlet.java
01: package servlets;
02: import java.io.*;
03: import java.util.Scanner;
04: import javax.servlet.ServletException;
05: import javax.servlet.annotation.MultipartConfig;
06: import javax.servlet.annotation.WebServlet;
07: import javax.servlet.http.*;
08: @WebServlet(name="UploadServlet", urlPatterns={"/upload"})
09: @MultipartConfig
10: public class UploadServlet extends HttpServlet {
11: protected void doPost(HttpServletRequest request,
12: HttpServletResponse response)
13: throws ServletException, IOException {
14: response.setContentType("text/html;charset=UTF-8");
15: PrintWriter out = response.getWriter();
16: try {
17: Part p1 = request.getPart("file");
18: InputStream is = p1.getInputStream();
19:
20: Part p2 = request.getPart("filename");
21: Scanner s = new Scanner(p2.getInputStream());
22: String filename = s.nextLine();
23:
24: // save file in server
25: String outputfile=
26: getServletContext().getRealPath(filename);
27: FileOutputStream os=new FileOutputStream (outputfile);
28:
29: int ch = is.read();
30: while (ch != -1) {
31: os.write(ch);
32: ch = is.read();
33: }
34: os.close();
35: out.println("<h3>File uploaded successfully!</h3>");
36: } finally {
37: out.close();
38: }
39: }
40: }

Srikanth Technologies
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.
A JSP page is a text document that contains two types of text:
Static data, which can be expressed in any text-based format
(such as HTML, WML, and XML) and JSP elements, which
construct dynamic content.
Provides expression language for accessing server-side objects.
JSP specifications extend the Java Servlet API.

01: <html>
02: <body>
03: <h2>
04: Current Date and Time:
05: <%
06: java.util.Date cd = new java.util.Date();
07: out.println(cd.toString());
08: %>
09: </h2>
10: </body>
11: </html>

Srikanth Technologies
Java EE (Web Applications I) 60
Life Cycle of a JSP Page
A JSP page services requests as a servlet. Thus, the life cycle of
JSP pages is determined by Java Servlet technology.
When a request is mapped to a JSP page, the web container first
checks whether the JSP pages servlet is older than the JSP page.
If the servlet is older, the web container translates the JSP page
into a servlet class and compiles the class.

JSP elements are treated as follows:

Directives Are used to control how the web container


translates and executes the JSP page.
Scripting elements Are inserted into the JSP pages servlet
class.
Expression language Expressions are passed to JSP expression
evaluator.
jsp[set|get]Property Elements are converted into method calls
to JavaBeans components.
jsp[include|forward] Elements are converted into invocations of
the Java Servlet API.
Custom tags Are converted into calls to the tag handler
that implements the custom tag.

After the page has been translated and compiled, the JSP pages
servlet follows the servlet life cycle:

If an instance of the JSP pages servlet does not exist, the


container loads the JSP pages servlet class; instantiates an
instance of the servlet class then initializes the servlet instance
by calling the jspInit method.
The container invokes the _jspService method, passing request
and response objects.
If the container needs to remove the JSP pages servlet, it calls
the jspDestroy method.

Srikanth Technologies
Java EE (Web Applications I) 61
JspPage interface
Every JSP Servlet class must implement JspPage interface
Extends Servlet interface
Contains two methods
void jspInit() - same as init()
void jspDestroy() - same as destroy()

HttpJspPage Interface
Contains one method jspService(), which is called by the JSP
container to generate the content of the JSP page.

void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException

It is up to the web container to implement HttpJspPage interface.

HttpJspPage
jspInit()
jspDestroy()
_jspService(..)

HttpJspBase

currentdate_jsp

jspInit()
_jspService()

Srikanth Technologies
Java EE (Web Applications I) 62
Implicit Objects
The following implicit objects can be used in JSPs.

Object Description
pageContext The context for the JSP page. Provides access to
various objects including implicit objects.
servletContext The context for the JSP pages servlet and any web
components contained in the same application.
session The session object for the client.
request The request triggering the execution of the JSP
page.
response The response returned by the JSP page.
out Writes the given data to output stream of client.
config Allows access to ServletConfig for JSP page.

Directive
Specifies what JSP container must do.
Directives start with @character within the tag.
There are three directives page, include and taglib.

Declarations
Declaration is a block of Java code that is used to define class-
wide variables and methods in the generated class file.
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;
04: public void m1()
05: { }
06: %>

Srikanth Technologies
Java EE (Web Applications I) 63
Scriptlets
Scriptlet is the block of Java code that is executed when JSP is
executed. It is enclosed in <% and %>
Scriptlets are placed in jspService() method.

01: <%
02: out.println("Hello JSP World");
03: %>

Expressions
An expression is a shorthand notation for a scriptlet that outputs
a value in the response stream back to the client.
It is enclosed in <%= and %>

01: <%=new Date()%>


02: <input type=text value=<%=request.getParameter("age")%>
03: name=age>

Comments in JSP
Comments in JSP are given using <%-- and --%>.

<%-- comment --%>

HTML form invoking JSP


The following example shows how to invoke JSP from HTML Form
and send data.

wish.html
01: <html><body>
02: <form action="wish.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
Java EE (Web Applications I) 64
wish.jsp
01: <html>
02: <body bgcolor="tan">
03: <%
04: String name = request.getParameter("uname");
05: if (name == null ) // no parameter passed
06: out.println("No name passed");
07: else
08: if (name.equals("")) // empty string was passed
09: out.println("Empty Name");
10: else
11: out.println(name);
12: %>
13: </body>
14: </html>

Srikanth Technologies
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. When
JSP is called first, it displays form. When user submits form, it calls
the same JSP again. It is important to differentiate the first call
from other calls (post back JSP calling itself).

even.jsp
01: <html>
02: <body>
03: <form action="even.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.getParameter("num");
12: if ( num != null && num.length() > 0 ){
13: int n = Integer.parseInt(num);
14: if ( n % 2 == 0 )
15: out.println("<h3>Even Number </h3>");
16: else
17: out.println("<h3>Odd Number </h3>");
18: }
19: %>
20: </body>
21: </html>

Note: Expression ${param.num} refers to request parameter


num. It is taken from EL (expression language).

Srikanth Technologies
Java EE (Web Applications I) 66
Accessing Database from Web Applications
Accessing database from a JSP/Servlet needs the following steps:

Make sure .jar file of JDBC driver (like ojdbc6.jar) is placed in


/WEB-INF/lib directory
Import package java.sql and (if required) javax.sql etc.
The rest of the process is same as what we have seen in JDBC
module

listdept.jsp
01: <html>
02: <body>
03: <center>
04: <h2>List of Departments </h2>
05: <%
06: javax.sql.rowset.CachedRowSet rs =
07: new oracle.jdbc.rowset.OracleCachedRowSet();
08: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
09: rs.setUsername("hr");
10: rs.setPassword("hr");
11: rs.setCommand("select * from departments");
12: rs.execute();
13: %>
14: <table border=1 cellpadding=5>
15: <tr><th>Id</th><th>Name </th></tr>
16: <%
17: while ( rs.next()){
18: %>
19: <tr><td> <%= rs.getString(1) %> </td>
20: <td> <%= rs.getString(2) %></td></tr>
21: <%
22: } // end of while
23: rs.close();
24: %>
25: </table>
26: </center>
27: </body>
28: </html>

Srikanth Technologies
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, read-only, or write-only


Simple, which means it contains a single value, or indexed, which
means it represents an array of values
A property does not have to be implemented by an instance
variable. It must simply be accessible using public methods that
conform to the following conventions:

For each readable property, the bean must have a method of form

type getProperty() { ... }

For each writable property, the bean must have a method of the
form

setProperty(type pc) { ... }

Srikanth Technologies
Java EE (Web Applications I) 68
Using JavaBeans with JSP
In order to use a JavaBean in JSP, 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. It specifies class, scope and id for Java Bean.

<jsp:useBean id="name" scope="scope"


class="fullyqualifiedclassname"/>

<jsp:useBean id="count" scope="page" class="test.Count" />

The above example creates an object of test.Count class and


assigns id count. Its life time is the execution of the page.
Remember the class Count is to be placed in package test. This
package starts with classes directory (/WEB-INF/classes).

Once a bean is included in JSP, throughout the page the bean can
be accessed using id of the bean. The scope of the bean can be any
of the following:

Scope Meaning
page Objects are available throughout the page. They are
released when request is over or another page is
invoked.
request Objects are available as long as the request is being
processed.
session Objects are available in the session in which they are
created.
application Objects are available in any session that is in the same
application as the session that created the bean.

Srikanth Technologies
Java EE (Web Applications I) 69
Session Object

An object of UserBean
with id user

login.jsp home.jsp

<jsp:useBean id=user <jsp:useBean id=user


scope=session scope=session
class=demo.UserBean /> class=demo.UserBean />

<jsp:setProperty >
It is used to set property of the bean to the given value or the
specified parameter of the form.

<jsp:setProperty name="beanname" property="propertyname|*"


value="value" | param="parametername" />

Attribute Meaning
Name Name of the bean defined by <jsp:useBean> tag.
property Name of the property to be changed. If the property is
set to * then the tag iterates over all the parameters of
the request, matching parameter names and value types
to bean properties, and setting each matched property
to the value of the matching parameter.
param Specifies the name of the request parameter whose
value is to be assigned to a bean property.
value Value to assign to the bean property. This cannot be
given if param is already given.

<jsp:setProperty name=emp property=* />


<jsp:setProperty name=emp property=bs param=sal />
<jsp:setProperty name=emp property=bs value=12000 />

Srikanth Technologies
Java EE (Web Applications I) 70
<jsp:getProperty>
It is used to retrieve the value of the parameter.

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

<jsp:getProperty name="emp" property="sal" />

JobBean.java
01: package beans;
02: import java.sql.*;
03: public class JobBean {
04: private String id, title;
05: public void addJob() throws Exception {
06: Class.forName("oracle.jdbc.driver.OracleDriver");
07: try (Connection con = DriverManager.getConnection
08: ("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
09: PreparedStatement ps = con.prepareStatement
10: ("insert into jobs values(?,?,null,null)")) {
11: ps.setString(1, getId());
12: ps.setString(2, getTitle());
13: ps.executeUpdate();
14: }
15: }
16: public String getId() {
17: return id;
18: }
19: public void setId(String id) {
20: this.id = id;
21: }
22: public String getTitle() {
23: return title;
24: }
25: public void setTitle(String title) {
26: this.title = title;
27: }
28: }

Srikanth Technologies
Java EE (Web Applications I) 71
addjob.html
01: <html>
02: <head>
03: <title>Add Job</title>
04: </head>
05: <body>
06: <form action="addjob.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.jsp
01: <html>
02: <body>
03: <jsp:useBean class="beans.JobBean"
04: scope="page" id="job" />
05: <jsp:setProperty name="job" property="*"/>
06: <%
07: try {
08: job.addJob();
09: out.println("Added Successfully!");
10: }
11: catch(Exception ex) {
12: out.println(ex.getMessage());
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.
The included page has access only to JspWriter object, and it
cannot set headers or Cookies.
If page output is buffered then the buffer is flushed prior to the
inclusion.

Srikanth Technologies
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.


The included page can access both the original and the new
parameters.
If parameter names are same, the old values are kept intact, but
the new values take precedence over existing values.

<jsp:include page=second.html/>

<jsp:forward>
Allows the request to be forwarded to another JSP, a servlet, or a
static resource.

<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. Execution in the
current JSP stops when it encounters a <jsp:forward> tag. The
buffer is cleared, and the request is modified to augment
additionally specified parameter using <jsp:param>.

Srikanth Technologies
Java EE (Web Applications I) 73
@Include directive
It is used to include the content of the specified file at translation
time. So even if the contents of the file included after calling JSP
are compiled, the changes are not incorporated in to JSP.

<%@ include file=filename %>

caller.jsp?p1=10&p2=20
01: <h1>Caller Page </h1>
02: P1 = ${param.p1} <p/>
03: P2 = ${param.p2} <p/>
04: <%
05: request.setAttribute("color","Red");
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
Java EE (Web Applications I) 74
called.jsp
01: <h1>Called Page </h1>
02: P1 = ${param.p1}
03: <p/>
04: P2 = ${param.p2}
05: <p/>
06: P3 = ${param.p3}
07: <p/>
08: Color = ${requestScope.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
Java EE (Web Applications I) 75
Expression Language - EL
Expression language is supported from JSP 2.0
Provides shorthand language for accessing values that are stored
in standard locations such as session, request, cookies etc.

Object Meaning
page This is a synonym to this object in JSP page.
param Maps a request parameter name to a single
value.
paramValues Maps a request parameter name to an array of
values.
header Maps a request header name to a single value.
headerValues Maps a request header name to an array of
values.
cookie Maps a cookie name to a single cookie.
initParam Maps a context initialization parameter name to a
single value.
pageScope Maps page-scoped variable names to their values.
requestScope Maps request-scoped variable names to their
values.
sessionScope Maps session-scoped variable names to their
values.
applicationScope Maps application-scoped variable names to their
values.

Expression language supports the following capabilities:

Concise access to attributes in objects like session, application


Shorthand notation for bean properties
Simple access to collection elements
Provides arithmetic, relational, logical operators to manipulate
objects within EL
Automatic type conversion
In most cases, missing values result in empty strings, and not
exceptions

Srikanth Technologies
Java EE (Web Applications I) 76
Operators in EL
The following are different types of operators available in EL.

Arithmetic +, -, * , / , %
Relational ==, !=, < , >, >=, <=
Logical &&, ||, !
Empty Empty
Conditional condition ? expression1 : expression2
expression

01: <jsp:useBean id="user" class="beans.User" scope="page"/>


02: <%
03: request.setAttribute("name","Srikanth");
04: %>
05: ${name}
06: ${user.name}
07: ${param.name}
08: <p>
09: ${header["User-Agent"]}
10: <p>
11: ${cookie.JSESSIONID.value}
12:
13: ${param.n1 + param.n2}
14: <p>
15: ${param.n1 == param.n2}
16: <p>
17: ${param.n1 > param.n2?"First is big":"Second is big"}

Srikanth Technologies
Java EE (Web Applications I) 77
Error Handling in JSP
The following are different types of errors that might occur in a JSP
page.

Translation time errors


Errors that occur during translation (conversion) of JSP to Servlet
are called as translation errors. They result in Internal Servlet Error
(error code 500).

Runtime Errors
Errors that occur when translated servlet is running are called as
runtime errors. These errors can be handled using exception
handling of Java language or handled using error directive and error
page.

To handle runtime errors using 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.jsp
01: <html>
02: <body>
03: <%@page errorPage="error.jsp"%>
04: <%
05: int n;
06: n = Integer.parseInt(request.getParameter("num"));
07: out.println(n);
08: %>
09: </body>
10: </html>

Create JSP that will handle errors. This page must use
isErrorPage attribute of page directive.

Srikanth Technologies
Java EE (Web Applications I) 78
error.jsp
01: <%@page isErrorPage="true" %>
02: <html>
03: <body>
04: Error : <%= exception.getMessage()%> <p/>
05: <a href="javascript:history.back()">Back </a>
06: </body>
07: </html>

Error Page
Is used to provide a more user-friendly message to user.
Contains access to exception object, through which the attributes
of most recent exception can be obtained.
Is automatically invoked whenever an exception occurs in the
page that referred to it.
Defined using <%@ page isErrorPage=true %>

Page directive
Page directive defines attributes that affect the process of the whole
page. The following are the attributes of page directive.

Attribute Meaning
import Imports the packages specified. Use comma to
separate multiple packages.
session Specifies if the page participates in an HTTP session.
buffer Specifies whether output is buffered or not and the
size of the buffer.
isErrorPage Indicates if the current JSP page is to handle errors.
errorPage Specifies the name of the JSP to be invoked when an
error occurs.
contentType Specifies the MIME type for the response of the page.

<%@ page import="java.util.*,java.io.*" session="false" %>

Srikanth Technologies
Java EE (Web Applications I) 79
JSP Tag Extensions Custom Tags
Tag extensions are user-defined tags (custom tags) in JSP.
Custom tags, also known as JSP tag extensions (because they
extend the set of built-in JSP tags), provide a way of
encapsulating reusable functionality on JSP pages.
When a JSP page containing a custom tag is translated into a
Servlet, the tag is converted to operations on a tag handler. The
web container then invokes those operations when the JSP
pages servlet is executed.

Custom tags can:

Be customized via attributes passed from the calling page.


Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other.
Be nested within one another.

Why we need custom tags?


Reusability - A tag library is simply a collection of one or more
custom tags. A tag library can be reused on a single page, on
several pages in an application, or across different applications.
Readability - Custom tags improve readability by encapsulating
Java code away from the page.
Maintainability - If you can encapsulate some bits of
functionality in a custom tag, changes or fixes to that
functionality are made only to the custom tag, and then every
JSP page that uses the tag automatically gets the fix.

Srikanth Technologies
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 .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. This must process the tags and react to
callback methods invoked by JSP engine.

The characteristics of the tag, such as its name and a list of any
attributes that it takes, are then defined in a tag library descriptor
(TLD) file. When the tag is finally used on the page, an instance of
the tag handler class is created and its methods are called to
execute the reusable functionality.

SimpleTag interface
The SimpleTag interface defines the basic contract between simple
tags and the JSP page on which they are used.

public interface SimpleTag extends JspTag {


public void doTag() throws JspException, IOException;
public JspTag getParent();
public void setJspBody(JspFragment jspBody);
public void setJspContext(JspContext jspContext);
public void setParent(JspTag parent);
}

SimpleTagSupport Class
The SimpleTagSupport class implements SimpleTag interface and
provides default implementations for all methods. We have to
extend SimpleTagSupport class and override doTag() method.

Srikanth Technologies
Java EE (Web Applications I) 81
CurrentTime.java
01: package st;
02: import java.util.Date;
03: import javax.servlet.jsp.tagext.*;
04: import javax.servlet.jsp.*;
05: public class CurrentTime extends SimpleTagSupport {
06: public void doTag() throws JspException {
07: JspWriter out=getJspContext().getOut();
08: try {
09: out.println( new Date().toString());
10: }
11: catch (java.io.IOException ex) {
12: throw new JspException(ex.getMessage());
13: }
14: }
15: }

Tag Library Descriptor


TLD is a file with extension .tld. It is required to map the tag handler
to tag. It is an XML file with standard elements. Tag library is
typically given extension .tld and placed in /WEB-INF or one of its
sub folders.

The following are important elements of root elements <taglib>

Element Description
description (optional) A string describing the use of the tag
library.
display-name(optional) Name intended to be displayed by tools.
tlib-version The tag librarys version.
short-name (optional) Name that could be used by a JSP page-
authoring tool to create names with a
mnemonic value.
uri A URI that uniquely identifies the tag
library.

The following are important elements of <tag> element. Each tag


contains a <tag> element in .tld file.

Srikanth Technologies
Java EE (Web Applications I) 82

Element Meaning
name Name of the tag.
tag-class Name of the class that is the tag handler for
this tag.
description(optional) Description of the element.
body-content Specifies how the content of the tag is to be
processed. The valid values are
tagdependent, empty and scriptless.
attribute Declares an attribute of the custom tag.

Body Content
Body content may be any of the following.

empty Specifies tag is having empty body. No content is


allowed between start and end tags.
scriptless It is same as JSP body content except that it cannot
contain any Java code wrapped up as scriptlets.
tagdependent Specifies that the body of the tag is handled by tag
handler in the way it needs.

st.tld
01: <?xml version="1.0" encoding="UTF-8"?>
02: <taglib version="2.1"
03: xmlns="http://java.sun.com/xml/ns/javaee"
04: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05: xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
06: http://java.sun.com/xml/ns/javaee/web-jsptaglibrary
07: _2_1.xsd">
08: <tlib-version>1.0</tlib-version>
09: <short-name>st</short-name>
10: <uri>http://www.srikanthtechnologies.com/tags</uri>
11: <tag>
12: <name>currenttime</name>
13: <tag-class>st.CurrentTime</tag-class>
14: <body-content>empty</body-content>
15: </tag>
16: </taglib>

Srikanth Technologies
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. 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.

<%@taglib uri="uri | .tld file" prefix="tagprefix" %>

<tagprefix:tagname>body</tagprefix:tagname>

uri is either uri given in .tld file or the location of .tld file.
prefix can be any name. It is used to prefix tags in the library.
tagname must be name of one of the tags defined in .tld file.

usetime.jsp
01: <%@taglib uri="http://www.srikanthtechnologies.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. Attributes could be either optional or
required. 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.
An attribute element in tag element of .tld file.

Srikanth Technologies
Java EE (Web Applications I) 84

The following are the sub elements of attribute element.

Element Meaning
description(optional) A description of the attribute.
name The unique name of the attribute being
declared.
required (optional) Whether the attribute is required. The default
is false.
rtexprvalue(optional) Whether the attributes value can be
processed at runtime by an EL expression.
The default is false.

Srikanth Technologies
Java EE (Web Applications I) 85

Srikanth Technologies
Java EE (Web Applications I) 86
FormattedDate.java
01: package st;
02: import java.text.SimpleDateFormat;
03: import java.util.Date;
04: import javax.servlet.jsp.*;
05: import javax.servlet.jsp.tagext.SimpleTagSupport;
06: public class FormattedDate extends SimpleTagSupport {
07: private String format;
08: public void doTag() throws JspException {
09: JspWriter out=getJspContext().getOut();
10: try {
11: SimpleDateFormat sd = new SimpleDateFormat(format);
12: out.println(sd.format(new Date()));
13: }
14: catch (java.io.IOException ex) {
15: throw new JspException(ex.getMessage());
16: }
17: }
18: public void setFormat(String value) {
19: this.format = value;
20: }
21: }

st.tld
01: <tag>
02: <name>FormattedDate</name>
03: <tag-class>st.FormattedDate</tag-class>
04: <body-content>empty</body-content>
05: <attribute>
06: <name>format</name>
07: <rtexprvalue>true</rtexprvalue>
08: <type>java.lang.String</type>
09: </attribute>
10: </tag>

Srikanth Technologies
Java EE (Web Applications I) 87
index.jsp
01: <%@taglib uri="/WEB-INF/tlds/st.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, which represents the tags body
content, is passed to the tag via the setJspBody() method.
The JspFragment has one method that is of interest here:
invoke(). Calling this method effectively asks the JSP container
to evaluate and process the body content and send it back to the
page.

JobTagHandler.java
01: package st;
02: import java.sql.Connection;
03: import java.sql.DriverManager;
04: import java.sql.ResultSet;
05: import java.sql.Statement;
06: import javax.servlet.jsp.*;
07: import javax.servlet.jsp.tagext.JspFragment;
08: import javax.servlet.jsp.tagext.SimpleTagSupport;
09:
10: public class JobTagHandler extends SimpleTagSupport {
11:
12: @Override
13: public void doTag() throws JspException, IOException {
14: JspWriter out = getJspContext().getOut();
15: PageContext ctx = (PageContext) getJspContext();
16: JspFragment body = getJspBody();
17: try {
18: OracleCachedRowSet crs = new OracleCachedRowSet();
19: crs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
20: crs.setUsername("hr");
21: crs.setPassword("hr");
22: crs.setCommand("select * from jobs");
23: crs.execute();
24:

Srikanth Technologies
Java EE (Web Applications I) 88
25: while (crs.next()) {
26: ctx.setAttribute("id", crs.getString("job_id"));
27: ctx.setAttribute("title",crs.getString("job_title"));
28: body.invoke(out); // process body
29: }
30: crs.close();
31: }
32: catch (Exception ex) {
33: System.out.println(ex.getMessage());
34: }
35: }
36: }

st.tld
01: <tag>
02: <name>jobs</name>
03: <tag-class>st.JobTagHandler</tag-class>
04: <body-content>scriptless</body-content>
05: </tag>

usejobs.jsp
01: <%@taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%>
02: <html>
03: <body>
04: <h2>List Of Jobs </h2>
05: <ul>
06: <st:jobs>
07: <li>${id}, ${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
Java EE (Web Applications I) 89
JSTL
JavaServer Pages Standard Tag Library (JSTL) encapsulates core
functionality common to many JSP applications.
JSTL allows you to employ a single, standard set of tags to
perform common tasks.
JSTL has tags for iterators and conditional operations, for
manipulating XML documents, internationalization, accessing
databases using SQL.

Note: Download JSTL .jar file from


http://repo1.maven.org/maven2/jstl/jstl/1.2

If you are using maven, use the following dependency:

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

Using JSTL
JSTL is exposed as multiple tag libraries, where each tag library
contains a set of tags related to one topic. The URIs for the libraries
are as follows:

Core http://java.sun.com/jsp/jstl/core
XML http://java.sun.com/jsp/jstl/xml
Internationalization http://java.sun.com/jsp/jstl/fmt
SQL http://java.sun.com/jsp/jstl/sql
Functions http://java.sun.com/jsp/jstl/functions

Srikanth Technologies
Java EE (Web Applications I) 90
Core Tags
Core tags include tags related to variable manipulation, flow control,
and accessing URL based resources.

Area Related Tags


Variable support Remove, set
Flow control choose (when, otherwise) forEach, forTokens, if
URL management Import (param), redirect (param), url (param)
Miscellaneous catch, out

The following table shows commonly used attributes of core tags.

Tag Attributes
out value, escapeXml, default
set var, value, scope
remove var, scope
if test, var, scope
forEach var, items, begin, end, step
forTokens var, items, delims, begin, end, step
import url, var, scope
url value, var, scope
redirect url, context
param name, value
choose
otherwise
when test
catch var

Srikanth Technologies
Java EE (Web Applications I) 91
core.jsp
01: <%@taglib uri="http://java.sun.com/jsp/jstl/core"
02: prefix="c"%>
03:
04: <c:set var="foo" scope="session" value="..."/>
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.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.jsp">
19: <c:param name="name" value="Srikanth" />
20: </c:redirect>

Srikanth Technologies
Java EE (Web Applications I) 92
cfor.jsp
01: <%@page contentType="text/html" pageEncoding="UTF-8"%>
02: <%@taglib prefix="c"
03: uri="http://java.sun.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,anders,roberts,micheal,hunter">
19: <li> ${name} </li>
20: </c:forEach>
21: </ul>
22: <ul>
23: <c:forTokens var="name"
24: items="james:roberts,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.getHeaderNames()%>">
31: <tr><td>${hname} </td>
32: <td>${header[hname]} </td></tr>
33: </c:forEach>
34: </table>
35: </body>
36: </html>

Srikanth Technologies
Java EE (Web Applications I) 93
SQL tags
These tags allow you to access database to execute queries and
manipulate database. The following are the tags in SQL tag library.

setDataSource
transaction
query (dateParam, param)
update (dateParam, param)

The following table lists important attributes for each SQL Tag.

Tag Attributes
setDataSource dataSource,driver,url,user,password,var,scope
query dataSource,var,sql,maxRows,startRow,scope
update sql,dataSource,var,scope
transaction dataSource
param Value
dateParam Value

The data retrieved by query tag can be accessed by the following


methods. These methods are part of Result interface.

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
Java EE (Web Applications I) 94
updatesal.jsp?empno=100&sal=5000
01: <%@taglib prefix="c"
02: uri="http://java.sun.com/jsp/jstl/core" %>
03: <%@taglib prefix="sql"
04: uri="http://java.sun.com/jsp/jstl/sql"%>
05:
06: <sql:setDataSource var="oracle"
07: driver="oracle.jdbc.driver.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.sal}"/>
15: <sql:param value="${param.empno}"/>
16: </sql:update>
17:
18: <c:if test="${uc > 0 }">
19: Updated Sucessfully!
20: </c:if>

emplist.jsp
01: <%@ taglib prefix="c"
02: uri="http://java.sun.com/jsp/jstl/core" %>
03: <%@ taglib prefix="sql"
04: uri="http://java.sun.com/jsp/jstl/sql" %>
05:
06: <sql:setDataSource var="oracle"
07: driver="oracle.jdbc.driver.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,salary
13: from employees
14: </sql:query>
15: <ul>
16: <c:forEach var="row" items="${emplist.rows}">
17: <li>${row.employee_id}, ${row.first_name},${row.salary}
18: </c:forEach>
19: </ul>

Srikanth Technologies
Java EE (Web Applications I) 95
sqlplus.jsp
01: <%@taglib prefix="c"
02: uri="http://java.sun.com/jsp/jstl/core"%>
03: <%@taglib prefix="sql"
04: uri="http://java.sun.com/jsp/jstl/sql"%>
05: <html>
06: <body>
07: <form action="sqlplus.jsp" method="post">
08: Enter Query : <br/>
09: <textarea cols="80" rows="3"
10: name="query">${param.query}
11: </textarea><br/>
12: <input type="submit" value="Execute">
13: </form>
14: <% String query = request.getParameter("query");
15: if (query == null || query.length() == 0)
16: return;
17: %>
18: <sql:setDataSource
19: var="oracle" driver="oracle.jdbc.driver.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.columnNames}">
30: <th>${cn}</th>
31: </c:forEach>
32: </tr>
33: <c:forEach var="row" items="${results.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
Java EE (Web Applications I) 96

XML Tags
The XML actions are divided into three categories: XML core actions,
XML flow control actions, and XML transform actions. The XML set of
actions in JSTL is therefore based on XPath.

out, parse, set


choose (when, otherwise)
forEach, if
transform (param)

Tag Attributes
parse doc, var, scope,
out select, escapeXml
set select, var, scope
if select, var, scope
when select
forEach var, select, begin, end, step
transform doc, xml, xslt, var, scope, result
param name, value
Srikanth Technologies
Java EE (Web Applications I) 97
catalog.xml
01: <?xml version="1.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.jsp
01: <%@taglib uri="http://java.sun.com/jsp/jstl/core"
02: prefix="c"%>
03: <%@taglib uri="http://java.sun.com/jsp/jstl/xml"
04: prefix="x"%>
05: <html>
06: <body>
07: <c:import url="catalog.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
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.
JavaMail API allows mails to be sent and received using Java.
It supports the development of Mail Agents (programs used to
send and receive mails) such as Outlook Express.
JavaMail providers implement the API and provide support for
most common protocols.
Oracle provides providers for Simple Mail Transfer Protocol
(SMTP), the Internet Message Access Protocol (IMAP), and Post
Office Protocol 3 (POP3).
JavaMail is dependent on the JavaBeans Activation
Framework.
javax.mail package provides the required interfaces and
classes.
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.

Mail server with SMTP and POP3/IMAP servers


Java Mail API, which includes SMTP, POP3, IMAP providers
javax.mail.jar. Download it from
https://java.net/projects/javamail/pages/Home
A mail agent to access Mail server - Outlook Express

Srikanth Technologies
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.host property to point to the local mail server.
Start a mail session with the Session.getInstance( ) method.
Create a new Message object, probably by instantiating one of
its concrete subclasses.
Set the message's from and to addresses, message's subject and
the content of the message.
Send the message with the Transport.send() method.

Java Mail API


The following are important classes in Java Mail API. These classes
are abstract classes and implemented by a specific provider. These
classes are provided through javax.mail and javax.mail.internet
packages.

Class Description
Message Provides the basic encapsulation of message objects. It
provides attributes to specify sender, recipient, message
etc.
Store Supports storing and retrieving the messages.
Transport Is used to exchange messages with message transfer
agents. It provides abstract interface to message
transfer protocol such as SMTP.
Session Used to implement Mail Session.
Folder Used to represent a folder for storing mails.
Srikanth Technologies
Java EE (Web Applications I) 100
Session Class
It acts as a factory for the installed Transport and Store
implementation.
The Session class represents a mail session. It collects together
properties and defaults used by the mail API's.
A single default session can be shared by multiple applications on
the desktop.

Method Meaning
static Session getDefaultInstance Get the default Session object.
(Properties props,
Authenticator authenticator)
static Session Get a new Session object.
getInstance(Properties props,
Authenticator authenticator)
Properties getProperties() Returns the Properties object
associated with this Session.
String getProperty(String name) Returns the value of the
specified property.
Provider getProvider Returns the default Provider for
(String protocol) the protocol specified.
Provider[] getProviders() Returns an array of all the
implementations installed via
the JavaMail.
Store getStore() Get a Store object that
implements this user's desired
Store protocol.
Store getStore(String protocol) Get a Store object that
implements the specified
protocol.
Transport Get a Transport object that
getTransport(String protocol) implements the specified
protocol.
void setDebug(boolean debug) Set the debug setting for this
Session.

Srikanth Technologies
Java EE (Web Applications I) 101
Session Properties
The following are Java Mail related properties.

Property Description
mail.transport.protocol The default Transport protocol.
mail.store.protocol The default Store protocol.
mail.host The default host for both Store and
Transport protocols.
mail.user The default user name for both Store and
Transport.
mail.protocol.host The host specific to a particular protocol.

Authenticator Class
The class Authenticator represents an object that knows how to
obtain authentication for a network connection.

PasswordAuthentication getPasswordAuthentication()
Called when password authentication is needed. Subclasses should
override the default implementation, which returns null.

PasswordAuthentication class
This class is a data holder that is used by Authenticator. It is simply
a repository for a user name and a password.

String getPassword()
String getUserName()

Store Class
Store class models a message store and its access protocol, for
storing and retrieving messages. Subclasses provide actual
implementations - IMAPStore and POP3Store.

Method Description
Folder getDefaultFolder() Returns a Folder object for 'root'.
Folder getFolder(name) Returns the folder object corresponding
to the given name.
Srikanth Technologies
Java EE (Web Applications I) 102
Folder Class
Folder class represents a folder for mail messages. Subclasses such
as IMAPFolder and POP3Folder implement protocol specific Folders.

Method Description
Message[] getMessages() Gets all message objects.
int getMode() Returns open mode of the folder.
int Returns total number of unread
getUnreadMessageCount() messages.
boolean isOpen() Indicates whether folder is open.
void open(int mode) Mode can be READ_ONLY or
READ_WRITE.

Message Class
This class models an email message. This is an abstract class.
Subclasses provide actual implementations.
Message implements the Part interface. Message contains a set
of attributes and "content". Messages within a folder also have a
set of flags that describe its state within the folder.
Message objects are obtained either from a Folder or by
constructing a new Message object of the appropriate subclass.
Messages that have been received are retrieved from a folder
named "INBOX".
To send a message, an appropriate subclass of Message (e.g.,
MimeMessage) is instantiated, the attributes and content are
filled in, and the message is sent using the Transport.send
method.
A message may be set to any of the valid states such as
ANSWERED, DELETED, SEEN and DRAFT.

Method Meaning
void Adds these addresses to the
addFrom(Address[] addlist) existing "From" attribute.
void addRecipient ( Adds this recipient address to the
Message.RecipientType type, existing ones of the given type.
Address address)

Srikanth Technologies
Java EE (Web Applications I) 103
void addRecipients Adds these recipient addresses to
(RecipientType type, the existing ones of the given type.
Address[] addresses)
Address[] getAllRecipients() Gets all recipient addresses of
message.
Flags getFlags() Returns a Flags object containing
the flags for this message.
Folder getFolder() Gets the folder from which this
message was obtained.
Address[] getFrom() Returns the "From" addresses.
Date getReceivedDate() Gets the date this message was
received.
Address[] getReplyTo() Gets the addresses to which replies
should be directed.
Date getSentDate() Gets the date this message was
sent.
String getSubject() Gets the subject of this message.
void setFlags Sets the specified flags on this
(Flags flag,boolean set) message to the specified value.
void setRecipients Sets the recipient addresses.
(RecipientType type,
Address[] addresses)
void setReplyTo(Address[] Sets the addresses to which replies
addlist) should be directed.
void setSentDate(Date date) Sets the sent date of this message.
void setSubject(String subject) Sets the subject of this message.

Sendmail.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
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.java
01: package servlets;
02: import java.io.IOException;
03: import java.io.PrintWriter;
04: import java.util.Properties;
05: import javax.activation.DataHandler;
06: import javax.mail.*;
07: import java.util.Date;
08: import javax.servlet.ServletException;
09: import javax.servlet.annotation.WebServlet;
10: import javax.servlet.http.*;
11:
12: @WebServlet(name = "SendMailServlet",
13: urlPatterns = {"/sendmail"})
14: public class SendMailServlet extends HttpServlet {
15: protected void doPost(HttpServletRequest request,
16: HttpServletResponse response)
17: throws ServletException, IOException {
18: response.setContentType("text/html");
19: PrintWriter out = response.getWriter();
20:
21: String to = request.getParameter("toaddress");
22: String from = request.getParameter("fromaddress");
23: String subject = request.getParameter("subject");
24: String body = request.getParameter("body");
25: Properties props = System.getProperties();
26: Session session = Session.getDefaultInstance(props,
null);

Srikanth Technologies
Java EE (Web Applications I) 105
27: try {
28: // construct the message
29: Message msg = new MimeMessage(session);
30: msg.setFrom(new InternetAddress(from));
31: msg.setRecipient(Message.RecipientType.TO,
32: new InternetAddress(to));
33: msg.setDataHandler(
34: new DataHandler(body, "text/html"));
35: msg.setSentDate(new Date());
36: msg.setSubject(subject);
37: Transport.send(msg); // send message
38: out.println("\nMail was sent successfully.");
39: }
40: catch(Exception ex){
41: out.println("Error --> " + ex.getMessage());
42: }
43: }
44: }

SendMailAttachmentServlet.java
01: package servlets;
02:
03: import java.io.IOException;
04: import java.io.PrintWriter;
05: import java.util.Properties;
06: import javax.activation.DataHandler;
07: import javax.activation.FileDataSource;
08: import javax.mail.*;
09: import javax.mail.*;
10: import javax.servlet.ServletException;
11: import javax.servlet.annotation.WebServlet;
12: import javax.servlet.http.*;
13:
14: @WebServlet(name = "SendMailServlet",
15: urlPatterns = {"/sendfile"})
16: public class SendMailAttachmentServlet extends HttpServlet{
17: protected void doGet(HttpServletRequest request,
18: HttpServletResponse response)
19: throws ServletException, IOException {
20: response.setContentType("text/html");
21: PrintWriter out = response.getWriter();
22:
23: String to = "james@st.com";

Srikanth Technologies
Java EE (Web Applications I) 106
24: String from = "webmaster@st.com";
25: String subject = "Ship";
26: String body = "Here is a ship....";
27: String filename = "ship.jpg";
28:
29: Properties props = System.getProperties();
30: Session session=Session.getDefaultInstance(props,null);
31: try {
32: MimeMessage msg = new MimeMessage(session);
33: msg.setFrom(new InternetAddress(from));
34: msg.setRecipient(Message.RecipientType.TO,
35: new InternetAddress(to));
36: msg.setSubject(subject);
37: // create and fill the first message part
38: MimeBodyPart mbp1 = new MimeBodyPart();
39: mbp1.setText(body);
40: // create the second message part
41: MimeBodyPart mbp2 = new MimeBodyPart();
42: FileDataSource fds =
43: new FileDataSource(
44: getServletContext().getRealPath(filename));
45: // attach the file to the message
46: mbp2.setDataHandler(new DataHandler(fds));
47: mbp2.setFileName(fds.getName());
48: // create the Multipart and its parts to it
49: Multipart mp = new MimeMultipart();
50: mp.addBodyPart(mbp1);
51: mp.addBodyPart(mbp2);
52: msg.setContent(mp);
53: Transport.send(msg);
54: out.println(
55: "<h4>Mail has been sent with attachment.</h4>");
56: } catch (Exception ex) {
57: ex.printStackTrace(out);
58: }
59: }
60: }

Srikanth Technologies
Java EE (Web Applications I) 107
Sendfromgmail.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.java
01: package servlets;
02: import java.io.IOException;
03: import java.io.PrintWriter;
04: import java.security.Security;
05: import java.util.Properties;
06: import javax.mail.*;
07: import javax.mail.internet.InternetAddress;
08: import javax.mail.internet.MimeMessage;
09: import javax.servlet.ServletException;
10: import javax.servlet.annotation.WebServlet;
11: import javax.servlet.http.*;
12:
13: @WebServlet(name = "SendFromGmailServlet",
14: urlPatterns = {"/sendfromgmail"})
15: public class SendMailFromGmailServlet
16: extends HttpServlet {
17: protected void doPost(HttpServletRequest request,
18: HttpServletResponse response)
Srikanth Technologies
Java EE (Web Applications I) 108
19: throws ServletException, IOException {
20:
21: String SMTP_HOST_NAME = "smtp.gmail.com";
22: String SMTP_PORT = "465"; // or use 567
23: String toAddress = request.getParameter("toaddress");
24: final String username=request.getParameter("username");
25: final String fromAddress=username + "@gmail.com";
26: final String password = request.getParameter("password");
27: String subject = request.getParameter("subject");
28: String body = request.getParameter("body");
29: String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
30: response.setContentType("text/html");
31: PrintWriter out = response.getWriter();
32: try {
33: Security.addProvider(
34: new com.sun.net.ssl.internal.ssl.Provider());
35: Properties props = new Properties();
36: props.put("mail.smtp.host", SMTP_HOST_NAME);
37: props.put("mail.smtp.auth", "true");
38: props.put("mail.smtp.port", SMTP_PORT);
39: props.put("mail.smtp.socketFactory.port", SMTP_PORT);
40: props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
41: props.put("mail.smtp.socketFactory.fallback", "false");
42: Session session = Session.getInstance(props,
43: new javax.mail.Authenticator() {
44: protected PasswordAuthentication
45: getPasswordAuthentication(){
46: return new PasswordAuthentication(username, password);
47: }
48: });
49: Message msg = new MimeMessage(session);
50: msg.setFrom(new InternetAddress(fromAddress));
51: msg.setRecipient(Message.RecipientType.TO,
52: new InternetAddress(toAddress));
53: msg.setSubject(subject);
54: msg.setText(body);
55: Transport.send(msg);
56: out.println("<h4>Mail has been sent Successfully!</h4>");
57: } catch (Exception ex) {
58: ex.printStackTrace(out);
59: }
60: }
61: }

Srikanth Technologies
Web
Applications - II
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 - JSON types
are string, number, array, boolean whereas in XML data are all
string
Native data form for JavaScript code. Data is readily accessible
as JSON objects in your JavaScript code.
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 - A JSON
object begins with "{" and ends with "}". Each name is followed
by : (colon) and the name/value pairs are separated by ,
(comma)

{"title":"Professional AJAX","price":399}

The eval() function


To convert a JSON text into a JSON object, use the eval() function.
The eval() invokes the JavaScript compiler and creates an object
from JSON string.

var myObject = eval('(' + myJSONtext + ')');

Srikanth Technologies
Java EE (Web Applications II) 2
JSON Processing API
Starting from Java EE 7.0, support for JSON Processing is provided
by Java. It is called as JSON Processing in Java EE (JSR-353). 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.
Class or Interface Description
Json Contains static methods to create instances
of JSON parsers, builders, and generators.
This class also contains methods to create
parser, builder, and generator factory
objects.
JsonReader Reads JSON data from a stream and creates
an object model in memory.
JsonObjectBuilder, Create an object model or an array model in
JsonArrayBuilder memory by adding elements from application
code.
JsonWriter Writes an object model from memory to a
stream.
JsonValue, Represent data types for elements in JSON
JsonStructure, data.
JsonObject,
JsonArray,
JsonString,
JsonNumber
JsonParser Represents an event-based parser that can
read JSON data from a stream or from an
object model.
JsonGenerator Writes JSON data to a stream one element at
a time.

Srikanth Technologies
Java EE (Web Applications II) 3
Note: Download implementation of JSON Processing API from
jsonp.java.net

Using JSON Processing API


The following programs demonstrate how to use JSON API provided
by Java EE 7.0.

01: import javax.json.Json;


02: import javax.json.JsonObject;
03: import javax.json.JsonObjectBuilder;
04:
05: public class CreateJsonObject {
06: public static void main(String[] args) {
07: JsonObjectBuilder builder = Json.createObjectBuilder();
08: builder.add("name", "Srikanth");
09: builder.add("occupation", "Director");
10: builder.add("company", "Srikanth Technologies");
11:
12: JsonObject person = builder.build();
13: System.out.println(person);
14: }
15: }

When you run the above program, the following output is


generated:

{"name":"Srikanth","occupation":"Director",
"company":"Srikanth Technologies"}

In case you want to write JSON object to a file, 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.txt");
04: JsonWriter fjw = Json.createWriter(fw);
05: fjw.writeObject(person);
06: fjw.close();
07: fw.close();

Srikanth Technologies
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. It creates an array with the name contacts and
adds two objects to it.

01: import javax.json.Json;


02: import javax.json.JsonArrayBuilder;
03: import javax.json.JsonObjectBuilder;
04:
05: public class CreateJsonArray {
06: public static void main(String[] args) {
07: JsonObjectBuilder person = Json.createObjectBuilder();
08: person.add("name", "Srikanth");
09: person.add("occupation",
10: "Director, Srikanth Technologies");
11:
12: JsonArrayBuilder emails = Json.createArrayBuilder();
13: emails.add("srikanthpragda@yahoo.com");
14: emails.add("srikanthpragada@gmail.com");
15:
16: person.add("emails", emails);
17: System.out.println(person.build());
18: }
19: }

The output JSON is as follows:

{"name":"Srikanth",
"occupation":"Director,Srikanth Technologies",
"emails":["srikanthpragda@yahoo.com","srikanthpragada@gmail.com
"]}

Creating JSON Object using Generator


The following program creates a JSON object using Generator.

01: import java.io.StringWriter;


02: import javax.json.Json;
03: import javax.json.stream.JsonGenerator;
04:

Srikanth Technologies
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.createGenerator(sw);
09:
10: gen.writeStartObject()
11: .write("name", "Srikanth Pragada")
12: .write("email", "srikanthpragada@yahoo.com")
13: .write("mobile","9059057000")
14: .writeEnd();
15:
16: gen.close();
17: System.out.println(sw.toString());
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.io.StringWriter;


02: import javax.json.Json;
03: import javax.json.stream.JsonGenerator;
04:
05: public class CreateJsonArrayWithGenerator {
06: public static void main(String[] args) {
07: StringWriter writer = new StringWriter();
08: JsonGenerator gen = Json.createGenerator(writer);
09: gen.writeStartObject()
10: .write("name", "Srikanth")
11: .write("occupation", "Director, Srikanth Technologies")
12: .writeStartArray("emails")
13: .write("srikanthpragada@yahoo.com")
14: .write("srikanthpragada@gmail.com")
15: .writeEnd() // for array
16: .writeEnd(); // for root object
17: gen.close();
18: System.out.println(writer);
19: }
20: }

Srikanth Technologies
Java EE (Web Applications II) 6
{"name":"Srikanth",
"occupation":"Director, Srikanth Technologies",
"emails":["srikanthpragada@yahoo.com","srikanthpragada@gmail.co
m"]}

Read JSON Object using Object Model


JSON API allows reading JSON objects either using JsonReader or
with JsonParser. This example shows how to use JsonReader.

01: import java.io.StringReader;


02: import javax.json.Json;
03: import javax.json.JsonObject;
04: import javax.json.JsonReader;
05:
06: public class ReadJsonObject {
07: public static void main(String[] args) throws Exception {
08: JsonReader reader = Json.createReader
09: (new StringReader("{ \"qty\" : 20, \"price\" : 1000}"));
10: JsonObject sale = reader.readObject();
11:
12: System.out.println("Qty : " + sale.getInt("qty"));
13: System.out.println("Price : " + sale.getInt("price"));
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. It is left to us to determine
the type of the event and handle it accordingly.

Srikanth Technologies
Java EE (Web Applications II) 7
01: import java.io.StringReader;
02: import javax.json.Json;
03: import javax.json.stream.JsonParser;
04:
05: public class ReadJsonObjectWithStreaming {
06: public static void main(String[] args) throws Exception {
07: JsonParser parser = Json.createParser
08: (new StringReader("{ \"qty\" : 20, \"price\" : 1000}"));
09: while (parser.hasNext()) {
10: JsonParser.Event event = parser.next();
11: switch (event) {
12: case KEY_NAME:
13: System.out.print(parser.getString() + " :");
14: break;
15: case VALUE_NUMBER:
16: System.out.println(parser.getInt());
17: break;
18: }
19: } // while
20: }
21: }

Srikanth Technologies
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, but a new way to use
existing standards
With AJAX you can create better, faster, and more user-friendly
web applications
AJAX is a technology that uses JavaScript, XML, DOM (Document
Object Model), 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. Used in Outlook Web
Access and MSDN applications.
Used in IE 5.0. Implemented as ActiveX object in IE.
Used to make asynchronous request and response.
No post back, no full refresh of the page.
Adopted by all other major browsers.
Implemented as standard object in other browsers.

Srikanth Technologies
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.

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. Response from server
3. XMLHttpRequest calls callback.

Web pages and web services

Web Server

onreadystatechange event
Specifies the JavaScript function to be called when readyState
property changes.
Generally it examines readyState property before processing
the response.

Srikanth Technologies
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. Body is not yet received
4 Response has been completely received

Methods
The following are the methods of XMLHttpRequest object.

Method Meaning
open(method, Prepares an asynchronous request
url,async,uname, pwd)
send(value) Sends the request with the given value.
The values are passed to server in http
post request.
setRequestHeader Sets request header to the given value
(name, value)
getResponseHeader Returns value of the specified response
(name) header
getAllResponseHeaders() Returns all response headers as a string
abort() Aborts the current request

add.jsp
01: <%@page contentType="text/plain"%>
02: <%
03: int n1, n2;
04: n1 = Integer.parseInt(request.getParameter("num1"));
05: n2 = Integer.parseInt(request.getParameter("num2"));
06: out.println(n1 + n2);
07: %>

Srikanth Technologies
Java EE (Web Applications II) 11
add.html
01: <html>
02: <head>
03: <script language="javascript">
04: var xhr;
05: function create(){
06: xhr = new XMLHttpRequest();
07: }
08: function updateTotal(){
09: var num1 = document.getElementById("num1");
10: var num2 = document.getElementById("num2");
11: var url="add.jsp?num1=" +num1.value+"&num2=" + num2.value;
12: xhr.open("GET",url,true);
13: xhr.onreadystatechange=doUpdate;
14: xhr.send(null); // make GET request
15: }
16: function doUpdate() {
17: if (xhr.readyState == 4)
18: if (xhr.status == 200){
19: var result = document.getElementById("result");
20: result.value= xhr.responseText;
21: }
22: else
23: alert("Error : " + xhr.statusText);
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
Java EE (Web Applications II) 12
AJAX and XML
Server-side script may send XML content to client, which is
processed using XML DOM and JavaScript in client. The following
example shows how to send XML from server and process it in client
using XML DOM and JavaScript.

empdetails.html
01: <html>
02: <head><title>AJAX and XML</title>
03: <script type ="text/javascript">
04: var xmlHttp;
05: var empname, empsal, message;
06: function create() {
07: xmlHttp = new XMLHttpRequest();
08: empname = document.getElementById("empname");
09: empsal = document.getElementById("empsal");
10: message = document.getElementById("message");
11: } // end of create
12: function getEmployeeDetails() {
13: var empid = document.getElementById("empid").value;
14: var url = "empdetails_json.jsp?empid=" + empid;
15: xmlHttp.open("GET", url, true);
16: xmlHttp.onreadystatechange = doUpdate;
17: xmlHttp.send(null); // make request
18: }
19: function doUpdate() {
20: if (xmlHttp.readyState === 4 &&
21: xmlHttp.status === 200){
22: var data = xmlHttp.responseText;
23: var details=eval("(" + data + ")");// JSON to Object
24: if (details.error) { // employee id not found
25: empname.value = "";
26: empsal.value = "";
27: message.innerHTML = details.error;
28: }
29: else { // employee found
30: empname.value = details.name;
31: empsal.value = details.salary;
32: }
33: }
34: }
35: </script>

Srikanth Technologies
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.jsp
01: <%@page import="java.sql.*" contentType="text/xml"%>
02: <%
03: String empid=request.getParameter("empid");
04: Class.forName("oracle.jdbc.driver.OracleDriver");
05: Connection con=DriverManager.getConnection
06: ("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
07: Statement st=con.createStatement();
08: ResultSet rs=st.executeQuery
09: ("select first_name,salary from employees where
10: employee_id=" + empid);
11: if (rs.next()) { // found
12: out.println("<employee><name>");
13: out.println(rs.getString(1));
14: out.println("</name><salary>");
15: out.println( rs.getInt(2));
16: out.println("</salary></employee>");
17: }
18: else
19: out.println("<error>Employee ID Not Found </error>");
20: rs.close(); st.close(); con.close();
21: %>

Srikanth Technologies
Java EE (Web Applications II) 14
empdetails_json.html
01: <html><head><title>AJAX and XML</title>
02: <script type ="text/javascript">
03: var xmlHttp;
04: var empname, empsal, message;
05: function create() {
06: xmlHttp = new XMLHttpRequest();
07: empname = document.getElementById("empname");
08: empsal = document.getElementById("empsal");
09: message = document.getElementById("message");
10: } // end of create
11: function getEmployeeDetails() {
12: var empid = document.getElementById("empid").value;
13: var url = "empdetails_json.jsp?empid=" + empid;
14: xmlHttp.open("GET", url, true);
15: xmlHttp.onreadystatechange = doUpdate;
16: xmlHttp.send(null); // make request
17: }
18: function doUpdate() {
19: if (xmlHttp.readyState === 4 &&
20: xmlHttp.status === 200){
21: var data = xmlHttp.responseText;
22: var details=eval("(" + data + ")");// JSON to Object
23: if (details.error) { // employee id not found
24: empname.value = "";
25: empsal.value = "";
26: message.innerHTML = details.error;
27: }
28: else { // employee found
29: empname.value = details.name;
30: empsal.value = details.salary;
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
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.jsp
01: <%@ page import="java.sql.*,javax.json.*"
02: contentType="text/json"%>
03: <%
04: Class.forName("oracle.jdbc.driver.OracleDriver");
05: Connection con = DriverManager.getConnection
06: ("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
07: PreparedStatement ps = con.prepareStatement
08: ("select first_name, salary from employees
09: where employee_id = ?");
10: ps.setString(1, request.getParameter("empid"));
11: ResultSet rs = ps.executeQuery();
12:
13: JsonObjectBuilder builder = Json.createObjectBuilder();
14: // generate JSON
15: if (rs.next()) { // found
16: builder.add("name", rs.getString("first_name"));
17: builder.add("salary", rs.getInt("salary"));
18: } else {
19: builder.add("error", "Sorry! Employee Not Found!");
20: }
21: out.println(builder.build().toString());
22: rs.close(); ps.close(); con.close();
23: %>

Srikanth Technologies
Java EE (Web Applications II) 16
jQuery
JQuery is a JavaScript library developed by John Resig and his
company.
Its tagline is - write less, do more.
It greatly simplifies things that you handle with JavaScript.
AJAX needs code to be written in JavaScript. So, instead of using
XMLHttpRequest object and other JavaScript construct to
implement AJAX, we can use JQuery to achieve the same, of
course with far less code to handle.
Many regard JQuery as the best JavaScript libraries of all.
Download JQuery from www.jquery.com. You can download
either of the versions compressed or development.
Place jquery-1.10.2.js in your web applications root directory.
Refer to JQuery from <script> tag in your pages.
It is a good practice to rename jquery-version.js to jquery.js
so that <script> tag need not change when version changes.

Syntax
The jQuery syntax is tailor-made for selecting HTML elements and
performing some action on the element(s).

$(selector).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 .ready() function


This function is used to execute code when the DOM is fully loaded.

01: $(document).ready(function(){
02:
03: // jQuery methods go here...
04:
05: });

Srikanth Technologies
Java EE (Web Applications II) 17
Selectors
jQuery selectors allow you to select and manipulate HTML
element(s).
jQuery selectors are used to "find" (or select) HTML elements
based on their id, classes, types, attributes, values of attributes
and much more.
All selectors in jQuery start with the dollar sign and parentheses:
$().

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 $(".red") Selects items with css class red
$("p.intro") Selects all <p> elements with
class="intro"

jQuery and AJAX


The following examples show how to use jQuery to make AJAX
request.

Method Meaning
load() The load() method loads data from a server
and puts the returned data into the selected
element.
$(selector).load(URL,data,callback);
get() The $.get() method requests data from the
server with an HTTP GET request.
jQuery.get( url [, data ] [, success(data,
textStatus, jqXHR) ] [, dataType ] )
post() The $.post() method requests data from the
server using an HTTP POST request.
jQuery.post( url [, data ] [, success(data,
textStatus, jqXHR) ] [, dataType ] )

Srikanth Technologies
Java EE (Web Applications II) 18
getJSON() Load JSON-encoded data from the server using
a GET HTTP request.
jQuery.getJSON( url [, data ] [, success(data,
textStatus, jqXHR)])

Create an HTML page (add.html) that takes two numbers from user
and calls add.jsp with .get() method of JQuery library.

add.html
01: <html>
02: <script type="text/javascript" src="jquery.js"></script>
03: <script type="text/javascript">
04: function addNumbers(){
05: $.get("add.jsp",{num1 : $("#num1").val(),
06: num2 : $("#num2").val()},doUpdate);
07: }
08: function doUpdate(response) {
09: if (response) {
10: $("#result").val(response);
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
Java EE (Web Applications II) 19
The following are important steps in the above program :

Include jquery.js using <script> tag


Use $.get method to make an AJAX call to add.jsp. No need to
use XMLHttpRequest directly. JQuery library takes care of it.
The expression $("#num1").val() takes the value from the
field that is with id num1. The last parameter to get() method is
the call-back method.
Call-back method (doUpdate) has a single parameter that
contains the response from the server, which is sum in this case.
Check whether response is available and then place it into text
field with id result.

Using XML with JQuery


The following is the code for EMPDETAILS.HTML. Apart from
taking XML from server and parsing it, it also demonstrates how
to show progress icon to user while request is in progress. I have
used clock.gif for this.
Make sure clock.gif is placed in webpages folder.
Function css is used to add CSS attributes to an element.
JSP empdetails.jsp is same as what we used in AJAX example.

01: <html>
02: <head>
03: <title>AJAX and XML with JQUERY </title>
04: <script src="jquery.js"></script>
05: <script>
06: function getEmployeeDetails() {
07: // make clock image visible
08: $("#clock").css("visibility", "visible")
09: $.get("../empdetails.jsp",
10: {empid: $("#empid").val()},
11: displayResult);
12: }
13: function displayResult(data) {
14: // hide clock image
15: $("#clock").css("visibility", "hidden")
16:
17: if($(data).find("error").text()!= "") // error
18: {
Srikanth Technologies
Java EE (Web Applications II) 20
19: // clear fields
20: $("#empname").val("")
21: $("#empsal").val("")
22: alert("Error : "+ $(data).find("error").text());
23: }
24: else // found employee and got details
25: {
26: $("#empname").val($(data).find("name").text());
27: $("#empsal").val($("salary", data).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.gif"
48: style="visibility:hidden"/>
49: </body>
50: </html>

Run EMPDETAILS.HTML page, enter employee id and click on


button. After a little while, you must see either details of employee
in text fields or error message as alert.

Srikanth Technologies
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.

Let us create HTML page (empdetails_json.html) that uses JQuery to


make AJAX call to EMPDETAILS_JSON.JSP. We will use
getJSON() method to send request to server. The main advantage
with this method is, it parses the response string as JSON. The code
is given below.

empdetails_json.html
01: <html>
02: <head>
03: <title>AJAX and JSON with JQUERY </title>
04: <script type="text/javascript" src="jquery.js"></script>
05: <script language="javascript">
06: function getEmployeeDetails(){
07: $.getJSON( "empdetails_json.jsp",{empid :
08: $("#empid").val()}, displayResult);
09: }
10: function displayResult(data) {
11: if ( data.error) { // emp not found
12: $("#empname").val("") // clear fields
13: $("#empsal").val("")
14: alert( data.error);
15: }
16: else { // Found employee. Display details
17: $("#empname").val( data.name);
18: $("#empsal").val( data.salary);
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
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.HTML page, enter employee id and click


on button. After a little while, you must see either details of
employee in text fields or error message as alert.

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.

jobs.html
01: <html>
02: <head>
03: <title>Jobs and Employees</title>
04: <script type="text/javascript" src="jquery.js"></script>
05: <script type="text/javascript" language="javascript">
06: // this is done when page is loaded
07: $(function() {
08: $.getJSON("jobs.jsp",{},displayJobs);
09: }
10: );
11:
12: function displayJobs(data) {
13: $.each(data, function(index,job){
14: // add items to List box
15: $("#jobs").append("<option value='" + job.id + "'>"
16: + job.title + "</option>");

Srikanth Technologies
Java EE (Web Applications II) 23
17: }
18: );
19: }
20:
21: function getEmployees() {
22: $("#employees").contents().remove(); // clear options
23: $.getJSON("employees.jsp",{jobid:$("#jobs").val()},
24: displayEmployees);
25: }
26:
27: function displayEmployees(data) {
28: $.each(data, function(index,name){
29: // add names to List box
30: $("#employees").append("<option>" +
31: name + "</option>");
32: } // end of function
33: ); // 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.</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
Java EE (Web Applications II) 24
jobs.jsp
01: <%@page import="javax.json.*"
02: contentType="application/json"%>
03:
04: <%
05: javax.sql.rowset.CachedRowSet rs =
06: new oracle.jdbc.rowset.OracleCachedRowSet();
07: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
08: rs.setUsername("hr");
09: rs.setPassword("hr");
10: rs.setCommand("select * from jobs");
11: rs.execute();
12:
13: JsonArrayBuilder jobs = Json.createArrayBuilder();
14:
15: while (rs.next()) {
16: JsonObjectBuilder job = Json.createObjectBuilder();
17: job.add("id", rs.getString("job_id"));
18: job.add("title", rs.getString("job_title"));
19: jobs.add(job.build());
20: }
21:
22: rs.close();
23: out.println(jobs.build().toString());
24: %>

employees.jsp
01: <%@page import="javax.json.*"
02: contentType="application/json"%>
03: <%
04: javax.sql.rowset.CachedRowSet rs =
05: new oracle.jdbc.rowset.OracleCachedRowSet();
06: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
07: rs.setUsername("hr");
08: rs.setPassword("hr");
09: rs.setCommand("select first_name ||' '|| last_name
10: fullname from employees where job_id = ?");
11: rs.setString(1, request.getParameter("jobid"));
12: rs.execute();
13:
14:
15: JsonArrayBuilder emps = Json.createArrayBuilder();
16: while (rs.next()) {
Srikanth Technologies
Java EE (Web Applications II) 25
17 emps.add(rs.getString("fullname"));
21: }
22: rs.close();
23: out.println( emps.build().toString());
24: %>

Srikanth Technologies
Java EE (Web Applications II) 26
BEAN VALIDATION
Bean validation (JSR 303) is a new feature that is available in
Java EE 6.
The bean validation model is supported by constraints in the
form of annotations placed on a field, method, or class of a
JavaBean.
Several built-in annotations are available in the
javax.validation.constraints package.

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.
@Max The annotated element must be a number whose value
must be lower or equal to the specified maximum.
@Size The annotated element must be between specified
minimum and maximum boundaries.
@NotNull The annotated element must not be null.
@Null The annotated element must be null.
@Pattern The annotated element must match the specified Java
regular expression.

To use Bean Validation, we have to use Hibernate Validator, which is


one of the implementations of Bean Validation Specifications.

Download Hibernate Validator from


http://hibernate.org/validator and place .jar files related to
Hibernate Validator and their dependencies in classpath of our
project.

User.java
01: import javax.validation.constraints.Max;
02: import javax.validation.constraints.Min;
03: import javax.validation.constraints.NotNull;
04: import javax.validation.constraints.Pattern;
05: import javax.validation.constraints.Size;
06:
07: public class User {
Srikanth Technologies
Java EE (Web Applications II) 27
08: @NotNull(message="Username Required")
09: @Size(min=6, max=10,
10: message="Username must be between 6 to 10 chars")
11: private String uname;
12:
13: @NotNull(message="Password Required")
14: private String password;
15:
16: @Min( value=18 , message="Age must be >= 18")
17: @Max( value=100, message="Age must be <= 100")
18: private int age;
19:
20: @Pattern (regexp="^[0-9]{10}$",
21: message = "Mobile number must be of 10 digits")
22: private String mobile;
23: public int getAge() {
24: return age;
25: }
26: public void setAge(int age) {
27: this.age = age;
28: }
29: public String getMobile() {
30: return mobile;
31: }
32: public void setMobile(String mobile) {
33: this.mobile = mobile;
34: }
35: public String getPassword() {
36: return password;
37: }
38: public void setPassword(String password) {
39: this.password = password;
40: }
41: public String getUname() {
42: return uname;
43: }
44: public void setUname(String uname) {
45: this.uname = uname;
46: }
47: }

Once Bean with validation annotations are created, we need to use


Validation API to test whether data in the bean is valid as follows:

Srikanth Technologies
Java EE (Web Applications II) 28

01: import java.util.Set;


02: import javax.validation.ConstraintViolation;
03: import javax.validation.Validation;
04: import javax.validation.Validator;
05: import javax.validation.ValidatorFactory;
06:
07: public class ValidateUser {
08: public static void main(String[] args) {
09: ValidatorFactory factory =
10: Validation.buildDefaultValidatorFactory();
11: Validator validator = factory.getValidator();
12:
13: User u = new User();
14: u.setAge(12);
15: u.setUname("Gavin");
16: u.setPassword("king");
17: u.setMobile("905905700");
18:
19: Set<ConstraintViolation<User>> errors =
20: validator.validate(u);
21:
22: for(ConstraintViolation<User> v: errors)
23: System.out.println(v.getMessage());
24: }
25: }

When run, 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
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.
Client uses the endpoints URI to connect to the server
After the connection has been established, 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.
The javax.websocket.server package contains annotations,
classes, and interfaces to create and configure server endpoints.
The javax.websocket package contains annotations, classes,
interfaces, and exceptions that are common to client and server
endpoints.
To create a programmatic endpoint, you extend the Endpoint
class and override its lifecycle methods.
To create an annotated endpoint, you decorate a Java class and
some of its methods with the annotations provided by the
packages above.

Annotation Event Example


OnOpen Connection @OnOpen
opened public void open(Session session,
EndpointConfig conf) { }
OnMessage Message received @OnMessage
public void message (Session session,
String msg) { }
OnError Connection error @OnError
public void error(Session session,
Throwable error) { }
OnClose Connection closed @OnClose
public void close(Session session,
CloseReason reason) { }

Srikanth Technologies
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.java
01: package endpoints;
02: import javax.websocket.OnMessage;
03: import javax.websocket.OnOpen;
04: import javax.websocket.Session;
05: import javax.websocket.server.ServerEndpoint;
06:
07: @ServerEndpoint("/time")
08: public class TimeEndPoint {
09: Thread childThread;
10: @OnOpen
11: public void openConnection(final Session session) {
12: System.out.println("Opened connection for TimeEndPoint");
13: childThread = new Thread(new Runnable() {
14: public void run() {
15: while (true) {
16: try {
17: Thread.sleep(5000);
18: session.getBasicRemote().
19: sendText(new java.util.Date().toString());
20: } catch (Exception ex) {
21: }
22: } // while
23: } // run()
24: });
25: childThread.start();
26: } // openConnection()
27: } // TimeEndPoint

Srikanth Technologies
Java EE (Web Applications II) 31
TimeClient.html
01: <!DOCTYPE html>
02: <html><head>
03: <script type="text/javascript">
04: var wsocket;
05: var outputText;
06: function connect() {
07: wsocket=new
08: WebSocket("ws://localhost:8888/websocketsdemo/time");
09: wsocket.onmessage = onMessage;
10: outputText = document.getElementById("outputText");
11: }
12: function onMessage(evt) {
13: var data = evt.data;
14: outputText.innerHTML = data;
15: }
16: window.addEventListener("load", connect);
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.

UpperEndPoint.java
01: package endpoints;
02: import javax.websocket.*;
03: import javax.websocket.server.ServerEndpoint;
04:
05: @ServerEndpoint("/upper")
06: public class UpperEndPoint {
07: @OnMessage
08: public void onMessage(Session session, String message){
09: try {
10: System.out.println("message received :" + message);
11: session.getBasicRemote().
12: sendText(message.toUpperCase());
13: } catch (Exception ex) {

Srikanth Technologies
Java EE (Web Applications II) 32
14: }
15: }
16: }

UpperClient.html
01: <!DOCTYPE html>
02: <html>
03: <head>
04: <script type="text/javascript">
05: var wsocket;
06: var inputText;
07: var outputText;
08: function connect() {
09: wsocket = new WebSocket
10: ("ws://localhost:8888/websocketsdemo/upper");
11: wsocket.onmessage = onMessage;
12: inputText = document.getElementById("inputText");
13: outputText = document.getElementById("outputText");
14: }
15: function onMessage(evt) {
16: var data = evt.data;
17: outputText.innerHTML = data;
18: }
19: function sendText(){
20: wsocket.send( inputText.value);
21: }
22: window.addEventListener("load", 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
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.
A Web service, a server application that implements the methods
that are available for clients to call, is deployed on a server-side
container.
A way of building service-oriented architecture (SOA).
Mainly used in B2B applications.
Language and platform independent.
Based on industry standards such as Http, XML and SOAP.
Web services can offer application components like currency
conversion, weather reports or even language translation as
services.
Websites like Amazon, Google, and EBay are providing web
services to third-party developers.

SOAP Request
Web Service
Web service Consumer
SOAP Request

Advantages of Web Service


Web service is another way to develop distributed applications.
However, compared with RMI, CORBA, and DCOM, web services
provide the following key advantages.

Accessible Legacy assets & internal apps are exposed and


accessible on the web.
Simple It is easy to create a web service and make it
available to all platforms.
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.
Scalable A client makes a request for a method in web
Srikanth Technologies
Java EE (Web Applications II) 34
service and receives the response and then
connection between web service and client is closed.
This helps in scalability as web service can serve
more number of clients easily.
Firewall Web services use HTTP protocol, which uses port
Friendly number 80. Port number 80 is generally accessible
through Firewall from outside the server. So the
administrator need not configure Firewall to allow
access to any specific port explicitly.

Interoperability
Interoperability allows service and client to be in different
languages and platforms. Allows connection across
heterogeneous networks using ubiquitous web-based standards.
What makes this interoperability possible is support for SOAP
and WSDL. SOAP defines standards for XML messaging and the
mapping of data types. Soap internally uses HTTP for transport
and XML for messaging.
WSDL is an XML document, which describes a Web service in a
standard way.

Types of Web Services


On a technical level, web services can be implemented in various
ways. The two types of web services discussed in this section can be
distinguished as big web services and RESTful web services.

Big Web Services


JAX-WS provides the functionality for big web services.
Big web services use XML messages that follow the Simple
Object Access Protocol (SOAP) standard, an XML language
defining a message architecture and message formats.
Provides description of the operations offered by the service,
written in the Web Services Description Language (WSDL), an
XML language for defining interfaces syntactically.
Project Metro implements JAX-WS.

Srikanth Technologies
Java EE (Web Applications II) 35
RESTful Web Services
JAX-RS provides the functionality for Representational State
Transfer (RESTful) web services.
REST is well suited for basic, ad hoc integration scenarios.
RESTful web services, often better integrated with HTTP than
SOAP-based services, do not require XML messages or WSDL
serviceAPI definitions.
Project Jersey is the production-ready reference implementation
for the JAX-RS specification.

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. 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
Java EE (Web Applications II) 36

SOAP message is made of SOAP Envelope and zero or more


attachments. 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. And it uses the MIME multipart as container for these non-XML
data.

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
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.
A WSDL description is an XML document that gives all the
pertinent information about a Web service, including its name,
the operations that can be called on it, the parameters for those
operations, and the location of where to send requests.
A consumer (Web client) can use the WSDL document to
discover what the service offers and how to access it.

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. It was earlier
called as JAX-RPC (Java API for XML Remote Procedure Call).
JAX-WS is a technology for building web services and clients that
communicate using XML.
JAX-WS allows developers to write message-oriented as well as
RPC-oriented web services.
In JAX-WS, a web service operation invocation is represented by
an XML-based protocol such as SOAP. The SOAP specification
defines the envelope structure, encoding rules, and conventions
for representing web service invocations and responses.
These calls and responses are transmitted as SOAP messages
(XML files) over HTTP.
Under J2EE context, Web services are defined as a set of
endpoints operating on messages.

Srikanth Technologies
Java EE (Web Applications II) 38
The endpoints receive request messages and then send back
response messages.
These endpoints are operating within a container, which provides
Web services runtime environment in the same way EJB
container provides runtime environment for EJB beans.
Another aspect to note is that a Web service is described in
WSDL document and this service description can be published to
a registry.
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.

How does JAX-WS work?


Although SOAP messages are complex, the JAX-WS API hides
this complexity from the application developer.
Client programs are also easy to code. A client creates a proxy (a
local object representing the service) and then simply invokes
methods on the proxy.
With JAX-WS, the developer does not generate or parse SOAP
messages.
It is the JAX-WS runtime system that converts the API calls and
responses to and from SOAP messages.

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.
A service endpoint interface (SEI) is a Java interface that
declares the methods that a client can invoke on the service.
An SEI is not required when building a JAX-WS endpoint. The
web service implementation class implicitly defines an SEI.
Srikanth Technologies
Java EE (Web Applications II) 39
The implementing class must be annotated with either the
WebService or WebServiceProvider annotation.
The implementing class may explicitly reference an SEI through
the endpointInterface element of the @WebService annotation,
but is not required to do so.
If no endpointInterface is specified in @WebService, an SEI is
implicitly defined for the implementing class.
The business methods of the implementing class must be public,
and must not be declared static or final.
Business methods that are exposed to web service clients must
be annotated with WebMethod.
Business methods that are exposed to web service clients must
have JAX-B-compatible parameters and return types.
Implementing class must not be declared final and must not
be abstract.
The implementing class must have a default public constructor.
The implementing class may use the PostConstruct or PreDestroy
annotations on its methods for lifecycle event callbacks.
The @PostConstruct method is called by the container before
the implementing class begins responding to web service clients.
The @PreDestroy method is called by the container before the
endpoint is removed from operation.

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.

Srikanth Technologies
Java EE (Web Applications II) 40
In order to use any implementation, we need to download
appropriate libraries (.jar files) and configure other components.

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.

WEB-INF/web.xml
01: <web-app version="3.1"
02: xmlns="http://xmlns.jcp.org/xml/ns/javaee"
03: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04: xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
05: http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
06:
07: <display-name>Metro Services Demo</display-name>
08: <listener>
09: <listener-class>
10: com.sun.xml.ws.transport.http.servlet.
11: WSServletContextListener
12: </listener-class>
13: </listener>
14: <servlet>
15: <servlet-name>metro-servlet</servlet-name>
16: <servlet-class>
17: com.sun.xml.ws.transport.http.servlet.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.xml which


provides information about web services in the current project.

01: <?xml version="1.0" encoding="UTF-8"?>


02: <endpoints
03: xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
04: version="2.0">

Srikanth Technologies
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. It can
be hosted on any server that supports Java EE web services.

01: package metro;


02: import java.util.Date;
03: import javax.jws.WebMethod;
04: import javax.jws.WebService;
05:
06: @WebService
07: public class HelloService {
08: @WebMethod
09: public Date getCurrentDate() {
10: return new Date();
11: }
12: @WebMethod
13: public String getMessage(String name) {
14: return "Hello ," + name;
15: }
16: }

Annotation WebService specifies the class HelloService is a web


service. Annotation WebMethod is used to create web method,
which can be called from consumer of the web service.

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
Java EE (Web Applications II) 42

Click on WSDL link to get WSDL generated for this web service.

Once Web Service is published to Tomcat, it can be consumed from


any other application irrespective of language, technology and
platform.

Consuming Web Service


In order to consume a web service, we have to create a web service
proxy using the following procedure in Eclipse.

Create a new Java Project.


Select src folder and right click. From popup menu select Other.
Select Web Services and Web Service Client option under
that. The following window is displayed.

Srikanth Technologies
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.
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.

Srikanth Technologies
Java EE (Web Applications II) 44

Here is the code for HelloClient, which uses proxy to call


getMessage() method of the Web Service.

01: package metroclient;


02: import metro.HelloServiceProxy;
03: public class HelloClient {
04: public static void main(String[] args) throws Exception {
05: HelloServiceProxy proxy = new HelloServiceProxy();
06: System.out.println(proxy.getMessage("Srikanth"));
07: }
08: }

Srikanth Technologies
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.

Attribute Meaning
endpointInterface The complete name of the service endpoint
interface defining the services abstract Web
Service contract.
name The name of the Web Service.
portName The port name of the Web Service.
serviceName The service name of the Web Service.
targetNamespace If the @WebService.targetNamespace annotation
is on a service endpoint interface, the
targetNamespace is used for the namespace for
the wsdl:portType (and associated XML
elements).
wsdlLocation The location of a pre-defined WSDL.

@WebMethod
It customizes a method that is exposed as a Web Service operation.
Method is not required to throw java.rmi.RemoteException.

Attribute Meaning
String action The action for this operation.
boolean exclude Marks a method to NOT be exposed as a web
method.
String Name of the wsdl:operation matching this
operationName method.

@WebParam
Customizes the mapping of an individual parameter to a Web
Service message part and XML element.

Attribute Meaning
boolean header If true, the parameter is pulled from a message
header rather than the message body.

Srikanth Technologies
Java EE (Web Applications II) 46
WebParam.Mode The direction in which the parameter is flowing
mode (One of IN, OUT, or INOUT).
String name Name of the parameter.
String partName The name of the wsdl:part representing this
parameter.
String The XML namespace for the parameter.
targetNamespace

@WebResult
It customizes the mapping of the return value to a WSDL part and
XML element.

Attribute Meaning
boolean header If true, the result is pulled from a message
header rather than the message body.
String name Name of return value.
String partName The name of the wsdl:part representing this
return value.
String The XML namespace for the return value.
targetNamespace

A web service to provide details of an Employee


The following web service provides details of employees by
accessing Oracle database.

Employee.java
01: package metro;
02:
03: public class Employee {
04: private String id, name;
05: private double salary;
06: public String getId() {
07: return id;
08: }
09: public void setId(String id) {
10: this.id = id;
11: }
12: public String getName() {

Srikanth Technologies
Java EE (Web Applications II) 47
13: return name;
14: }
15: public void setName(String name) {
16: this.name = name;
17: }
18: public double getSalary() {
19: return salary;
20: }
21: public void setSalary(double salary) {
22: this.salary = salary;
23: }
24: }

Employees.java
01: package metro;
02: import java.util.ArrayList;
03: import javax.jws.*;
04: import javax.sql.rowset.CachedRowSet;
05: import oracle.jdbc.rowset.OracleCachedRowSet;
06: @WebService(serviceName = "EmployeeService")
07: public class EmployeeService {
08: @WebMethod
09: public ArrayList<Employee> getEmployees() {
10: try (CachedRowSet rs = new OracleCachedRowSet()) {
11: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
12: rs.setUsername("hr");
13: rs.setPassword("hr");
14: rs.setCommand("select * from employees");
15: rs.execute();
16: ArrayList<Employee> el = new ArrayList<>();
17: while (rs.next()) {
18: Employee e = new Employee();
19: e.setId(rs.getString("employee_id"));
20: e.setName(rs.getString("first_name"));
21: e.setSalary(rs.getDouble("salary"));
22: el.add(e);
23: }
24: return el;
25: } catch (Exception ex) {
26: System.out.println(ex.getMessage());
27: return null;
28: }
29: }

Srikanth Technologies
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.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
36: rs.setUsername("hr");
37: rs.setPassword("hr");
38: rs.setCommand
39: ("select * from employees where employee_id=?");
40: rs.setString(1, empid);
41: rs.execute();
42: if (rs.next()) {
43: Employee e = new Employee();
44: e.setId(rs.getString("employee_id"));
45: e.setName(rs.getString("first_name"));
46: e.setSalary(rs.getDouble("salary"));
47: return e;
48: } else {
49: return null;
50: }
51: } catch (Exception ex) {
52: System.out.println(ex.getMessage());
53: return null;
54: }
55: } // getDetails()
56: } // EmployeeService

EmployeeClient.java
01: package metroclient;
02: import metro.Employee;
03: import metro.EmployeeServiceProxy;
04: public class EmployeeClient {
05: public static void main(String[] args) throws Exception {
06: EmployeeServiceProxy proxy = new EmployeeServiceProxy();
07: Employee list [] = proxy.getEmployees();
08: for(Employee e : list)
09: System.out.println(e.getName());
10:
11: Employee e = proxy.getDetails("111");
12: System.out.println(e.getName());
13: }
14: }

Srikanth Technologies
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. Application developers
don't need to know the details of these mappings, 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.

Java Class XML Data Type


java.lang.String xs:string
java.math.BigInteger xs:integer
java.math.BigDecimal xs:decimal
java.util.Calendar xs:dateTime
java.util.Date xs:dateTime
javax.xml.namespace.QName xs:QName
java.net.URI xs:string
javax.xml.datatype.XMLGregorianCalendar xs:anySimpleType
javax.xml.datatype.Duration xs:duration
java.lang.Object xs:anyType
java.awt.Image xs:base64Binary
javax.activation.DataHandler xs:base64Binary
javax.xml.transform.Source xs:base64Binary
java.util.UUID xs:string

Srikanth Technologies
Java EE (Web Applications II) 50
Unmarshalling
Unmarshlling provides a client application the ability to convert
XML data into JAXB-derived Java objects.
Marshalling provides a client application the ability to convert a
JAXB-derived Java object tree back into XML data.
By default, the Marshaller uses UTF-8 encoding when generating
XML data.
Client applications are not required to validate the Java content
tree before marshalling. 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
Validation is the process of verifying that an XML document
meets all the constraints expressed in the schema.
JAXB 1.0 provided validation at unmarshal time and also enabled
on-demand validation on a JAXB content tree.
JAXB 2.0 only allows validation at unmarshal and marshal time.
A web service processing model is to be lax in reading data and
strict on writing it out. To meet that model, validation was added
to marshal time, so that one could confirm that they did not
invalidate the XML document when modifying the document in
JAXB form.

Srikanth Technologies
Java EE (Web Applications II) 51
RESTful Web Services
Jersey, the reference implementation of JAX-RS, implements
support for the annotations defined in JSR 311, making it easy for
developers to build RESTful web services by using the Java
programming language.

What are RESTful Web Services?


RESTful web services are built to work best on the Web.
Representational State Transfer (REST) is an architectural style
that specifies constraints, such as the uniform interface, that if
applied to a web service, induce desirable properties, such as
performance, scalability, and modifiability, which enable services
to work best on the Web.
In the REST architectural style, data and functionality are
considered resources and are accessed using Uniform Resource
Identifiers (URIs), typically links on the Web.

Advantages of RESTful Services


The following are considered as advantages of Restful services,
mainly compared with SOAP web services.

It is possible to cache result of RESTful web service


Highly interoperable as clients dont need any toolkit (to create
proxy). They just need to access URL and receive the response
sent by URL.
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.
The response could be XML, JSON or plain text.

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, such as @GET, @PUT, @POST,
or @DELETE.

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

01: package rest;


02: public class Book {
03: String title;
04: double price;
05: public Book(String title, double price) {
06: super();
07: this.title = title;
08: this.price = price;
09: }
10: public String getTitle() {
11: return title;
12: }
13: public void setTitle(String title) {
14: this.title = title;
15: }
16: public double getPrice() {
17: return price;
18: }
19: public void setPrice(double price) {
20: this.price = price;
21: }
22: }

01: package rest;


02: import java.util.ArrayList;
03: import java.util.List;
04: import javax.ws.rs.GET;
05: import javax.ws.rs.Path;
06: import javax.ws.rs.PathParam;
07: import javax.ws.rs.Produces;
08: import javax.ws.rs.core.MediaType;
09:
10: @Path("/books")
11: public class Books {
12: List<Book> books = new ArrayList<>();
13: public Books() {
14: books.add(new Book("C Language For Beginners",99));

Srikanth Technologies
Java EE (Web Applications II) 58
15: books.add(new Book("Oracle Database 12c
16: for Beginners",149));
17: books.add( new Book("Java SE Course Material",149));
18: books.add( new Book("Java EE Course Material",149));
19: }
20: @GET
21: @Produces(MediaType.APPLICATION_JSON)
22: Public List<Book> getFirstBook() {
23: return books;
24: }
25: @GET
26: @Path("/{id}")
27: @Produces(MediaType.APPLICATION_JSON)
28: public Book getOneBook(@PathParam("id") int id) {
29: return books.get(id);
30: }
31: }

JavaScript Client
The following code invokes restful web service and displays the data
in the client using JavaScript. It uses JQuery to make an Ajax call to
web services and process the Json returned by web service. So
make sure you download jQuery from jquery.com and include it in
this project.

BooksClient.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: $.getJSON("http://localhost:8888/jersey/rest/books",
09: {}, displayResult);
10: }
11: function displayResult(data) {
12: if (data.length == 0) {
13: $("#error").html("Sorry! No Books found!");
14: $("#books").html("");
15: return;
16: }
Srikanth Technologies
Java EE (Web Applications II) 59
17:
18: $("#error").html("");
19: var out = '';
20: for (var i = 0; i < data.length; i++) {
21: out += '<li>'+ data[i].title + ' - ' +
22: data[i].price +"</li>";
23: }
24: $("#books").html(out);
25: }
26:
27: getBooks(); // 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;font-weight:bold" id="error"></div>
35: </body>
36: </html>

Srikanth Technologies
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, which are lightweight container-
managed objects (POJOs) with minimal requirements. They
support a small set of basic services, such as resource injection,
lifecycle callbacks and interceptors.
A web deployment descriptor (web.xml file)
Optionally, one or more application configuration resource files,
such as a faces-config.xml file, which can be used to define page
navigation rules and configure beans and other custom objects,
such as custom components

Srikanth Technologies
Java EE (Web Applications II) 61
Optionally, a set of custom objects, which can include custom
components, validators, converters, or listeners, 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; the final version, JSF 1.0, was released on
March-2004, and JSF 1.1 arrived on May, 2004. JSF 1.2 was
release in May, 2006.
JSF 2.0 (JSR 314) is part of Java EE 6.0.
JSF 2.2 (JSR 344) was released in April, 2013.
The companies and organizations (other than Sun) involved in
developing Faces include the Apache Software Foundation, BEA
Systems, Borland Software, IBM, Oracle, Macromedia, and many
others.
Get more information at https://javaserverfaces.dev.java.net

Advantages of JSF
The following are the important reasons to use JSF:

MVC (Model View Controller) for web applications. It offers a


clean separation between behaviour and presentation
Provides a rich architecture for managing component state,
processing component data, validating user input, and handling
events
Easy to use
Extensible Component and Rendering architecture
Standard - part of Java EE 7.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
Java EE (Web Applications II) 62
JSF Implementations
JSF is a set of specifications. Anyone can implement these
specifications to provide JSF support. The following are some of the
popular implementations of JSF.

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.


Creating the pages using the UI component and core tags.
Developing the Managed beans.

Mapping the FacesServlet Instance


All JavaServer Faces applications must include a mapping to the
FacesServlet instance in their deployment descriptors.
The FacesServlet instance accepts incoming requests, passes
them to the life cycle for processing, and initializes resources.

web.xml
01: <servlet>
02: <servlet-name>Faces Servlet</servlet-name>
03: <servlet-class>javax.faces.webapp.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
Java EE (Web Applications II) 63
Creating JSF Pages
JSF pages could be either JSPs or XHTML documents called Facelets.
Starting from JSF 2.0, Facelet is the default presentation language.

perfect.xhtml
01: <!DOCTYPE html PUBLIC
02: "-//W3C//DTD XHTML 1.0 Transitional//EN"
03: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04: <html xmlns="http://www.w3.org/1999/xhtml"
05: xmlns:h="http://java.sun.com/jsf/html"
06: xmlns:f="http://java.sun.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.check}" type="submit" />
24: <p/>
25: <h3>#{perfectBean.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
Java EE (Web Applications II) 64
PerfectBean.java
01: package beans;
02: import javax.faces.bean.ManagedBean;
03: import javax.faces.bean.RequestScoped;
04: import javax.faces.event.ActionEvent;
05: @ManagedBean
06: @RequestScoped
07: public class PerfectBean {
08: private int number;
09: private String message;
10: public String getMessage() {
11: return message;
12: }
13: public void setMessage(String message) {
14: this.message = message;
15: }
16:
17: public int getNumber() {
18: return number;
19: }
20: public void setNumber(int number) {
21: this.number = number;
22: }
23: public void check(ActionEvent evt) {
24: int sum = 0;
25: for (int i = 1; i <= number / 2; i++) {
26: if (number % i == 0) {
27: sum += i;
28: }
29: }
30: if (sum == number) {
31: message = "Perfect Number";
32: } else {
33: message = "Not a Perfect Number";
34: }
35: }
36: }

Srikanth Technologies
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, web pages built with XHTML have an
.xhtml extension
To support the JavaServer Faces tag library mechanism, Facelets
uses XML namespace declarations

Old namespace JSF 2.2 namespace


http://java.sun.com/jsf/core http://xmlns.jcp.org/jsf/core
http://java.sun.com/jsf/html http://xmlns.jcp.org/jsf/html
http://java.sun.com/jsf/facelets http://xmlns.jcp.org/jsf/facelets
http://java.sun.com/jsp/jstl/core http://xmlns.jcp.org/jsp/jstl/core
http://java.sun.com/jsp/jstl/functions http://xmlns.jcp.org/jsp/jstl/functions

URI Prefix Contents


http://java.sun.com/jsf/facelets ui Tags for templating
http://java.sun.com/jsf/html h JavaServer Faces
component tags for all
UIComponent objects
http://java.sun.com/jsf/core f Tags for JavaServer
Faces custom actions that
are independent of any
particular render kit

Srikanth Technologies
Java EE (Web Applications II) 66
http://java.sun.com/jsp/jstl/core c JSTL 1.2 Core Tags
http://java.sun.com/jsp/jstl/functions fn JSTL 1.2 Functions Tags

Common attributes for UI components


The following attributes are supported by many UI components.

Attribute Description
binding Identifies a bean property and binds the component
instance to it.
id Uniquely identifies the component.
immediate If set to true, indicates that any events, validations, and
conversion associated with the component should happen
when request parameter values are applied.
rendered Specifies a condition under which the component should
be rendered. If the condition is not satisfied, the
component is not rendered.
style Specifies a Cascading Style Sheet (CSS) style for the tag.
styleClass Specifies a CSS class that contains definitions of the
styles.
value Specifies the value of the component, in the form of a
value expression.

Using Text Components


The following are the tags related to components that take text from
user.

Tag Function
h:inputHidden Allows a page author to include a hidden variable in
a page
h:inputSecret The standard password field - accepts one line of
text with no spaces and displays it as a set of
asterisks as it is typed
Srikanth Technologies
Java EE (Web Applications II) 67
h:inputText The standard text field - accepts a one-line text
string
h:inputTextarea The standard text area - accepts multiple lines of
text

The following are important attributes of input elements.

Attribute Description
converter Identifies a converter that will be used to
convert the components local data.
converterMessage Specifies an error message to display when the
converter registered on the component fails.
dir Specifies the direction of the text displayed by
this component. Acceptable values are LTR,
meaning left-to-right, and RTL, meaning right-
to-left.
label Specifies a name that can be used to identify
this component in error messages.
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.
validator Identifies a method expression pointing to a
managed bean method that performs
validation on the components data.
validatorMessage Specifies an error message to display when the
validator registered on the component fails to
validate the components local value.
valueChangeListener Points to a managed bean method that handles
the event of entering a value in this
component.

Srikanth Technologies
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 - 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, such as submitting a form, and for navigating to another
page. These tags are called command component tags because
they perform an action when activated.
The h:commandButton tag is rendered as a button.
The h:commandLink tag is rendered as a hyperlink.

Attribute Description
action Is either a logical outcome String or a method
expression pointing to a bean method that returns a
logical outcome String. In either case, the logical
outcome String is used to determine what page to
access when the command component tag is
activated.
actionListener Is a method expression pointing to a bean method
that processes an action event fired by the
command component tag.

Srikanth Technologies
Java EE (Web Applications II) 69
h:panelGrid and h:panelGroup Tags
In a JavaServer Faces application, you use a panel as a layout
container for a set of other components. A panel is rendered as a
HTML table.

Tag Attributes Function


h:panelGrid columns,columnClasses, Displays a table
footerClass,headerClass,
panelClass,
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, whether it is the only value available or one of a
set of choices.

The most common tags for this kind of component are as follows:

Component Description
h:selectBooleanCheckbox displayed as a check box, which
represents a Boolean state
h:selectOneRadio displayed as a set of radio buttons
h:selectOneMenu displayed as a drop-down menu, with a
scrollable list
h:selectOneListbox displayed as a list box, with an
unscrollable list

01: <h:selectOneMenu id="shippingOption" required="true"


02: value="#{cashier.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
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. 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.newsletters}">
03: <f:selectItems value="#{cashier.newsletterItems}"/>
04: </h:selectManyCheckbox>

Conversion Model
A JavaServer Faces application can optionally associate a component
with server-side object data. This object is a JavaBeans component,
such as a backing bean. An application gets and sets the object data
for a component by calling the appropriate object properties for that
component.

When a component is bound to an object, the application has two


views of the components data:

The model view, in which data is represented as data types, such


as int or long.
The presentation view, in which data is represented in a manner
that can be read or modified by the user. For example, a
java.util.Date might be represented as a text string in the
format mm/dd/yy or as a set of three text strings.

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 components data.

Srikanth Technologies
Java EE (Web Applications II) 71
Some component data must be bound to properties of a particular
type. For example, a UISelectBoolean component must be bound to
a property of type boolean or java.lang.Boolean.

The following tags are used to specify explicit conversion.

Tag Attributes
f:convertNumber currencyCode, currencySymbol ,groupingUsed,
integerOnly, locale, max(min)FractionDigits,
max(min)IntegerDigits, pattern
(DecimalFormat),
type - number, currency, percentage
f:convertDateTime type - date, time, both, dateStyle, timeStyle -
default, short, medium, long, full, pattern
(SimpleDateFormat), locale, timeZone

Validation Model
JavaServer Faces technology supports a mechanism for validating
the local data of editable components (such as text fields). This
validation occurs before the corresponding model data is updated to
match the local value.

Define bean properties to be simple standard types int, long,


double, boolean, char etc.
System attempts to convert automatically to required type
If there is conversion error, 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. It returns empty
string if there is no message
Add immediate attribute to bypass validation. For ex.,
h:commandButton with logout or cancel operation.

Srikanth Technologies
Java EE (Web Applications II) 72
Tag Function Attributes
validateBean Registers a bean validator for validationGroups
the component.
validateDoubleRange Checks whether the local value minimum,
of a component is within a maximum
certain range. The value must
be floating-point or convertible
to floating-point.
validateLength Checks whether the length of a minimum,
components local value is maximum
within a certain range. The
value must be a String.
validateLongRange Checks whether the local value minimum,
of a component is within a maximum
certain range. The value must
be any numeric type
or String that can be converted
to a long.
validateRegEx Checks whether the local value pattern
of a component is a match
against a regular expression
from the
java.util.regex package.
validateRequired Ensures that the local value is
not empty on an
EditableValueHolder component.

Each of these validators has one or more standard error messages


associated with it.

If you have registered one of these validators onto a component on


your page, and the validator is unable to validate the components
value, the validators error message will display on the page.

Srikanth Technologies
Java EE (Web Applications II) 73
For example, the error message that is displayed when the
components 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, the {1} substitution parameter is replaced by the


components label or id, and the {0} substitution parameter is
replaced with the maximum value allowed by the validator.

Integrating Bean Validation and JSF


The following example shows how to integrate Bean Validation with
JSF.

01: package beans;


02: import javax.faces.bean.ManagedBean;
03: import javax.validation.constraints.Size;
04:
05: @ManagedBean
06: public class User {
07: private String uname,password, message;
08: @Size(min=4,max=10,message="Username must be
09: 4 to 10 chars")
10: public String getUname() {
11: return uname;
12: }
13: public void setUname(String uname) {
14: this.uname = uname;
15: }
16: @Size ( min=1, message="Password is required!")
17: public String getPassword() {
18: return password;
19: }
20: public void setPassword(String password) {
21: this.password = password;
22: }
23: public String getMessage() {
24: return message;
25: }
26: public void setMessage(String message) {

Srikanth Technologies
Java EE (Web Applications II) 74
27: this.message = message;
28: }
29: public String login() {
30: if ( uname.equals("admin") && password.equals("admin"))
31: return "home";
32: else {
33: message = "Sorry! Invalid Login!";
34: return "login";
35: }
36: }
37: }
login.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:h="http://xmlns.jcp.org/jsf/html"
07: xmlns:f="http://xmlns.jcp.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.uname}">
16: <f:validateBean />
17: </h:inputText>
18: <h:message for="uname" />
19: <p/>
20: Password <br/>
21: <h:inputSecret id="password" value="#{user.password}">
22: <f:validateBean />
23: </h:inputSecret>
24: <h:message for="password" />
25: <p/>
26: <h:commandButton action="#{user.login}" value="Login"/>
27: <p/>
28: <h3>#{user.message}</h3>
29: </h:form>
30: </h:body>
31: </html>

Srikanth Technologies
Java EE (Web Applications II) 75
Navigation
Navigation in JSF may be either implicit or explicit.
Explicit navigation is specified using elements in faces-
config.xml.
JSF 2.0 introduced simple navigation defaults that reduce
navigation-related process.
If no matching navigation case is found after checking all
available rules, the navigation handler checks to see whether the
action outcome corresponds to a view id. If a view matching the
action outcome is found, an implicit navigation to the matching
view occurs.

01: @ManagedBean(name="registerBean")
02: public class RegisterBean {
03: private String email, message, phone;
04: public String register() {
05: if (done)
06: return "success"; // calls success.xhtml
07: else
08: return "failure"; // calls failure.xhtml
09: }
10: }

Here is an example for explicit navigation using faces-config.xml.

01: <navigation-rule>
02: <from-view-id>/login.xhtml</from-view-id>
03: <navigation-case>
04: <from-outcome>success</from-outcome>
05: <to-view-id>/home.xhtml</to-view-id>
06: </navigation-case>
07: <navigation-case>
08: <from-outcome>failure</from-outcome>
09: <to-view-id>/loginfail.xhtml</to-view-id>
10: </navigation-case>
11: </navigation-rule>

Srikanth Technologies
Java EE (Web Applications II) 76
Pass-through Attributes
JSF 2.2 introduces the so-called pass-through attributes to
support new and modified attributes defined in HTML5.
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.jcp.org/jsf/passthrough and
associate attributes with this namespace to pass them to client.

PersonBean.java
01: package beans;
02: import javax.enterprise.context.RequestScoped;
03: import javax.faces.bean.ManagedBean;
04: @ManagedBean
05: @RequestScoped
06: public class PersonBean {
07: private String name, email,mobile;
08: private int age;
09: private String message;
10: // getter and setter methods
11: }

Person.xhtml
01:<?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:h="http://xmlns.jcp.org/jsf/html"
07: xmlns:f="http://xmlns.jcp.org/jsf/core"
08: xmlns:p="http://xmlns.jcp.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.name}"
17: p:placeholder="Fullname" p:required="required"/>
18: <p/>

Srikanth Technologies
Java EE (Web Applications II) 77
19: Email :
20: <h:inputText value="#{personBean.email}"
21: p:placeholder="Email Address"
22: p:required="required" p:type="email" /> <p/>
23: Mobile :
24: <h:inputText value="#{personBean.mobile}"
25: title="10 digits mobile number"
26: p:pattern="^[0-9]{10}$" p:required="required" /><p/>
27: Age :
28: <h:inputText value="#{personBean.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, Object> with
f:passThroughAttributes.

01: <h:inputText id="email" value="#{bean.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.
Events on the client such as user selecting an option in drop-
down listbox, clicking on the button etc., can be associated with
methods that run on the server.
So events on the client are handled on the server.

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
Java EE (Web Applications II) 78
An action event occurs when the user activates a component that
implements ActionSource. These components include buttons and
hyperlinks.

String actionControllerMethod() {
}

ActionListener
We can register an ActionListener implementation on a command
component by nesting an f:actionListener tag within the
components 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. An
example is selecting a check box, an action that results in the
components value changing to true.
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 components tag on the
page
ValueChangeListener is attached to combobox, listbox,
radiobutton, checkbox, textfield etc.
Form is not automatically submitted, 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
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.w3.org/1999/xhtml"
02: xmlns:h="http://java.sun.com/jsf/html"
03: xmlns:f="http://java.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.category}"
12: valueChangeListener="#{booksBean.process}">
13: <f:selectItem itemLabel="Java Books"
14: itemValue="java" />
15: <f:selectItem itemLabel="MS.Net Books"
16: itemValue=".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.category == "java"}'
24: valueChangeListener=
25: "#{booksBean.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
Java EE (Web Applications II) 80
37: "#{booksBean.calculatePrice}"
38: onchange="submit()"
39: rendered='#{booksBean.category==".net"}'>
40: <f:selectItem itemLabel="C# Comp Ref."
41: itemValue="400"/>
42: <f:selectItem itemLabel="ASP.NET 4.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;font-weight:700">
50: <td colspan="2">
51: <h:outputText
52: rendered='#{booksBean.price != ""}'
53: value="Price : #{booksBean.price}" /> </td>
54: </tr>
55: </table>
56: </h:form>
57: </h:body>
58: </html>

BooksBean.java
01: package beans;
02: import javax.faces.bean.ManagedBean;
03: import javax.faces.bean.SessionScoped;
04: import javax.faces.event.ValueChangeEvent;
05:
06: @ManagedBean
07: @SessionScoped
08: public class BooksBean {
09: private String category = "java", price ="";
10: public String getCategory() {
11: return category;
12: }
13: public void setCategory(String category) {
14: this.category = category;
15: }
16: public String getPrice() {
17: return price;
18: }
19: public void setPrice(String price) {

Srikanth Technologies
Java EE (Web Applications II) 81
20: this.price = price;
21: }
22: public void process(ValueChangeEvent e) {
23: category = e.getNewValue().toString();
24: price = "";
25: }
26: public void calculatePrice(ValueChangeEvent e) {
27: price = e.getNewValue().toString();
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, and the server responds with the page translated to HTML.
However, JSF page life cycle is split up into multiple phases in
order to support the sophisticated UI component model, which
requires component data to be converted and validated,
component events to be handled, and component data to be
propagated to beans in an orderly fashion.
JSF implementation handles the request and automatically goes
through the phases in the lifecycle to perform any necessary
conversions, validations, and model updates, and to generate the
response.

Initial request vs. Postback


The life cycle handles both kinds of requests: initial request and
postback. When a user makes an initial request for a page, he or
she is requesting the page for the first time. When a user
executes a postback, 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.
When the life cycle handles an initial request, it only executes the
restore view and renders response phases because there is no
user input or action to process. Conversely, when the life cycle
handles a postback, it executes all of the phases.

Srikanth Technologies
Java EE (Web Applications II) 82
Lifecycle Phase Description
Restore View Finds or creates a tree of components for the
request.
Apply Request Updates the value of local components to
Values equal ones sent in the request.
Process Validations Asks each component to validate itself.
Update Model Updates properties in Managed bean with
Values values of components.
Invoke Application Calls registered listeners.
Render Response Displays the selected view using rendering
technology.

Restore View
A view represents all the components of the page.
FacesServlet examines the request and extracts the view ID,
which is determined by the name of the JSF page.
The JSF framework controller uses the view ID to look up the
components for the current view. If the view doesn't already
exist, the JSF controller creates it. If the view already exists, the
JSF controller uses it.
In the case of a new view, JSF builds the view of the Faces page
and wires the event handlers and validators to the components.
The view is saved in a FacesContext object.
In the case of an initial view (the first time a page is loaded), JSF
creates an empty view. The empty view is populated as the JSF
page is processed. From an initial view, JSF advances directly to
the render response phase.
In the case of a postback, the view corresponding to the page
already exists, so it only needs to be restored. In this case, JSF
uses the existing view's state information to reconstruct its state.

Srikanth Technologies
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.
If some components on the page have their immediate
attributes set to true, then the validation, conversion, and events
associated with these components will be processed during this
phase.
If the value conversion or value validation fails, an error message
is generated and queued in the FacesContext, where it will be
displayed during the render response phase, along with any
other validation errors.
At the end of this phase, the components are set to their new
values.

Process Validations
Conversion and validation normally happen in this phase.
If the local value is invalid, the JavaServer Faces implementation
adds an error message to the FacesContext instance, and the life
cycle advances directly to the render response phase so that the
page is rendered again with the error messages displayed.
If local value changes, component generates value-change
event.

Update Model Values


It can walk the component tree and set the corresponding bean
properties to the components local values.
Only the properties pointed at by an input components value
attribute are updated.

Invoke Application
JSF broadcasts events for this phase to any registered listeners.
JSF sends action listener to any registered action listeners of the
component.

Srikanth Technologies
Java EE (Web Applications II) 85
Render Response
Component values are updated from bean properties.
Sends response back to user.
Saves the state of the view so that it can be restored.
Values are converted to string for display purpose.

Working with Properties Files and Internationalization


Take the following steps to use properties files that contain
messages related to web application:

Create a .properties file in/under WEB-INF/classes. It contains


simple keyName=value pairs.
Load file with f:loadBundle basename gives base file name
and var gives scoped variable (Map) that will hold results.
Output messages using normal expression language constructs -
#{variable.keyName}

i18ndemo.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:f="http://xmlns.jcp.org/jsf/core"
07: xmlns:h="http://xmlns.jcp.org/jsf/html">
08: <h:head>
09: <title>Internationalisation Demo</title>
10: </h:head>
11: <h:body>
12: <f:view
13: locale="#{facesContext.externalContext.request.locale}">
14: <f:loadBundle basename="messages" var="msgs"/>
15: <h2>#{msgs.title}</h2>
16: </f:view>
17: </h:body>
18: </html>

Srikanth Technologies
Java EE (Web Applications II) 86
/WEB-INF/classes/messages.properties
title=Srikanth Technologies

/WEB-INF/classes/messages_es.properties
title=srikanth Tecnologas

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, 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. These parts
include headers, footers, and captions
Facets can have only one child, 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. The
rows attribute specifies the number of rows, starting with the
first row, to be displayed. For example, if you wanted to display
records 2 through 10 of the underlying data, you would set first
to 2 and rows to 9
If columnClasses or rowClasses specify more than one style, 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.faces.model.DataModel object
A java.sql.ResultSet object
A javax.servlet.jsp.jstl.sql.Result object
Srikanth Technologies
Java EE (Web Applications II) 87
A javax.sql.RowSet object
Attribute var contains each element of the collection. Properties
of object can be accessed using JSF expression language.

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.

01: <html xmlns="http://www.w3.org/1999/xhtml"


02: xmlns:h="http://java.sun.com/jsf/html"
03: xmlns:f="http://java.sun.com/jsf/core">
04: <h:head>
05: <title>Jobs</title>
06: <style>
07: .head{color:white;background-color:red;
08: font-family:arial; font-size:20pt;font-weight:700}
09: .colhead {color:white;background-color:gray;
10: font-family:verdana; font-size:12pt;font-weight:700}
11: .foot { color:white;background-color:blue;
12: font-family:arial; font-size:14pt;font-weight:700}
13: .oddrow { background-color:silver}
14: .evenrow { background-color:white}
15: .rows { font-family:verdana}
16: .rightjustify {text-align:right}
17: .leftjustify {text-align:left}
18: </style>
19: </h:head>
20: <h:body>
21: <h:form>
22: <h:dataTable value="#{jobsBean.jobs}" var="job" border="1"
23: footerClass="foot" captionClass="head"

Srikanth Technologies
Java EE (Web Applications II) 88
24: columnClasses="leftjustify,rightjustify,rightjustify"
25: styleClass="rows" headerClass="colhead"
26: rowClasses="evenrow,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.min_salary}
34: </h:column>
35: <h:column>
36: <f:facet name="header">Max Salary</f:facet>
37: #{job.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.count}
43: </center>
44: </f:facet>
45: </h:dataTable>
46: </h:form>
47: </h:body>
48: </html>

JobsBean.java
01: package beans;
02: import javax.faces.bean.ManagedBean;
03: import javax.faces.bean.RequestScoped;
04: import javax.sql.RowSet;
05: import javax.sql.rowset.CachedRowSet;
06: import oracle.jdbc.rowset.OracleCachedRowSet;
07: @ManagedBean
08: @RequestScoped
09: public class JobsBean {
10: private int count;
11: public int getCount() {
12: return count;
13: }
14: public RowSet getJobs() {
15: try {
16: CachedRowSet rs = new OracleCachedRowSet();

Srikanth Technologies
Java EE (Web Applications II) 89
17: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
18: rs.setUsername("hr");
19: rs.setPassword("hr");
20: rs.setCommand("select * from jobs");
21: rs.execute();
22: // count number of rows
23: rs.last();
24: count = rs.getRow();
25: rs.beforeFirst();
26: return rs;
27: } catch (Exception ex) {
28: System.out.println(ex.getMessage());
29: return null;
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.
value The name of a collection of items that this tag iterates
over. The collection may be
a List, array, java.sql.ResultSet, or an individual java
Object. If the collection is null, this tag does nothing.
varStatus String giving a variable name that will refer to status
object.

This has the following properties :


begin, end, step : values of offset, size, and step

Srikanth Technologies
Java EE (Web Applications II) 90
attributes
index- the current index (int)
first/last- is this the first/last iteration? (boolean)
even/odd- is this even/odd iteration? (boolean) (1st
iteration is 0: even)
offset Specifies how far into the collection to start. Default 0.
size Specifies how far down the collection to go. Default is
the end of the collection.
step Specifies how far to jump down the collection after each
item. Default is 1.

01: <ul>
02: <ui:repeat value="#{personsBean.persons}" var="person"
03: offset="2" size="4">
04: <li>
05: #{person.name} : #{person.age}
06: #{person.age lt 30 ? "Young" : "Middle Aged"}
07: <ui:fragment rendered ="#{person.name.length() > 15}">
08: Big Name
09: </ui:fragment>
10: </li>
11: </ui:repeat>
12: </ul>

Person.java
01: package beans;
02: public class Person {
03: private String name;
04: private int age;
05: public Person(String name, int age) {
06: this.name = name;
07: this.age = age;
08: }
09: public int getAge() {
10: return age;
11: }
12: public void setAge(int age) {
13: this.age = age;
14: }
15: public String getName() {
16: return name;

Srikanth Technologies
Java EE (Web Applications II) 91
17: }
18: public void setName(String name) {
19: this.name = name;
20: }
21: }

PersonsBean.java
01: package beans;
02: import java.util.ArrayList;
03: import java.util.List;
04: import javax.faces.bean.ManagedBean;
05: @ManagedBean
06: public class PersonsBean {
07: public List<Person> getPersons() {
08: ArrayList<Person> persons = new ArrayList();
09: persons.add( new Person("Mr.John Resig",32));
10: persons.add( new Person("Mr.Joe Stagner",42));
11: persons.add( new Person("Mr.Scott Mitchell",38));
12: persons.add( new Person("Mr.Rod Johnson",41));
13: return persons;
14: }
15: }

AJAX Support using <f:ajax>


JSF 2.0 supports integrated Ajax using <f:ajax> tag.
The presence of the <f:ajax> tag triggers the Ajax request.
This allows Ajax requests to be issued without requiring the page
author to write any JavaScript code.
This tag serves two roles depending on its placement. If this tag
is nested within a single component, it will associate an Ajax
action with that component. If this tag is placed around a group
of components it will associate an Ajax action with all
components that support the event attribute.

Attribute Description
event A String identifying the type of event the Ajax action will
apply to. If specified, it must be one of the events
supported by the component the Ajax behavior is being
applied to. If not specified, the default event is
determined for the component. The default event is
Srikanth Technologies
Java EE (Web Applications II) 92
action for ActionSource components and
valueChange for EditableValueHolder components.
execute If a literal is specified, it must be a space delimited
String of component identifiers and/or one of the
keywords given below.

@all - All component identifiers


@none - No identifiers
@this - The element that triggered the request
@form - The enclosing form

If not specified, then @this is the default. If a


ValueExpression is specified, it must refer to a property
that returns a Collection of Strings.
render A Collection that identifies a list of components to be
rendered on the client. It has the same options as
execute attribute. If not specified, then @none is the
default.

If a ValueExpression is specified, it must refer to a


property that returns a Collection of Strings.
onevent The name of a JavaScript function that will handle
events.
onerror The name of a JavaScript function that will handle
errors.
listener The name of the listener method that is called when an
AjaxBehaviorEvent has been broadcast for the listener.

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.

Srikanth Technologies
Java EE (Web Applications II) 93
The listener's processAjaxBehavior method is called once during
the Invoke Application phase of the lifecycle.

<f:ajax listener="#{mybean.someaction}" render="somecomponent" />

The following code represents the someaction method in mybean.

01: public void someaction(AjaxBehaviorEvent event) {


02: dosomething;
03: }

phonedirectory.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <html xmlns="http://www.w3.org/1999/xhtml"
03: xmlns:h="http://java.sun.com/jsf/html"
04: xmlns:f="http://java.sun.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.name}" />
11: <p/>
12: <h:commandButton actionListener="#{directoryBean.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.email}" id="email"/>
20: </h:form>
21: </h:body>
22: </html>

Srikanth Technologies
Java EE (Web Applications II) 94
DirectoryBean.java
01: import java.util.TreeMap;
02: import javax.faces.bean.ManagedBean;
03: import javax.faces.bean.RequestScoped;
04: import javax.faces.event.ActionEvent;
05:
06: @ManagedBean(name="directoryBean")
07: @RequestScoped
08: public class DirectoryBean {
09: private TreeMap<String,String>directory
10: = new TreeMap<String,String>();
11: private String name,phone, email;
12: public DirectoryBean() {
13: directory.put("Resig","9000099999:resig@yahoo.com");
14: directory.put("John", "9000011111:john@yahoo.com");
15: }
16: public String getName() { return name; }
17: public void setName(String name) {
18: this.name = name;
19: }
20: public String getPhone() { return phone;}
21: public void setPhone(String phone) {
22: this.phone = phone;
23: }
24: public void search(ActionEvent evt) {
25: String details = directory.get(name);
26: if ( details == null) {
27: phone = "Sorry! Name not found";
28: email = "";
29: }
30: else {
31: String parts[] = details.split(":");
32: phone = parts[0];
33: email = parts[1];
34: }
35: }
36: public String getEmail() {
37: return email;
38: }
39: public void setEmail(String email) {
40: this.email = email;
41: }
42: }

Srikanth Technologies
Java EE (Web Applications II) 95
Templates
JSF provides the tools to implement user interfaces that are easy
to extend and reuse. Templating is a useful Facelets feature that
allows you to create a page that will act as the base, or template,
for the other pages in an application.
By using templates, you can reuse code and avoid recreating
similarly constructed pages. Templating also helps in maintaining
a standard look and feel in an application with a large number of
pages.
A template page is used as a template for other pages, usually
referred to as client pages.
Templates in JSF are similar to Tiles in Struts.

Tag Function
ui:component Defines a component that is created and added to
the component tree.
ui:composition Defines a page composition that optionally uses a
template. Content outside this tag is ignored.
ui:define Defines content that is inserted into a page by a
template.
ui:fragment Similar to the component tag but does not
disregard content outside this tag.
ui:include Encapsulates and reuses content for multiple pages.
ui:insert Inserts content into a template.
ui:param Used to pass parameters to an included file.
ui:repeat Used as an alternative for loop tags, such as
c:forEach or h:dataTable.
ui:remove Removes content from a page.

template.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:h="http://java.sun.com/jsf/html"
07: xmlns:ui="http://java.sun.com/jsf/facelets">
08: <h:head>
Srikanth Technologies
Java EE (Web Applications II) 96
09: <title><ui:insert name="title">Title</ui:insert></title>
10: <h:outputStylesheet library="css" name="default.css"/>
11: </h:head>
12: <h:body>
13: <ui:include src="header.html"></ui:include>
14: <div class="links">
15: <a href="first.xhtml">First Page </a>
16: &nbsp;&nbsp;
17: <a href="second.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.css
01: .main { background-color:red;}
02: .links{ background-color:white;}
03: .head {background-color:yellow;font-size:20pt;
04: font-weight:700;}
05: .title{font-size:16pt;font-weight:700;}
06: body {background-color: silver;}

Header.html
<h1>Templates Demo</h1>

first.xhtml
01: <ui:composition xmlns="http://www.w3.org/1999/xhtml"
02: xmlns:ui="http://java.sun.com/jsf/facelets"
03: template="/template.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
Java EE (Web Applications II) 97
second.xhtml
01: <ui:composition xmlns="http://www.w3.org/1999/xhtml"
02: xmlns:ui="http://java.sun.com/jsf/facelets"
03: template="/template.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.servlet.http.Part referenced in the value attribute.
The form submit encoding must be set to multipart/form-
data in the enctype attribute of the enclosing h:form.

countwords.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:c="http://java.sun.com/jsp/jstl/core"
07: xmlns:f="http://xmlns.jcp.org/jsf/core"
08: xmlns:h="http://xmlns.jcp.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.file}"/>
17: <p/>
18: <h:commandButton value="Upload"
19: actionListener="#{fileBean.upload}" />
20: <p/>
21: <c:if test="#{fileBean.count gt 0}">
22: No. of words in the document are :
23: <h:outputText value="#{fileBean.count}" />
24: </c:if>
25: </h:form>
26: </h:body>
Srikanth Technologies
Java EE (Web Applications II) 98
27: </html>

FileBean.java
01: package beans;
02: import java.io.*;
03: import javax.faces.bean.*
04: import javax.faces.event.ActionEvent;
05: import javax.servlet.http.Part;
06:
07: @ManagedBean
08: @RequestScoped
09: public class FileBean {
10: private Part file;
11: private int count;
12: public Part getFile() {
13: return file;
14: }
15: public void setFile(Part file) {
16: this.file = file;
17: }
18: public int getCount() {
19: return count;
20: }
21: public void setCount(int count) {
22: this.count = count;
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.getInputStream()));
29: String line = br.readLine();
30: count = 0;
31: while (line != null) {
32: String words[] = line.split("[^A-Za-z0-9-]+");
33: count += words.length;
34: line = br.readLine();
35: }
36: br.close();
37: } catch (Exception ex) {
38: System.out.println("Error -->" + ex.getMessage());
39: }
40: }

Srikanth Technologies
Java EE (Web Applications II) 99
41: }

The <viewAction> and <viewParam> components


JSF 2.2 extends GET processing further by allowing you to take
action using viewAction component.
A view action operates like a button command (UICommand)
component.
By default, it is executed during the Invoke Application phase in
response to an initial request.
The viewAction component is declared as a child of the metadata
facet (<f:metadata>). This allows the view action to be
incorporated into the JavaServer Faces lifecycle on both non-
faces (initial) and faces (postback) requests.
Like other UICommand components, the viewAction component
supports declarative navigation as well. So you can write a
navigation rule that is consulted before the page is rendered.

WishBean.java
01: package beans;
02: import java.util.Calendar;
03: import javax.enterprise.context.RequestScoped;
04: import javax.faces.bean.ManagedBean;
05:
06: @ManagedBean
07: @RequestScoped
08: public class WishBean {
09: private String name, message;
10: public String getMessage() {
11: return message;
12: }
13: public void setMessage(String message) {
14: this.message = message;
15: }
16: public String getName() {
17: return name;
18: }
19: public void setName(String name) {
20: this.name = name;
21: }
22: public String wish() {

Srikanth Technologies
Java EE (Web Applications II) 100
23: Calendar c = Calendar.getInstance();
24: int hour = c.get(Calendar.HOUR_OF_DAY);
25: message = name + ", ";
26: if (hour < 12) {
27: message += "Good Morning";
28: } else if (hour < 17) {
29: message += "Good Afternoon";
30: } else {
31: message += "Good Evening";
32: }
33: return null;
34: }
35: }

wish.xhtml
01: <?xml version='1.0' encoding='UTF-8' ?>
02: <!DOCTYPE html PUBLIC
03: "-//W3C//DTD XHTML 1.0 Transitional//EN"
04: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05: <html xmlns="http://www.w3.org/1999/xhtml"
06: xmlns:h="http://java.sun.com/jsf/html"
07: xmlns:f="http://java.sun.com/jsf/core">
08: <f:view>
09: <f:metadata>
10: <f:viewParam name="name" value="#{wishBean.name}"/>
11: <f:viewAction action="#{wishBean.wish}" />
12: </f:metadata>
13: <h:head>
14: <title>ViewAction Demo</title>
15: </h:head>
16: <h:body>
17: <h2> #{wishBean.message} </h2>
18: </h:body>
19: </f:view>
20: </html>

Srikanth Technologies
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.

employees.xhtml
01: <html xmlns="http://www.w3.org/1999/xhtml"
02: xmlns:h="http://java.sun.com/jsf/html"
03: xmlns:f="http://java.sun.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.job}"
09: onchange="submit()">
10: <f:selectItems value="#{employeeBean.jobs}"/>
11: </h:selectOneMenu>
12: <p/>
13: <h:dataTable rendered='#{employeeBean.job != null}'
14: value="#{employeeBean.employees}"
15: var="employee" border="1">
16: <h:column>
17: <f:facet name="header">First Name</f:facet>
18: #{employee.first_name}
19: </h:column>
20: <h:column>
21: <f:facet name="header">Salary</f:facet>
22: #{employee.salary}
23: </h:column>
24: <h:column>
25: <f:facet name="header">Hire Date</f:facet>
26: #{employee.hire_date}
27: </h:column>
28: </h:dataTable>
29: </h:form>
30: </f:view>
31: </h:body>
32: </html>

Srikanth Technologies
Java EE (Web Applications II) 102
EmployeeBean.java
01: package beans;
02: import java.util.ArrayList;
03: import javax.faces.bean.ManagedBean;
04: import javax.faces.model.SelectItem;
05: import javax.sql.RowSet;
06: import javax.sql.rowset.CachedRowSet;
07: import oracle.jdbc.rowset.OracleCachedRowSet;
08: @ManagedBean
09: public class EmployeeBean {
10: private String job;
11: public String getJob() {
12: return job;
13: }
14: public void setJob(String job) {
15: this.job = job;
16: }
17: public ArrayList<SelectItem> getJobs() {
18: try {
19: CachedRowSet rs = new OracleCachedRowSet();
20: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
21: rs.setUsername("hr");
22: rs.setPassword("hr");
23: rs.setCommand("select * from jobs");
24: rs.execute();
25: ArrayList<SelectItem> al =
26: new ArrayList<SelectItem>();
27: while (rs.next()) {
28: al.add(new SelectItem(rs.getString("job_id"),
29: rs.getString("job_title")));
30: }
31: rs.close();
32: return al;
33: } catch (Exception e) {
34: System.out.println("Error In getJobs() -->" +
35: e.getMessage());
36: return null;
37: }
38: }
39: public RowSet getEmployees() {
40: try {
41: CachedRowSet rs = new OracleCachedRowSet();
42: rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
43: rs.setUsername("hr");
Srikanth Technologies
Java EE (Web Applications II) 103
44: rs.setPassword("hr");
45: rs.setCommand
46: ("select * from employees where job_id = ?");
47: rs.setString(1, job);
48: rs.execute();
49: return rs;
50: } catch (Exception e) {
51: System.out.println(e);
52: return (null);
53: }
54: } // getEmployees
55: }

Srikanth Technologies

Você também pode gostar