Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Advanced Java - BSc(CS) v Sem-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Course Code :CS511T Advanced Java BSc(CS)-V Sem

Unit-I

Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We have discussed the above four drivers in the next chapter.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces
for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:


o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
1
Course Code :CS511T Advanced Java BSc(CS)-V Sem

dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the
following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver

JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

Java Database Connectivity with 5 Steps

1. Register the driver class


2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object

There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
2
Course Code :CS511T Advanced Java BSc(CS)-V Sem

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

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException

Example to close connection


con.close();
It avoids explicit connection closing step.

Java Database Connectivity with Oracle


3
Course Code :CS511T Advanced Java BSc(CS)-V Sem

To connect java application with the oracle database, we need to follow 5 following steps. In this
example, we are using Oracle 10g as the database. So we need to know following information for
the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name. You may get
all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.

Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.
create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database


In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and password of the Oracle database.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();
4
Course Code :CS511T Advanced Java BSc(CS)-V Sem

}catch(Exception e){ System.out.println(e);}

}
}
The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.

download the jar file ojdbc14.jar

Two ways to load the jar file:


1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
o temporary
o permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
5
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Connectivity with Access without DSN


There are two ways to connect java application with the access database.
1. Without DSN (Data Source Name)
2. With DSN
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.

Example to Connect Java Application with access without DSN


In this example, we are going to connect the java program with the access database. In such case,
we have created the login table in the access database. There is only one column in the table
named name. Let's get all the name of the login table.

import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";//Here database exists in the current directory

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};


DBQ=" + database + ";DriverID=22;READONLY=true";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){
System.out.println(rs.getString(1));
}

}catch(Exception ee){System.out.println(ee);}

}}

Example to Connect Java Application with access with DSN


Connectivity with type1 driver is not considered good. To connect java application with type1
driver, create DSN first, here we are assuming your dsn name is mydsn.

import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
6
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){
System.out.println(rs.getString(1));
}

}catch(Exception ee){System.out.println(ee);}

}}

The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().

Useful methods of DriverManager class

Method Description

1) public static void is used to register the given driver with


registerDriver(Driver driver): DriverManager.

2) public static void is used to deregister the given driver (drop the
deregisterDriver(Driver driver): driver from the list) with DriverManager.

3) public static Connection is used to establish the connection with the


getConnection(String url): specified url.

4) public static Connection is used to establish the connection with the


getConnection(String url,String specified url, username and password.
userName,String password):

Connection interface
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like commit(),
rollback() etc..
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int
7
Course Code :CS511T Advanced Java BSc(CS)-V Sem

resultSetConcurrency): Creates a Statement object that will generate ResultSet


objects with the given type and concurrency
3) public void setAutoCommit(boolean status): is used to set the commit status.By
default it is true
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous
commit/rollback
6) public void close(): closes the connection and Releases a JDBC resources
immediately

Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns
the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


1) public boolean next(): is used to move the cursor to the one row next
from the current position.

2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.

3) public boolean first(): is used to move the cursor to the first row in
result set object.

8
Course Code :CS511T Advanced Java BSc(CS)-V Sem

4) public boolean last(): is used to move the cursor to the last row in
result set object.

5) public boolean absolute(int row): is used to move the cursor to the specified row
number in the ResultSet object.

6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be
positive or negative.

7) public int getInt(int is used to return the data of specified column


columnIndex): index of the current row as int.

8) public int getInt(String is used to return the data of specified column


columnName): name of the current row as int.

9) public String getString(int is used to return the data of specified column


columnIndex): index of the current row as String.

10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int sets the integer value to the given parameter index.
paramIndex, int value)

public void setString(int sets the String value to the given parameter index.

9
Course Code :CS511T Advanced Java BSc(CS)-V Sem

paramIndex, String value)

public void setFloat(int sets the float value to the given parameter index.
paramIndex, float value)

public void setDouble(int sets the double value to the given parameter index.
paramIndex, double value)

public int executeUpdate() executes the query. It is used for create, drop, insert, update,
delete etc.

public ResultSet executes the select query. It returns an instance of ResultSet.


executeQuery()

Example of PreparedStatement interface that inserts the record


First of all create table as given below:
create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}

Java CallableStatement Interface


CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.
10
Course Code :CS511T Advanced Java BSc(CS)-V Sem

What is the difference between stored procedures and functions.


The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output parameters. Function supports only input parameter.

Exception handling using try/catch block can be Exception handling using try/catch can't be
used in stored procedures. used in user defined functions.

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user420 values(id,name);
end;
/
The table structure is given below:
create table user420(id number(10), name varchar2(200));
In this example, we are going to call the stored procedure INSERTR that receives id and name as
the parameter and inserts it into the table user420. Note that you need to create the user420 table
as well to run this application.
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

11
Course Code :CS511T Advanced Java BSc(CS)-V Sem

System.out.println("success");
}
}

Socket Programming -
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking


1. sharing resources
2. centralize software management

Java Networking Terminology

The widely used java networking terminologies are given below:


1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.

3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.

4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol

12
Course Code :CS511T Advanced Java BSc(CS)-V Sem

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two way communication.
Visit next page for java socket programming.

java.net package
The java.net package provides many classes to deal with networking applications in Java. A list
of these classes is given below:

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.


Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.

13
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

Important methods
Method Description

1) public InputStream returns the InputStream attached


getInputStream() with this socket.

2) public OutputStream returns the OutputStream attached


getOutputStream() with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection


between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming

Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.
14
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Socket s=new Socket("localhost",6666);

Let's see a simple of Java socket programming where client sends a text and server receives and
prints it.

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

File: MyClient.java

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server console.

15
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.

File: MyServer.java

import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
16
Course Code :CS511T Advanced Java BSc(CS)-V Sem

ss.close();
}}

File: MyClient.java

import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}}

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:

A URL contains many information:


1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Constructors of Java URL class

17
Course Code :CS511T Advanced Java BSc(CS)-V Sem

URL(String spec)
Creates an instance of a URL from the String representation.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given
context.

Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given
below.
Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

public String toString() it returns the string representation of the URL.

public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.

public URLConnection it returns the instance of URLConnection i.e.


openConnection() associated with this URL.

public boolean equals(Object it compares the URL with the given object.
obj)

public Object getContent() it returns the content of the URL.

public String getRef() it returns the anchor or reference of the URL.

public URI toURI() it returns a URI of the URL.

18
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Example of Java URL class

import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}

Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

Let us see another example URL class in Java.

import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sour
ceid=chrome&ie=UTF-8");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("Query String: "+url.getQuery());
System.out.println("Path: "+url.getPath());
System.out.println("File: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: https
Host Name: www.google.com
Port Number: -1
19
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Default Port Number: 443


Query String: q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8

Java URLConnection class


The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.
How to get the object of URLConnection class
The openConnection() method of URL class returns the object of URLConnection class. Syntax:
public URLConnection openConnection()throws IOException{}

Displaying source code of a webpage by URLConnecton class

The URLConnection class provides many methods, we can display all the data of a webpage by
using the getInputStream() method. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.

Example of Java URLConnection class

import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. It is a mechanism used for transmitting datagram packets over network.`
A datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
20
Course Code :CS511T Advanced Java BSc(CS)-V Sem

o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with
the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram
socket and binds it with the specified port number and host address.
Java DatagramSocket Class
Method Description

void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.

void close() It closes the datagram socket.

void connect(InetAddress address, It connects the socket to a remote address for the socket.
int port)

void disconnect() It disconnects the socket.

boolean getBroadcast() It tests if SO_BROADCAST is enabled.

DatagramChannel getChannel() It returns the unique DatagramChannel object associated with the
datagram socket.

InetAddress getInetAddress() It returns the address to where the socket is connected.

InetAddress getLocalAddress() It gets the local address to which the socket is connected.

int getLocalPort() It returns the port number on the local host to which the socket is
bound.

SocketAddress It returns the address of the endpoint the socket is bound to.
getLocalSocketAddress()

int getPort() It returns the port number to which the socket is connected.

int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this DatagramSocket
that is the buffer size used by the platform for input on the
DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.

boolean isConnected() It returns the connection state of the socket.

void send(DatagramPacket p) It sends the datagram packet from the socket.

void receive(DatagramPacket p) It receives the datagram packet from the socket.

21
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Unit-II
Applet
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:


o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is
the subclass of Component.
22
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Lifecycle of Java Applet


Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

public void init(): is used to initialized the Applet. It is invoked only once.

public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.

public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.

public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
23
Course Code :CS511T Advanced Java BSc(CS)-V Sem

How to run an Applet?

There are two ways to run an applet


By html file.
By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}

myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
24
Course Code :CS511T Advanced Java BSc(CS)-V Sem

/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet


{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
25
Course Code :CS511T Advanced Java BSc(CS)-V Sem

g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax of drawImage() method:

1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

How to get the object of Image:

The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:

public Image getImage(URL u, String image){}


Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
Example of Image with animation -

import java.awt.*;
import java.applet.*;
public class AniEx extends Applet
{
Image picture;
public void init()
{
picture=getImage(getDocumentBase(),"abc.jpg");
}
26
Course Code :CS511T Advanced Java BSc(CS)-V Sem

public void paint(Graphics g)


{
for(int i=0;i<15;i++)
{
g.drawImage(picture, i,30, this);
try
{
Thread.sleep(100);
}
catch(Exception e){}
}
}
}

/*
<applet code="AniEx.class" width="300" height="300">
</applet>
*/

O/p –

Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method
named getParameter(). Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}

27
Course Code :CS511T Advanced Java BSc(CS)-V Sem

}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Servlets
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.

What is a web application?


A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and
JavaScript. The web components typically execute in Web Server and respond to the HTTP
request.
Web Terminology
Servlet Description

28
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Terminology

Website: static vs It is a collection of related web pages that may contain text, images, audio
dynamic and video.

HTTP It is the data communication protocol used to establish communication


between client and server.

HTTP Requests It is the request send by the computer to a web server that contains all sorts of
potentially interesting information.

Get vs Post It gives the difference between GET and POST request.

Container It is used in java for dynamically generating the web pages on the server side.

Server: Web vs It is used to manage the network resources and for running the program or
Application software that provides services.

Content Type It is HTTP header that provides the description about what are you sending to
the browser.

Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:


29
Course Code :CS511T Advanced Java BSc(CS)-V Sem

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:


1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:


1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface defines methods
that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.

30
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.

public void service(ServletRequest provides response for the incoming request. It is


request,ServletResponse response) invoked at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is
being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer,


copyright, version etc.

Servlet Example by implementing Servlet interface


Let's see the simple example of servlet by implementing the servlet interface.
File: First.java
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}

GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.

31
Course Code :CS511T Advanced Java BSc(CS)-V Sem

You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is
being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to
call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file
and a stack trace.

Servlet Example by inheriting the GenericServlet class


Let's see the simple example of servlet by inheriting the GenericServlet class.
File: First.java
import java.io.*;
import javax.servlet.*;

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

HttpServlet class
1. HttpServlet class
2. Methods of HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specifi
methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:

32
Course Code :CS511T Advanced Java BSc(CS)-V Sem

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the


protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method depending
on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST
request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the
HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

33
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Unit-III
JSP
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to Servlet because it provides more functionality than servlet such as
expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet
in JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
ADVERTISEMENT
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).

34
Course Code :CS511T Advanced Java BSc(CS)-V Sem

o Destroy ( the container invokes jspDestroy() method).

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating the
JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted
into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later
like initialization, committing response to the browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
It will print 10 on the browser.

How to run a simple JSP Page?


35
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Follow the following steps to execute this JSP page:


o Start the server
o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp
o
Do I need to follow the directory structure to run a simple JSP?
No, there is no need of directory structure if you don't have class files or TLD files. For example,
put JSP files in a folder directly and deploy that folder. It will be running fine. However, if you
are using Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.

JSP Scriptlet tag (Scripting elements)


In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
36
Course Code :CS511T Advanced Java BSc(CS)-V Sem

<% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.
ADVERTISEMENT
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The index.html file gets
the username from the user and the welcome.jsp file prints the username with the welcome
message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So
you need not write out.print() to write data. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag


<%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
37
Course Code :CS511T Advanced Java BSc(CS)-V Sem

<body>
<%= "welcome to jsp" %>
</body>
</html>

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag. The index.html file gets
the username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
38
Course Code :CS511T Advanced Java BSc(CS)-V Sem

The syntax of the declaration tag is as follows:


ADVERTISEMENT
<%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside
_jspService() method. the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

JSP Implicit Objects


There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.

39
Course Code :CS511T Advanced Java BSc(CS)-V Sem

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of
JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.

Example of out implicit object


In this example we are simply displaying date and time.
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Output

40
Course Code :CS511T Advanced Java BSc(CS)-V Sem

JSP request implicit object


The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request
by the web container. It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name of the
user with welcome message.
Example of JSP request implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Output

41
Course Code :CS511T Advanced Java BSc(CS)-V Sem

JSP response implicit object


In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.
It can be used to add or manipulate response such as redirect response to another resource, send
error etc.
Let's see the example of response implicit object where we are redirecting the response to the
Google.

Example of response implicit object


index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
Output

42
Course Code :CS511T Advanced Java BSc(CS)-V Sem

JSP config implicit object


In JSP, config is an implicit object of type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page. The config object is created by the web
container for each jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
Example of config implicit object:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
43
Course Code :CS511T Advanced Java BSc(CS)-V Sem

out.print("driver name is="+driver);


%>
Output

JSP application implicit object


In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.
This object can be used to get initialization parameter from configuaration file (web.xml). It can
also be used to get, set or remove attribute from the application scope.
This initialization parameter can be used by all jsp pages.
ADVERTISEMENT
Example of application implicit object:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
44
Course Code :CS511T Advanced Java BSc(CS)-V Sem

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

</web-app>
welcome.jsp
<%

out.print("Welcome "+request.getParameter("uname"));

String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);

%>
Output

45
Course Code :CS511T Advanced Java BSc(CS)-V Sem

session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set,get
or remove attribute or to get session information.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
46
Course Code :CS511T Advanced Java BSc(CS)-V Sem

</html>
welcome.jsp
<html>
<body>
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

session.setAttribute("user",name);

<a href="second.jsp">second jsp page</a>

%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Output

47
Course Code :CS511T Advanced Java BSc(CS)-V Sem

48
Course Code :CS511T Advanced Java BSc(CS)-V Sem

pageContext implicit object


In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can be used
to set,get or remove attribute from one of the following scopes:
o page
o request
o session
o application
In JSP, page scope is the default scope.
Example of pageContext implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
49
Course Code :CS511T Advanced Java BSc(CS)-V Sem

<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
Output

50
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Page implicit object:


In JSP, page is an implicit object of type Object class.This object is assigned to the reference of auto generated
servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
<% this.log("message"); %>

Exception implicit object


In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the
exception. But it can only be used in error pages.It is better to learn it after page directive. Let's see a simple
example:
Example of exception implicit object:
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>

Sorry following exception occured:<%= exception %>

</body>
</html>
To get the full example, click here full example of exception handling in jsp. But, it will be better
to learn it after the JSP Directives.
JSP directives
1. JSP directives
1. page directive

51
Course Code :CS511T Advanced Java BSc(CS)-V Sem

2. Attributes of page directive


The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
ADVERTISEMENT
o page directive
o include directive
o taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage
import
The import attribute is used to import class,interface or all the members of a package.It is similar to import
keyword in java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>

52
Course Code :CS511T Advanced Java BSc(CS)-V Sem

</html>

extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
Example of info attribute
<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.
Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".
isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e.
Expression Language is enabled by default. We see Expression Language later.
<%@ page isELIgnored="true" %>//Now EL will be ignored
isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false, the web
container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before
passing another request to it.If you make the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
53
Course Code :CS511T Advanced Java BSc(CS)-V Sem

errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp file, html file
or text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static
resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

JSP Taglib directive

54
Course Code :CS511T Advanced Java BSc(CS)-V Sem

The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so
it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>

JSP Action Tags


There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we
will see these tags in bean developement.
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html
or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>

Example of jsp:forward action tag without parameter


In this example, we are simply forwarding the request to the printdate.jsp file.
index.jsp
<html>
<body>
55
Course Code :CS511T Advanced Java BSc(CS)-V Sem

<h2>this is index page</h2>


<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Example of jsp:forward action tag with parameter


In this example, we are forwarding the request to the printdate.jsp file with parameter and
printdate.jsp file prints the parameter value with date and time.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="javatpoint.com" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>

jsp:include action tag


The jsp:include action tag is used to include the content of another resource it may be jsp, html
or servlet.
The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag
Code reusability : We can use a page many times such as including header and footer pages in
all pages. So it saves a lot of time.

Difference between jsp include directive and include action


JSP include directive JSP include action
includes resource at translation time. includes resource at request time.
better for static pages. better for dynamic pages.
includes the original content in the generated servlet. calls the include method.
Syntax of jsp:include action tag without parameter
<jsp:include page="relativeURL | <%= expression %>" />
56
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Syntax of jsp:include action tag with parameter


<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>

Example of jsp:include action tag without parameter


In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>

Expression Language (EL) in JSP


The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.
There are many implicit objects, operators and reserve words in EL.
It is the newly added feature in JSP technology version 2.0.

Syntax for Expression Language (EL)


${ expression }

Implicit Objects in Expression Language (EL)


There are many implicit objects in the Expression Language. They are as follows:

Implicit Objects Usage

pageScope it maps the given attribute name with the value set in the page scope

requestScope it maps the given attribute name with the value set in the request scope

sessionScope it maps the given attribute name with the value set in the session scope

applicationScope it maps the given attribute name with the value set in the application scope
57
Course Code :CS511T Advanced Java BSc(CS)-V Sem

param it maps the request parameter to the single value

paramValues it maps the request parameter to an array of values

header it maps the request header name to the single value

headerValues it maps the request header name to an array of values

cookie it maps the given cookie name to the cookie value

initParam it maps the initialization parameter

pageContext it provides access to many objects request, session etc.

EL param example
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input
from the user and sends the request to the process.jsp which in turn prints the name of the user
using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }

EL sessionScope example
In this example, we printing the data stored in the session scope using EL. For this purpose, we
have used sessionScope object.
index.jsp
<h3>welcome to index page</h3>
<%
session.setAttribute("user","sonoo");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }

EL cookie example
index.jsp
<h1>First JSP</h1>
<%
Cookie ck=new Cookie("name","abhishek");
response.addCookie(ck);
%>
<a href="process.jsp">click</a>
process.jsp
58
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Hello, ${cookie.name.value}

Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence
are as follows:
[] .
()
-(unary) not ! empty
* / div % mod
+ - (binary)
< <= > >= lt le gt ge
== != eq ne
&& and
|| or
?:
Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null

JSTL (JSP Standard Tag Library)


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.

JSTL Tags
There JSTL mainly provides five types of tags:

Tag Description
Name

Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL for
the core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.

Function The functions tags provide support for string manipulation and string length. The URL for the
tags functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting The Formatting tags provide support for message formatting, number and date formatting, etc.
tags The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the XML tags
is http://java.sun.com/jsp/jstl/xml and prefix is x.
59
Course Code :CS511T Advanced Java BSc(CS)-V Sem

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

JSTL Function Tags


The JSTL function provides a number of standard functions, most of these functions are common
string manipulation functions. The syntax used for including JSTL function library in your JSP
is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
JSTL Function Tags List
JSTL Functions Description

fn:contains() It is used to test if an input string containing the specified substring in a program.

fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case
insensitive way.

fn:endsWith() It is used to test if an input string ends with the specified suffix.

fn:escapeXml() It escapes the characters that would be interpreted as XML markup.

fn:indexOf() It returns an index within a string of first occurrence of a specified substring.

fn:trim() It removes the blank spaces from both the ends of a string.

fn:startsWith() It is used for checking whether the given string is started with a particular string
value.

fn:split() It splits the string into an array of substrings.

fn:toLowerCase() It converts all the characters of a string to lower case.

fn:toUpperCase() It converts all the characters of a string to upper case.

fn:substring() It returns the subset of a string according to the given start and end position.

fn:substringAfter() It returns the subset of string after a specific substring.

fn:substringBefore() It returns the subset of string before a specific substring.

fn:length() It returns the number of characters inside a string, or the number of items in a
collection.

fn:replace() It replaces all the occurrence of a string with another string sequence.

JSTL fn:contains() Function


60
Course Code :CS511T Advanced Java BSc(CS)-V Sem

The fn:contains() is used for testing if the string containing the specified substring. If the
specified substring is found in the string, it returns true otherwise false.
The syntax used for including the fn:contains() function is:
boolean contains(java.lang.String, java.lang.String)
Let's see the simple example to understand the functionality of fn:contains() function:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var="String" value="Welcome to javatpoint"/>
<c:if test="${fn:contains(String, 'javatpoint')}">
<p>Found javatpoint string<p>
</c:if>
<c:if test="${fn:contains(String, 'JAVATPOINT')}">
<p>Found JAVATPOINT string<p>
</c:if>
</body>
</html>

Output:
Found javatpoint string

JSTL Formatting tags


The formatting tags provide support for message formatting, number and date formatting etc.
The url for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
The JSTL formatting tags are used for internationalized web sites to display and format text, the
time, the date and numbers. The syntax used for including JSTL formatting library in your JSP
is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

61
Course Code :CS511T Advanced Java BSc(CS)-V Sem

Formatting Descriptions
Tags

fmt:parseNumber It is used to Parses the string representation of a currency, percentage or number.

fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time
formatting.

fmt:formatNumber It is used to format the numerical value with specific format or precision.

fmt:parseDate It parses the string representation of a time and date.

fmt:bundle It is used for creating the ResourceBundle objects which will be used by their tag
body.

fmt:setTimeZone It stores the time zone inside a time zone configuration variable.

fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable or the
named scoped variable.

fmt:message It display an internationalized message.

fmt:formatDate It formats the time and/or date using the supplied pattern and styles.

JSTL XML tags


The JSTL XML tags are used for providing a JSP-centric way of manipulating and creating
XML documents.
The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has custom tags
used for interacting with XML data. The syntax used for including JSTL XML tags library in
your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
Before you proceed further with the examples, you need to copy the two XML and XPath
related libraries into the <Tomcat Installation Directory>\lib:
Xalan.jar: Download this jar file from the link:
http://xml.apache.org/xalan-j/index.html
XercesImpl.jar: Download this jar file from the link:
http://www.apache.org/dist/xerces/j/

JSTL XML tags List


XML Descriptions
Tags

x:out Similar to <%= ... > tag, but for XPath expressions.

x:parse It is used for parse the XML data specified either in the tag body or an attribute.

62
Course Code :CS511T Advanced Java BSc(CS)-V Sem

x:set It is used to sets a variable to the value of an XPath expression.

x:choose It is a conditional tag that establish a context for mutually exclusive conditional operations.

x:when It is a subtag of that will include its body if the condition evaluated be 'true'.

x:otherwise It is subtag of that follows tags and runs only if all the prior conditions evaluated be 'false'.

x:if It is used for evaluating the test XPath expression and if it is true, it will processes its body
content.

x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet Language)
transformation.

x:param It is used along with the transform tag for setting the parameter in the XSLT style sheet.

JSTL SQL Tags


The JSTL sql tags provide SQL support. The url for the sql tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
The SQL tag library allows the tag to interact with RDBMSs (Relational Databases) such as
Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL SQL tags library
in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

JSTL SQL Tags List


SQL Tags Descriptions

sql:setDataSource It is used for creating a simple data source suitable only for prototyping.

sql:query It is used for executing the SQL query defined in its sql attribute or the body.

sql:update It is used for executing the SQL update defined in its sql attribute or in the tag body.

sql:param It is used for sets the parameter in an SQL statement to the specified value.

sql:dateParam It is used for sets the parameter in an SQL statement to a specified java.util.Date value.

sql:transaction It is used to provide the nested database action with a common connection.

63

You might also like