BMC 201 Complete Notes
BMC 201 Complete Notes
Q1. What is Server Socket? Discuss the difference between the Socket and
ServerSocket class.
Ans. The ServerSocket class (java.net) can be used to create a server socket.
This object is used to establish communication with the clients.
A server socket waits for requests to come in over the network. It performs some operation based
on that request, and then possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl class.
An application can change the socket factory that creates the socket implementation to configure
itself to create sockets appropriate to the local firewall.
Constructor
ServerSocket(int port) Creates a server socket, bound to the specified port.
Method
public Socket accept() Returns the socket and establish a connection between
server and client.
Syntax
ServerSocket ss=new ServerSocket(Port_no);
Difference between the Socket and ServerSocket class.
ServerSocket Socket
It is placed in server side, which sends request It is placed in client side, which sends request
to client side socket (Socket) and wait for the to server side socket (ServerSocket) and wait
response from client. for the response from serve.
ServerSocket ss=new ServerSocket Socket s = new
(1111); Socket("localhost",1111);
Q2. What is Datagram Socket and Datagram Packet? Explain in detail with
example.
Ans. Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Datagram Socket
DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Constructor
DatagramSocket() It creates a datagram socket and binds it with the available Port
Number on the localhost machine.
DatagramSocket(int port) It creates a datagram socket and binds it with the given Port
Number.
DatagramSocket(int port, It creates a datagram socket and binds it with the specified port
InetAddress address) number and host address.
1
Unit 1 – Java Networking
Datagram Packet
Java DatagramPacket is a message that can be sent or received.
Additionally, packet delivery is not guaranteed.
Datagram packets are used to implement a connectionless packet delivery service.
Each message is routed from one machine to another based solely on information contained within
that packet.
Multiple packets sent from one machine to another might be routed differently, and might arrive in
any order.
Constructor
DatagramPacket(byte[] barr, int length) It creates a datagram packet. This constructor is used to
receive the packets.
DatagramPacket(byte[] barr, int length, It creates a datagram packet. This constructor is used to
InetAddress address, int port) send the packets.
DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0,dp.getLength());
System.out.println(str);
ds.close();
}
}
2
Unit 1 – Java Networking
Q3. Explain InetAddress methods with appropriate example.
Ans. This class represents an Internet Protocol (IP) address.
The java.net.InetAddress class provides methods to get an IP of host name.
It is the superclass of Inet6Address and Inet4Address classes.
There are no constructors for this class but static methods which returns instances of InetAddress
class for general use.
Methods
Method Description
public static InetAddress Determines the IP address of a given host's name.
getByName(String host) InetAddress ip
throws UnknownHostException =InetAddress.getByName("www.darshan.ac.in");
System.out.println(“ip:“+ ip);
public static InetAddress Returns the address of the local host.
getLocalHost() InetAddress ip=InetAddress.getLocalHost();
throws UnknownHostException System.out.println(“LocalHost:“+ip);
URLConnection class
URLConnection is the superclass of all classes that represent a communications link between the
application and a URL.
Instances of this class can be used both to read from and to write to the resource referenced by the
URL.
3
Unit 1 – Java Networking
Method
public InputStream getInputStream() Returns an input stream that reads from this open
throws IOException connection.
public OutputStream getOutputStream() Returns an output stream that writes to this connection.
throws IOException
Example
import java.io.*; //required for input stream
import java.net.*; //required for URL & URLConnection
public class URLConnectionDemo {
public static void main(String[] args){
try{
URL url=new URL("http://www.darshan.ac.in");
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);}
}
}
Q5. How to display IP address and host name for local machine.
Ans. import java.net.InetAddress;
public class Main {
public static void main(String[] args)throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: "+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}
4
Unit 1 – Java Networking
Q6. Write TCP and UDP program for two way communication.
Ans. TCP
-Server-
import java.io.*;
import java.net.*;
class Server1
{
public static void main(String ar[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established");
OutputStream obj=s.getOutputStream();
PrintStream ps=new PrintStream(obj);
ps.close();
ss.close();
s.close();
}
}
-TCPClient-
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String ar[])throws Exception
{
Socket s=new Socket("localhost",777);
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
String str;
while((str=br.readLine())!=null)
{
System.out.println("From Server: "+str);
}
br.close();
s.close();
}
}
5
Unit 1 – Java Networking
UDP
-Server-
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
-UDPClient-
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
6
Unit 1 – Java Networking
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Q7. Write a client-server program using UDP socket. Client send the list of N
strings and server responds the concatenation of those strings.
Ans. Dsender.java
import java.net.*;
import java.util.Scanner;
public class Dsender{
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp;
InetAddress ip=InetAddress.getByName("localhost");
String str;
Scanner sc=new Scanner(System.in);
while(true){
System.out.print("Enter Msg:");
str=sc.nextLine();
dp=new DatagramPacket(str.getBytes(),str.length(),ip,3000);
ds.send(dp);
}
}}
Dreceiver.java
import java.net.*;
public class Dreceiver{
public static void main(String[] args)throws Exception{
String str="",concat="";
DatagramSocket ds=new DatagramSocket(3000);
byte[] buf;
DatagramPacket dp;
while(true){
buf=new byte[1024];
dp=new DatagramPacket(buf, 1024);
ds.receive(dp);
str=new String(dp.getData(),0,dp.getLength());
if( !str.equals("exit"))
{ concat+=str; }
else{break;}
}
System.out.println(concat);
ds.close();}}
7
Unit 1 – Java Networking
Q8. Write a client server program using TCP where client sends a string and
server checks whether that string is palindrome or not and responds with
appropriate message.
Ans. -Server-
import java.net.*;
import java.io.*;
public class Server {
}
if(str.equalsIgnoreCase(newstr))
{
ps.println("string is palindrome ");
}
else
{
ps.println("string is not palindrome ");
}
ps.close();
ss.close();
s.close();
}
}
-Client-
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",777);
BufferedReader kbr=new BufferedReader(new InputStreamReader(System.in));
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
System.out.println("Enter text");
String str = kbr.readLine();
ps.println(str);
8
Unit 1 – Java Networking
String newStr = br.readLine();
System.out.println("Response from server=" + newStr);
br.close();
s.close();
}
}
Q9. Write a client-server program using TCP or UDP where the client sends 10
numbers and server responds with the numbers in sorted order.
Ans. Server-
import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(7777);
Socket s=ss.accept();
System.out.println("connected ......... ");
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int r,i=0;
int n=din.readInt();
int a[]=new int[n];
System.out.println("data:");
int count=0;
System.out.println("Receiving Data ... ");
for(i=0;i<n;i++)
{
a[i]=din.readInt();
}
System.out.println("Data Received");
System.out.println("Sorting Data ....... ");
Arrays.sort(a);
System.out.println("Data Sorted");
System.out.println("Sending Data ....... ");
for(i=0;i<n;i++)
{
dout.writeInt(a[i]);
}
System.out.println("\nData Sent Successfully");
s.close();
ss.close();
}
}
9
Unit 1 – Java Networking
-Client-
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{ Socket s=new Socket("127.0.0.1",7777);
if(s.isConnected())
{ System.out.println("Connected to server");
}
System.out.println("Enter size of array:");
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
int a[]=new int[n];
System.out.println("Enter element to array:");
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeInt(n);
for(int i=0;i<n;i++)
{
int r=scanner.nextInt();;
dout.writeInt(r);
}
System.out.println("Data Sent");
DataInputStream din=new DataInputStream(s.getInputStream());
int r;
System.out.println("Receiving Sorted Data ... ");
for(int i=0;i<n;i++)
{ r=din.readInt();
System.out.print(r+" ");
}
s.close();
}
}
Q10. Write a TCP Client-Server program to get the Date & Time details from
Server on the Client request.
Ans. -Server-
import java.net.*;
import java.io.*;
import java.util.Date;
public class Server {
public static void main(String args[]) throws Exception
{ ServerSocket ss=new ServerSocket(777);
while(true)
{ System.out.println("Waiting For Connection ...");
Socket soc=ss.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date " + (new Date()).toString() + "\n");
out.close();
soc.close();
}}}
10
Unit 1 – Java Networking
-Client-
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",777);
BufferedReader in=
new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());
}
}
11
Unit 2 – JDBC Programming
Q1. What is JDBC? Explain the types of JDBC drivers?
Ans. What is JDBC?
JDBC is an API, which is used in java programming for interacting with database.
JDBC (Java Data Base Connection) is the standard method of accessing databases from Java
application.
JDBC is a specification from Sun Microsystem that provides a standard API for java application to
communicate with different database.
JDBC is a platform independent interface between relational database and java applications.
JDBC Drivers
1. Type1 (JDBC-ODBC Driver)
Depends on support for ODBC
Type1 is not portable driver
Translate JDBC calls into ODBC calls and use Windows ODBC built in drivers
ODBC must be set up on every client
For server side servlets ODBC must be set up on web server
Driver sun.jdbc.odbc.JdbcOdbc provided by JavaSoft with JDK
No support from JDK 1.8 (Java 8) onwards.
E.g. MS Access
12
Unit 2 – JDBC Programming
Because of listed disadvantage, type1 driver is not used in production environment. It can only
be used, when database doesn’t have any other JDBC driver implementation.
13
Unit 2 – JDBC Programming
3. Type 3 (Java Protocol)
This driver translate the jdbc calls into a database server independent and middleware
server specific calls.
With the help of the middleware server, the translated jdbc calls further translated into
database server specific calls.
This type of driver also known as net-protocol fully java technology-enabled driver.
Type-3 driver is recommended to be used with applets. its auto-downloadable.
Can interface to multiple databases – Not vendor specific.
Follows a three-tier communication approach.
The JDBC clients use standard network sockets to communicate with a middleware
application server.
The socket information is then translated by the middleware application server into the
call format required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.
Disadvantages
Compared to Type 2 drivers, Type 3 drivers are slow due to increased number of network calls.
Requires database-specific coding to be done in the middle tier.
The middleware layer added may result in additional latency, but is typically overcome by using
better middleware services.
14
Unit 2 – JDBC Programming
4. Type 4 (Database Protocol)
It is known as the Direct to Database Pure Java Driver
Need to download a new driver for each database engine
Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection.
This kind of driver is extremely flexible, you don't need to install special software on the
client or server.
This type of driver is lightweight and generally known as thin driver.
You can use this driver when you want an auto downloadable option the client side
application
i.e. thin driver for oracle from oracle corporation, weblogic and ms sqlserver4 for ms sql
server from BEA system
Disadvantage
This Driver uses database specific protocol and it is DBMS vendor dependent.
15
Unit 2 – JDBC Programming
Comparison between JDBC Drivers
Type Type 1 Type 2 Type 3 Type 4
Name JDBC-ODBC Bridge Native Code Java Protocol/ Database
Driver/ JNI Middleware Protocol
Vendor Specific No Yes No Yes
Portable No No Yes Yes
Pure Java Driver No No Yes Yes
Working JDBC-> ODBC call JDBC call -> JDBC call -> JDBC call ->DB
ODBC -> native native specific middleware specific call
call call specific.
Middleware ->
native call
Multiple DB Yes NO Yes No
[only ODBC [DB Driver should
supported DB] be in middleware]
Example MS Access Oracle OCI driver IDA Server MySQL
Execution Speed Slowest among all Faster Compared Slower Compared Fastest among
to Type1 to Type2 all
Driver Thick Driver Thick Driver Thin Driver Thin Driver
16
Unit 2 – JDBC Programming
Q2. Explain Thick and Thin driver. Comment on selection of driver. Write code
snippet for each type of JDBC connection.
Ans. Thick driver
Thick client would need the client installation.
E.g. Type 1 and Type 2.
Thin driver
The thin client driver, which mean you can connect to a database without the client installed on your
machine.
E.g. Type 4
Connection conn=
DriverManager.getConnection("jdbc:mysql://localhost:PortNo/database
Name",“uid”, “pwd”);
2. Oracle
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=
DriverManager.getConnection("jdbc:oracle:thin:@hostname:port
Number:databaseName","root", "pwd");
3. DB2
Class.forName("com.ibm.db2.jdbc.net.DB2Driver");
Connection conn=
DriverManager.getConnection("jdbc:db2:hostname:port Number
/databaseName")
17
Unit 2 – JDBC Programming
Q3. Explain Statement Interface with appropriate example.
Ans. Java.sql.Statement
Used for general-purpose access to your database.
Useful for static SQL statements, e.g. SELECT specific row from table etc.
The Statement interface defines a standard abstraction to execute the SQL statements requested by a
user and return the results by using the ResultSet object.
The Statement interface is created after the connection to the specified database is made.
The object is created using the createStatement() method of the Connection interface, as shown in
following code snippet:
Statement stmt = con.createStatement();
1. import java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
4. try {
5. // Load and register the driver
6. Class.forName("com.mysql.jdbc.Driver");
18
Unit 2 – JDBC Programming
Q4. Explain Prepared Statement with example.
Ans. The PreparedStatement interface is subclass of the Statement interface, can be used to
represent a precompiled query, which can be executed multiple times.
Prepared Statement is used when you plan to execute same SQL statements many times.
PreparedStatement interface accepts input parameters at runtime.
A SQL statement is precompiled and stored in a PreparedStatement object.
This object can then be used to efficiently execute this statement multiple times.
The object is created using the prepareStatement() method of Connection interface, as
shown in following snippet:
Advantages:
The performance of the application will be faster, if you use PreparedStatement interface
because query is compiled only once.
This is because creating a PreparedStatement object by explicitly giving the SQL statement
causes the statement to be precompiled within the database immediately.
Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile
the SQL statement.
Late binding and compilation is done by DBMS.
Provides the programmatic approach to set the values.
Disadvantage:
The main disadvantage of PreparedStatement is that it can represent only one SQL statement at a
time.
Example of PreparedStatement
Write a program to insert student records to database using prepared statement
1. import java.sql.*;
2. public class PreparedInsert {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/DIET", "root","pwd");
19
Unit 2 – JDBC Programming
14. int i=ps.executeUpdate();
15. System.out.println("no. of rows updated ="+i);
16. ps.close();
17. conn.close();
18. }catch(Exception e){System.out.println(e.toString());} }//PSVM
}//class
Parameter Description
INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.
20
Unit 2 – JDBC Programming
Example of CallableStatement
Writa a Callable Statement program to retrieve branch of the student using {getBranch()
procedure} from given enrollment number. Also write code for Stored Procedure
Stored Procedure: getbranch()
1. DELIMITER @@
2. DROP PROCEDURE getbranch @@
3. CREATE PROCEDURE databaseName.getbranch
4. (IN enr_no INT, OUT my_branch VARCHAR(10))
5. BEGIN
6. SELECT branch INTO my_branch
7. FROM dietStudent
8. WHERE enr_no=enrno;
9. END @@
10. DELIMITER ;
21
Unit 2 – JDBC Programming
The Statement interface The PreparedStatement The CallableStatement interface
cannot accept parameters. interface accepts input can also accept runtime input
parameters at runtime. parameters.
stmt = PreparedStatement CallableStatement
conn.createStatement(); ps=con.prepareStatement cs=conn.prepareCall("{call
("insert into studentDiet getbranch(?,?)}");
values(?,?,?)");
java.sql.Statement is slower PreparedStatement is faster None
as compared to Prepared because it is used for
Statement in java JDBC. executing precompiled SQL
statement in java JDBC.
java.sql.Statement is suitable java.sql.PreparedStatement java.sql.CallableStatement is
for executing DDL commands is suitable for executing DML suitable for executing stored
- CREATE, drop, alter and commands - SELECT, INSERT, procedure.
truncate in java JDBC. UPDATE and DELETE in java
JDBC.
22
Unit 2 – JDBC Programming
23
Unit 2 – JDBC Programming
Q8. Explain methods of ResultSet Interface.
Ans. Categories
1. Navigational Used to move the cursor around.
methods
2. Get methods Used to view the data in the columns of the current row
being pointed by the cursor.
3. Update methods Used to update the data in the columns of the current row.
The updates can then be updated in the underlying
database as well.
int getInt Returns the integer value to the current row in the specified
(int columnIndex) column index. The column index starts at 1, meaning the
throws SQLException first column of a row is 1, the second column of a row is 2,
and so on.
24
Unit 2 – JDBC Programming
String getString Retrieves the value of the designated column in the current
(String columnLabel) row of this ResultSet object as a String in the Java
throws SQLException programming language.
String getString Retrieves the value of the designated column in the current
(int columnIndex) row of this ResultSet object as a String in the Java
throws SQLException programming language.
25
Unit 2 – JDBC Programming
Q9. Differentiate executeQuery(), executeUpdate() and execute() with
appropriate example.
Concurrency of ResultSet
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. (Default Type)
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
26
Unit 2 – JDBC Programming
Example
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
Example: ResultSetMetaData
1.import java.sql.*;
2.public class MetadataDemo {
3.public static void main(String[] args) {
4. try {Class.forName("com.mysql.jdbc.Driver");
5. Connection conn= DriverManager.getConnection
6. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
7.Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from gtu");
9. ResultSetMetaData rsmd=rs.getMetaData();
10. System.out.println("Total columns:
"+rsmd.getColumnCount());
11. System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
12. System.out.println("Column Type Name of 1st column:“
+rsmd.getColumnTypeName(1));
13. stmt.close();
14. conn.close();
15. }catch(Exception e)
16. {System.out.println(e.toString());}
17. }//PSVM
18. }//class
OUTPUT:
Total columns: 3
Column Name of 1st column:Enr_no
Column Type Name of 1st column:INT
27
Unit 2 – JDBC Programming
Q12. Explain DatabaseMetaData Interface with Example
Ans. DatabaseMetaData interface provides methods to get meta data of a database such as
1. Database product name
2. Database product version
3. Driver name
4. Name of total number of tables etc.
Example: DatabaseMetaData
import java.sql.*;
public class DatabaseMetaDataDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/temp6",
"root","root");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println
("getDatabaseProductName:"+dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():
"+dbmd.getDatabaseProductVersion());
System.out.println("getDriverName():"+dbmd.getDriverName())
;
System.out.println("getDriverVersion():
"+dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());
28
Unit 2 – JDBC Programming
Q13. Explain Transaction Management in JDBC with appropriate example.
Ans. Transaction Management in java is required when we are dealing with relational databases.
By default when we create a database connection, it runs in auto-commit mode.
It means that whenever we execute a query and it’s completed, the commit is fired
automatically.
So every SQL query we fire is a transaction and if we are running some DML or DDL queries,
the changes are getting saved into database after every SQL statement finishes.
Sometimes we want a group of SQL queries to be part of a transaction so that we can commit
them when all the queries runs fine. If we get any exception, we have a choice of rollback
all the queries executed as part of the transaction.
29
Unit 2 – JDBC Programming
Example
1. import java.sql.*;
2. class RollbackDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into diet
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into diet
values(607,'mno','ch')");
12. System.out.println("no. of rows inserted="+i);
13. con.rollback(); //Rollback Transaction
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }}
30
Unit 2 – JDBC Programming
E.g.
Transaction A begins Transaction B begins
UPDATE EMPLOYEE SET SALARY = 10000 SELECT * FROM EMPLOYEE;
WHERE EMP_ID= ‘123’; (Transaction B sees data which is updated by
transaction A. But, those updates have not
yet been committed.)
Example
con.setTransactionIsolation(8);
System.out.println("con.getTransactionIsolation():"
+con.getTransactionIsolation());
31
Unit 2 – JDBC Programming
Q15. Explain Batch Processing in JDBC
Ans. Instead of executing a single query, we can execute a batch (group) of queries.
It makes the performance fast.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for
batch processing.
1. Class.forName("com.mysql.jdbc.Driver");
2. Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/GTU","root","root");
3. con.setAutoCommit(false);
4. Statement stmt=con.createStatement();
5. String query1,query2,query3,query4,query5;
6. query1="create table DietStudent(enr INT PRIMARY
KEY, name VARCHAR(20),sem INT,branch
VARCHAR(10))";
7. query2="insert into DietStudent
values(6001,'java',6,'ce')";
8. query3="insert into DietStudent
values(6002,'php',6,'ce')";
9. query4="update DietStudent set name='cg' where
enr=6002";
10. query5="delete from DietStudent where
name='java'";
11. stmt.addBatch(query1);
12. stmt.addBatch(query2);
13. stmt.addBatch(query3);
14. stmt.addBatch(query4);
15. stmt.addBatch(query5);
16. int[] i=stmt.executeBatch();
17. con.commit();
32
Unit 2 – JDBC Programming
GTU Questions
1. What is JDBC? [Win -14]
List out different types of JDBC driver and explain role of each. [Sum -15]
Write code snippet for each type of JDBC connection. [Win -15]
Explain Thick and Thin driver. [Sum -16]
Comment on selection of driver. [Win -16]
3. Give the use of Statement, PreparedStatement and CallableStatement object. [Win -14]
Write code to insert three records into student table using PreparedStatement
(assume student table with Name, RollNo, and Branch field).
4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16]
33
Unit 3 – Servlet API and Overview
Q1. What is Servlet? List and Explain various stages of Servlet life cycle. Explain
role of web container.
Ans. What is Servlet?
Servlet is java class which extends the functionality of web server by dynamically generating web
pages. Servlet technology is used to create Dynamic web application.
The client enters the URL in the web browser and makes a request. The browser then
generates the HTTP request and sends it to the Web server.
Web server maps this request to the corresponding servlet.
init()
The server basically invokes the init() method of servlet. This method is called only when the
servlet is loaded in the memory for the first time.
The class loader is responsible to load the servlet class.
The servlet class is loaded when the first request for the servlet is received by the web
container.
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
34
Unit 3 – Servlet API and Overview
The web container calls the init method only once after creating the servlet instance. The
init() method is used to initialize the servlet.
public void init(ServletConfig config)throws ServletException
{
//Servlet Initialization…
}
A servlet configuration object used by a servlet container to pass information to a servlet
during initialization.
service()
The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests coming
from the client( browsers) and to write the response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service.
destroy()
Finally server unloads the servlet from the memory using the destroy() method.
The destroy() method is called only once at the end of the life cycle of a servlet.
This method gives your servlet a chance to close
1. database connections,
2. halt background threads,
3. write cookie lists or hit counts to disk, and
4. perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
public void destroy()
{
// Finalization code...
}
35
Unit 3 – Servlet API and Overview
Example
1. import java.io.*;
2. import javax.servlet.*;
3. public class MyServlet1 extends GenericServlet
4. {
5. public void init() throws ServletException
6. {//Initailization Code
7. }
8. public void service(ServletRequest request,
ServletResponse response)
throws ServletException,IOException
9. { //Servlet code
10. }
36
Unit 3 – Servlet API and Overview
Q3. Differentiate GenericServlet and HttpServlet
Ans. GenericServlet HttpServlet
javax.servlet.GenericServlet (abstract class) javax.servlet.http.HttpServlet (abstract class)
It is the immediate subclass of Servlet The immediate super class of HttpServlet is
interface. GenericServlet.
It defines a generic, protocol-independent It defines a HTTP protocol specific servlet.
servlet. it can be used with any protocol, say,
SMTP, FTP, CGI including HTTP etc.
GenericServlet is a super class of HttpServlet HttpServlet is a sub class of GenericServlet
class. class.
All methods are concrete except service() All methods are concrete (non-abstract).
method. service() method is abstract service() is non-abstract method. service()
method. can be replaced by doGet() or doPost()
methods.
37
Unit 3 – Servlet API and Overview
Q5. Write a Servlet program using doPost() to enter two numbers and find
maximum among them.
Ans. max.html
1. <html>
2. <head>
3. <title> Maximum number </title>
4. </head>
5. <body>
6. <form action="/ServletTemp/Max" method="POST" >
7. <p>Enter No-1:<input type="text" name="no1"></p>
8. <p>Enter No-2:<input type="text" name="no2"></p>
9. <p><input type="submit"></p>
10. </form>
11. </body>
12. </html>
Output: max.html
Max.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class Max extends HttpServlet
5. { public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { int n1=0,n2=0;
7. response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. n1=Integer.parseInt(request.getParameter("no1"));
10. n2=Integer.parseInt(request.getParameter("no2"));
11.
12. if(n1>n2)
13. out.println("n1="+n1+"is max number");
14. else if(n2>n1)
38
Unit 3 – Servlet API and Overview
15. out.println("n2="+n2+"is max number");
16. else if(n1==n2)
17. out.println("n1= "+n1+"and n2="+n2+"are equal numbers");
18. }
19. }
Output:Max.java
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
Usage of ServletConfig
If any specific content is modified from time to time. you can manage the Web application easily
without modifying servlet through editing the value in web.xml
E.g. ServletConfig config=getServletConfig();
web.xml
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>cxcy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
39
Unit 3 – Servlet API and Overview
MyServlet.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class MyServlet extends HttpServlet
5. { String msg;
6. PrintWriter out;
7. public void init(ServletConfig config)throws
ServletException
8. { msg = config.getInitParameter("name"); }
9. public void doGet(HttpServletRequest request ,
HttpServletResponse response) throws
i. ServletException,IOException
10. { response.setContentType("text/html");
11. out = response.getWriter();
12. out.println("<h1>"+ msg +"</h1>");
13. }
14. public void destroy()
15. { out.close(); }}
Output: MyServlet.java
40
Unit 3 – Servlet API and Overview
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet.
We provide this information from the web.xml file, so if the information is changed, we
don't need to modify the servlet. Thus it removes maintenance problem.
Usage of ServletContext
There can be a lot of usage of ServletContext object. Some of them are as follows:
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml
file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
Example of ServletContext
Web.xml
<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>ServletContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemo</servlet-name>
<url-pattern>/ServletContextDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>DIET</param-value>
</context-param>
</web-app>
41
Unit 3 – Servlet API and Overview
ServletContextDemo.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class ServletContextDemo extends HttpServlet{
5. public void doGet(HttpServletRequest
req,HttpServletResponse res) throws
ServletException,IOException
6. { res.setContentType("text/html");
7. PrintWriter out=res.getWriter();
8. //creating ServletContext object
9. ServletContext context=getServletContext();
10. //Getting value of initialization parameter and printing it
11. String college=context.getInitParameter("name");
12. out.println("College name is="+college);
13. out.close();
14. }}
Output: ServletContextDemo.java
42
Unit 3 – Servlet API and Overview
Q8. Differentiate ServletConfig and ServletContext Interface.
Ans. Servlet Config Servlet Context
ServletConfig object is one per servlet class ServletContext object is global to entire web
application
Object of ServletConfig will be created during Object of ServletContext will be created at
initialization process of the servlet the time of web application deployment
Scope: As long as a servlet is executing, Scope: As long as web application is
ServletConfig object will be available, it will be executing, ServletContext object will be
destroyed once the servlet execution is available, and it will be destroyed once the
completed. application is removed from the server.
We should give request explicitly, in order to ServletContext object will be available even
create ServletConfig object for the first time before giving the first request
In web.xml – <init-param> tag will be appear In web.xml – <context-param> tag will be
under <servlet-class> tag appear under <web-app> tag
43
Unit 3 – Servlet API and Overview
Output:
host localhost:8080
user-agent Mozilla/5.0 (Windows NT 6.2; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
accept text/html,application/xhtml+xml,
application/xml;q=0.9,*/*;q=0.8
accept-language en-US,en;q=0.5
accept-encoding gzip, deflate
connection keep-alive
upgrade-insecure-requests 1
3. String getHeader(String name) Returns the value of the specified request header as
a String.
E.g. out.println("<p>request.getHeader():"
+request.getHeader("host")+"</p>");
out.println("<p>request.getHeader():"+request.getHeader("referer"
)+"</p>");
Output:
request.getHeader():host=localhost:8080
request.getHeader():referer=http://localhost:8080/ServletTemp/servletmeth.html
4. String getQueryString() Returns the query string that is contained in the request
URL after the path.
5. String getServletPath() Returns the part of this request's URL that calls the
servlet. This path starts with a "/" character and includes
either the servlet name or a path to the servlet
E.g. out.println("<p>request.getServletPath():"
+request.getServletPath()+"</p>");
Output: request.getServletPath(): /ServletMeth
6. String getMethod() Returns the name of the HTTP method with which this
request was made, for example GET or POST
E.g. out.println("<p>request.getMethod():"
+request.getMethod()+"</p>");
Output: request.getMethod(): GET
44
Unit 3 – Servlet API and Overview
Q.10 Write servlet which displayed following information of client.
I. Client Browser
II. Client IP address
III. Client Port No
IV. Server Port No
V. Local Port No
VI. Method used by client for form submission
VII. Query String name and values
Ans. 1. import java.io.*;
2. import javax.servlet.http.*;
3. public class ServletInfo extends HttpServlet{
4. PrintWriter out;
5. public void doGet(HttpServletRequest req,HttpServletResponse
res) throws
IOException
6. {
7. res.setContentType("text/html");
8. out=res.getWriter();
9. // I. Client Browser: we use String getHeader(user-agent)
10. out.println("<p> Client Browser=" +req.getHeader
. ("user-agent")+"</p>");
11. //II. Client IP address
12. out.println("<p> Client IP address= "+req.getRemoteAddr());
13. //III. Client Port No
14. out.println("<p> Client Port No= "+req.getRemotePort());
15. //IV. Server Port No
16. out.println("<p> Server Port No= "+req.getServerPort());
17. //V. Local Port No
18. out.println("<p> Local Port No= "+req.getLocalPort());
19. //VI. Method used by client for form submission
20. out.println("<p> Method used by client= "+req.getMethod());
21. //VII. Query String name and values
22. out.println("<p> Query String name & values=
"+req.getQueryString());
23. }}
Output:
Client Browser=Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0
Client IP address= 0:0:0:0:0:0:0:1
Client Port No= 64779
Server Port No= 8080
Local Port No= 8080
Method used by client= GET
Query String name & values= null
45
Unit 3 – Servlet API and Overview
Q11. What is Request Dispatcher? What is the difference between Request
dispatcher’s forward () and include () method?
Ans. javax.servlet.RequestDispatcher Interface
The RequestDispatcher interface provides the facility of dispatching the request to another
resource.
Resource can be HTML, Servlet or JSP.
This interface can also be used to include the content of another resource.
It is one of the way of servlet collaboration.
The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher.
Syntax
RequestDispatcher getRequestDispatcher(String resource)
Example
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);//method may be include/forward
RequestDispatcher: forward()
46
Unit 3 – Servlet API and Overview
Example: forward()
//for java servlet
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
//for html page
RequestDispatcher rd= request.getRequestDispatcher("/1.html");
rd.forward(request, response);
RequestDispatcher: include()
Example: include()
//for java servlet
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.include(request, response);
//for html page
RequestDispatcher rd=request.getRequestDispatcher("/1.html");
rd.include(request, response);
47
Unit 3 – Servlet API and Overview
Q12. Write a Servlet program to authenticate user with user_id and password, if
user is authenticated then forward to welcome page else include message
with invalid user_id/password.
Ans. 1.html
1. <html>
2. <head>
3. <title>1.html</title>
4. </head>
5. <body>
6. <form action="/Dispatcher/CallServlet" method="POST">
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="text" name="pwd"></p>
9. <p><input type="submit" value="Sign In"></p>
10. </form>
11. </body>
12. </html>
Output:
CallServlet.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class CallServlet extends HttpServlet
5. { public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { response.setContentType("text/html");
7. PrintWriter out=response.getWriter();
8. RequestDispatcher rd;
9. String login=request.getParameter("login");
10. String pwd=request.getParameter("pwd");
11. if(login.equals("java") && pwd.equals("servlet"))
12. { rd=request.getRequestDispatcher("FwdDemo");
13. rd.forward(request, response);
14. }//if
15. else
16. { out.println("<p><h1>Incorrect Login Id/Password
</h1></p>");
17. rd=request.getRequestDispatcher("/1.html");
18. rd.include(request, response); }//else
19. }//dopost }
48
Unit 3 – Servlet API and Overview
FwdDemo.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class FwdDemo extends HttpServlet{
5. public void doPost(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String username=request.getParameter("login");
10. out.println("<h1>"+"Welcome "+username+"</h1>");
11. }
12. }
Output:forward()
Output:include()
Syntax
void sendRedirect(String location) throws IOException
Example
response.sendRedirect("http://www.darshan.ac.in");
response.sendRedirect("/1.html");//relative path
response.sendRedirect("http://localhost:8080/1.html");
//absolute path
49
Unit 3 – Servlet API and Overview
Program: sendRedirect()
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Redirect extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String login=request.getParameter("login");
10. String pwd=request.getParameter("pwd");
11. if(login.equals("java") && pwd.equals("servlet"))
12. { response.sendRedirect("/Dispatcher/Welcome");
13. }
14. else
15. response.sendRedirect("/Dispatcher/redirect.html");
16. } //doGet
17. }
50
Unit 3 – Servlet API and Overview
Q15. What is Session? Why we require Session? List the different ways to manage
the session.
Ans. Define Session
“A session refers to the entire interaction between a client and a server from the time of the client’s
first request, which generally begins the session, to the time of last request/response.”
51
Unit 3 – Servlet API and Overview
• Hidden field will be visible with GET method
• User might view page source and can view hidden field
login.html
1. <html>
2. <head>
3. <title>login</title>
4. </head>
5. <body>
6. <form action="/Session/Valid" method="POST">
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="text" name="pwd"></p>
9. <p><input type="hidden" name="session_id"
value="054"></p>
10. <p><input type="submit" value="Sign In"></p>
11. </form>
12. </body>
13. </html>
Output:
52
Unit 3 – Servlet API and Overview
Valid.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Valid extends HttpServlet
5. { public void doPost(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. {
8. response.setContentType("text/html");
9. PrintWriter out=response.getWriter();
10. RequestDispatcher rd;
11. String login=request.getParameter("login");
12. String pwd=request.getParameter("pwd");
13. String session=request.getParameter("session_id");
14. if(login.equals("java") && pwd.equals("servlet"))
15. {
16. rd=request.getRequestDispatcher("Welcome");
17. rd.forward(request, response);
18. }//if
19. else
20. {
21. out.println("<p><h1>Incorrect LoginId/Password
</h1></p>");
22. rd=request.getRequestDispatcher("/login.html");
23. rd.include(request, response);
24. }//else
25. } }
Welcome.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Welcome extends HttpServlet
5. { public void doPost(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String session=request.getParameter("session_id");
10. String username=request.getParameter("login");
11. out.println("<h1>"+"id:"+session+"</h1>");
12. out.println("<h3>"+"Welcome "+username+"</h3>");
13. }
14. }
53
Unit 3 – Servlet API and Overview
Q17. Explain URL Rewriting with appropriate example.
Ans. In URL rewriting, a token or identifier is appended to the URL of the next Servlet or the next
resource.
We can send parameter name/value pairs using the following format:
URL ? Name1 = value1 & name2 = value2 &…
Here, A name and a value is separated using an equal (=) sign and name/value pair is separated
from another parameter using the ampersand(&).
When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
From a Servlet, we can use getParameter() method to obtain a parameter value.
54
Unit 3 – Servlet API and Overview
Output:
Url2.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Url2 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String session1=request.getParameter("s_id1");
10. String session2=request.getParameter("s_id2");
11. out.println("<h3>"+"id:"+session1+"</h3>");
12. out.println("<h3>"+"id:"+session2+"</h3>");
13. }
14. }
Output:
55
Unit 3 – Servlet API and Overview
Q18. What is Cookie? What does the cookie contains? Explain methods of Cookie
class.
Ans. What is Cookie? What does the cookie contains?
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a
1. Name
2. Single value
3. Optional attributes such as
i. comment
ii. path
iii. domain qualifiers
iv. a maximum age
v. Version number etc.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie/Session cookie: It is valid for single session only. It is removed each time
when user closes the browser.
2. Persistent cookie: It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Cookie class(javax.servlet.http.Cookie )
This class provides the functionality of using cookies.
It provides a lots of useful methods for cookies.
Constructor
Cookie(String name, String value): constructs a cookie with a specified name and value.
Example
Cookie c = new Cookie("session_id","054");
//creating cookie object
Methods of Cookie class
void setMaxAge(int expiry) Sets the maximum age in seconds for this Cookie
int getMaxAge() Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will
persist until browser shutdown.
String getName() Returns the name of the cookie. The name cannot be
changed after creation.
void setValue(String newValue) Assigns a new value to this Cookie.
String getValue() Gets the current value of this Cookie.
56
Unit 3 – Servlet API and Overview
Cookie[] getCookies() Returns an array containing all of the Cookie objects the client
sent with this request. This method returns null if no cookies
were sent.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
57
Unit 3 – Servlet API and Overview
Q19. Write a Servlet program for Session Management using Cookie.
Ans.
cookie.html
1. <html>
2. <head>
3. <title>cookie</title>
4. </head>
5. <body>
6. <form action="/Session/Cookie1" >
<p>Login ID:<input type="text" name="login"></p>
7. <p>Password:<input type="password" name="pwd"></p>
8. <p><input type="submit" value="Sign In"></p>
9. </form>
10. </body>
11. </html>
Output: cookie.html
58
Unit 3 – Servlet API and Overview
Cookie1.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Cookie1 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String login=request.getParameter("login");
10. String pwd=request.getParameter("pwd");
11.
12. if(login.equals("java") && pwd.equals("servlet"))
13. {
14. Cookie c = new Cookie("c1",login);//create cookie
15. response.addCookie(c);//adds cookie with response
16.
17. out.println("Cookie named:"+c.getName()+" added");
18. String path="/Session/Cookie2";
19. out.println("<p><a href="+path+">next page</a></p>");
20. }
21. else
22. {
23. out.println("<p><h1>Incorrect Login Id/Password </h1></p>");
24. rd=request.getRequestDispatcher("/cookie.html");
25. rd.include(request, response);}
26. } }
Output: Cookie1.java
59
Unit 3 – Servlet API and Overview
Cookie2.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4.
5. public class Cookie2 extends HttpServlet
6. { public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException
7. {
8. response.setContentType("text/html");
9. PrintWriter out=response.getWriter();
10. Cookie c[]=request.getCookies();
11. out.println("c.length="+c.length);
12. for(int i=0;i<c.length;i++)
13. { out.println("CookieName="+c[i].getName()+
14. "CookieValue="+c[i].getValue());
15. }
16. //to add another cookie
17. Cookie c1 = new Cookie("c2","054");
18. response.addCookie(c1);
19. String path="/Session/Cookie3";
20. out.println("<a href="+path+">next page</a>");
21. }}
Output: Cookie2.java
Cookie3.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Cookie3 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. Cookie c[]=request.getCookies();
10. for(int i=0;i<c.length;i++)
60
Unit 3 – Servlet API and Overview
11. { out.println("<p>");
12. out.println("CookieName="+c[i].getName()+
13. "CookieValue="+c[i].getValue());
14. out.println("</p>");
15. }
16. }
17. }
Output: Cookie3.java
61
Unit 3 – Servlet API and Overview
62
Unit 3 – Servlet API and Overview
How to create the Session?
HttpSession hs=request.getSession();
hs.setAttribute("s_id", "diet054");
Httpsession.html
1. <html>
2. <head>
3. <title>HttpSession</title>
4. </head>
5. <body>
6. <form action="/Session/HSession1" method="Get">
7. <p>Login ID:<input type="text" name="login"></p>
8. <p><input type="submit" value="Sign In"></p>
9. </form>
10. </body>
11. </html>
Output:Httpsession.html
63
Unit 3 – Servlet API and Overview
HSession1.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class HSession1 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { response.setContentType("text/html");
7. PrintWriter out=response.getWriter();
8. RequestDispatcher rd;
9. String login=request.getParameter("login");
10. if(login.equals("java") )
11. { HttpSession hs=request.getSession();
12. hs.setAttribute("s_id",login);
13. out.println("<p> HSession1:Session Created:
"+hs.getAttribute("s_id")+"</p>");
14. out.print("<a href='HSession2'>Homepage</a>");
15. }
16. else
17. { out.println("<p><h1>Incorrect Login Id/Password
</h1></p>");
18. rd=request.getRequestDispatcher("/httpsession.html");
19. rd.include(request, response);
20. }
21. } }
Output:HSession1.java
64
Unit 3 – Servlet API and Overview
HSession2.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class HSession2 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { response.setContentType("text/html");
7. PrintWriter out=response.getWriter();
8. HttpSession hs=request.getSession(false);
9. String n=(String)hs.getAttribute("s_id");
10. out.print("HSession2:Hello s_id: "+n);
11. out.print("<p><a href='HSession3'>visit</a></p>");
12. } }
Output:HSession2.java
HSession3.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class HSession3 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { response.setContentType("text/html");
7. PrintWriter out=response.getWriter();
8. HttpSession hs=request.getSession(false);
9. String n=(String)hs.getAttribute("s_id");
10. out.print("HSession3 :Hello again: "+n);
11. out.println("<p><form action='/Session/HSession4'></p>");
12. out.println("<p><input type='submit' value='End
Session'></p></form>");
13. hs.invalidate();//Session Invalidated
14. }}
65
Unit 3 – Servlet API and Overview
Output:HSession3.java
HSession4.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class HSession4 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
6. { response.setContentType("text/html");
7. PrintWriter out=response.getWriter();
8. HttpSession hs=request.getSession(false);
9. try{
10. String n=(String)hs.getAttribute("s_id");
11. }
12. catch(NullPointerException ne)
13. {out.println("<p>HSession4:Session Invalidated
</p>"+ne.toString());}
14. out.println("<form action='/Session/httpsession.html'>");
15. out.println("<p><input type='submit'
value='logout'></p></form>");
16. }
17. }
Output:HSession4.java
66
Unit 3 – Servlet API and Overview
Q22. What is filter? What is its use? List different filter interfaces with their
important methods. List the applications of filter.
Ans. What is filter?
A filter is an object that is invoked at the preprocessing and post processing of a request. Java Servlet
Filter is used to intercept request and do some pre-processing and can be used to intercept response
and do post-processing before sending to client in web application.
2. FilterChain
The object of FilterChain is responsible to invoke the next filter or resource in the chain.
This object is passed in the doFilter method of Filter interface.
The FilterChain interface contains only one method:
67
Unit 3 – Servlet API and Overview
3. FilterConfig
FilterConfig is created by the web container.
This object can be used to get the configuration information from the web.xml file.
Method
void init(FilterConfig config) init() method is invoked only once it is used to
initialize the filter.
Advantage of Filter
Filter is pluggable.
One filter don't have dependency onto another resource.
Less Maintenance Cost
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of
filter from the web.xml file, filter will be removed automatically and we don't need to change the
servlet.
So maintenance cost will be less.
68
Unit 3 – Servlet API and Overview
Q23. Write a Servlet Program that uses two filters
i) Authentication Filter: Checks authentication value
(userid/password)
ii) Config Param Filter: Checks value of config param in web.xml
Ans.
Web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>FilteredServlet</servlet-name>
4. <servlet-class>FilteredServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>FilteredServlet</servlet-name>
8. <url-pattern>/FilteredServlet</url-pattern>
9. </servlet-mapping>
10. <filter>
11. <filter-name>f1</filter-name>
12. <filter-class>Filter1</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/FilteredServlet</url-pattern>
17. </filter-mapping>
69
Unit 3 – Servlet API and Overview
18. <filter>
19. <filter-name>f2</filter-name>
20. <filter-class>Filter2</filter-class>
21. <init-param>
22. <param-name>permit</param-name>
23. <param-value>yes</param-value>
24. </init-param>
25. </filter>
26. <filter-mapping>
27. <filter-name>f2</filter-name>
28. <url-pattern>/FilteredServlet</url-pattern>
29. </filter-mapping>
30. </web-app>
index.html
1. <html>
2. <head>
3. <title>filter</title>
4. </head>
5. <body>
6. <form action="/Filter/FilteredServlet" >
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="password" name="pwd"></p>
9. <p><input type="submit" value="Sign In"></p>
10. </form>
11. </body>
12. </html>
Filter1.java
31. import java.io.IOException;
32. import java.io.PrintWriter;
33. import javax.servlet.*;
34. public class Filter1 implements Filter{
35. public void init(FilterConfig config) {}
36. public void doFilter(ServletRequest req,
37. ServletResponse resp,
38. FilterChain chain)
39. throws IOException, ServletException
40. {
41. PrintWriter out=resp.getWriter();
42. out.print("<p>filter1 is invoked before</p>");
43. if(req.getParameter("login").equals("java") &&
req.getParameter("pwd").equals("servlet"))
{
44. chain.doFilter(req, resp);//send request to next resource
}//if
70
Unit 3 – Servlet API and Overview
45. else
46. {out.print("<p>invalid login/password</p>");}//else
47.
48. out.print("<p>filter1 is invoked after</p>");
49. }
50. public void destroy() {}}
Filter2.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class Filter2 implements Filter{
5. String permission;
6. public void init(FilterConfig config) throws ServletException
7. { permission=config.getInitParameter("permit");
}
8. public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain)
throws IOException, ServletException
9. { PrintWriter out=resp.getWriter();
10. out.print("<p>filter2 is invoked before</p>");
11. if(permission.equals("yes"))
12. { chain.doFilter(req, resp);}//if
13. else
14. { out.println("Permission Denied"); }//else
15. out.print("<p>filter2 is invoked after</p>");
}
16. public void destroy() {}}
FilteredServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class FilteredServlet extends HttpServlet
5. {
6. public void doGet(HttpServletRequest request,
HttpServletResponse response)
7. throws ServletException, IOException
8. {
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11. out.println("<p><h3>welcome to servlet</h3></p>");
12. }
13. }
71
Unit 3 – Servlet API and Overview
Output:
72
Unit 3 – Servlet API and Overview
Event classes
ServletRequestEvent Events of this kind indicate lifecycle events for a
ServletRequest. The source of the event is the ServletContext
of this web application.
ServletContextEvent This is the event class for notifications about changes to the
servlet context of a web application.
ServletRequestAttributeEvent This is the event class for notifications of changes to the
attributes of the servlet request in an application.
ServletContextAttributeEvent Event class for notifications about changes to the attributes of
the ServletContext of a web application.
HttpSessionEvent This is the class representing event notifications for changes to
sessions within a web application.
HttpSessionBindingEvent Send to an Object that implements HttpSessionBindingListener
when bound into a session or unbound from a session.
74
Unit 3 – Servlet API and Overview
Q5. How does the JVM execute a servlet compared with a regular Java class?
Ans. Servlets are standard Java classes and are executed by the Java Virtual Machine in exactly the
same way as any other. However, the environment or context in which Servlets are executed
is different. A Servlet is not invoked directly through a main method, the class is loaded and
run by a Servlet Container.
A servlet is not invoked directly using a main() method like any other class.
The servlet class is invoked and executed by a web container (Like Apache Tomcat).
The container reads the configuration (like web.xml), identifies the servlet class, and uses java
class loader system to load and run the servlets.
Q6. How to get the fully qualified name of the client that sent the request in
servlet?
Ans. A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the client's IP Address and
client's host name from a http requisition.
75
Unit 3 – Servlet API and Overview
GTU Questions
1. Write a Login servlet. Take input username and password from html file login.html and Win’17
authenticate the user. Write the web.xml.[7]
2. List and Explain various stages of Servlet life cycle. Explain role of web container.[7] Win’17
Sum’16
3. What is Session? Explain various Session tracking mechanisms in servlet with example.[7] Win’17
Sum’16
Win’16
4. What is filter? What is its use? List different filter interfaces with their important Win’17
methods[7] Win’16
7. Write a servlet RegistrationServlet to get the values from registration.html html page and Win’17
display the contents. Write the web.xml file.[7]
8. Design a form to input details of an employee and submit the data to a servlet. Write code Sum’17
for servlet that will save the entered details as a new record in database table Employee
with fields (EmpId, EName, Email, Age).[7]
76
Unit 4 – Java Server Pages
Q1. List and Explain various stages of JSP life cycle. Briefly give the function of
each phase. cleanliness
Ans. 1. A JSP life cycle can be defined as the entire process from its creation till the destruction.
2. It is similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
3. A JSP page is converted into Servlet in order to service requests.
4. The translation of a JSP page to a Servlet is called Lifecycle of JSP.
77
Unit 4 – Java Server Pages
3. Loading Servlet class
The java servlet class that was compiled from the JSP source is loaded into the container.
78
Unit 4 – Java Server Pages
Q2. Compare JSP with Servlet. Also state advantages of JSP over Servlets.
Ans.
JSP Servlet
JSP is a webpage scripting language that Servlets are Java programs that are already
generates dynamic content. compiled which also creates dynamic web
content.
A JSP technically gets converted to a servlet We A servlet is a java class.
embed the java code into HTML. We can put HTML into print statements.
E.g. <html> <% java code %> </html> E.g. out.println(“<html code>”);
JSPs are extension of servlets which minimizes A servlet is a server-side program and written
the effort of developers to write User purely on Java.
Interfaces using Java programming.
JSP runs slower than servlet. Servlets run faster than JSP
As, it has the transition phase for converting
from JSP to a Servlet. Once it is converted to a
Servlet then it will start the compilation
In MVC architecture JSP acts as view. In MVC architecture Servlet acts as controller.
We can build custom tags using JSP API We cannot build any custom tags in servlet.
79
Unit 4 – Java Server Pages
Scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
A scriptlet can contain
Any number of JAVA language statements
Variable
Method declarations
Expressions that are valid in the page scripting language
Syntax
<% // java source code %>
Example
<% out.print("welcome to jsp"); %>
<% int a=10; %>
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.
Do not end your statement with semicolon in case of expression tag.
Syntax
<%=statement %>
Example
<%=(2*5) %>
80
Unit 4 – Java Server Pages
Declaration
The JSP declaration tag is used to declare variables and methods
The declaration of jsp declaration tag is placed outside the _jspService() method.
Syntax
<%! variable or method declaration %>
Example
<%! int a = 10; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
Comments
The comments can be used for documentation.
This JSP comment tag tells the JSP container to ignore the comment part from compilation.
Syntax
<%-- comments --%>
81
Unit 4 – Java Server Pages
Q4. Explain JSP Page Directives with appropriate example.
Ans. JSP directives provide directions and instructions to the container, telling it how to translate
a JSP page into the corresponding servlet.
A JSP directive affects the overall structure of the servlet class.
JSP engine handles directives at Translation time.
There are two types of directives:
1. page directive
2. include directive
Syntax
<%@ directive attribute="value" %>
page directive
The page directive defines attributes that apply to an entire JSP page.
You may code page directives anywhere in your JSP page.
By convention, page directives are coded at the top of the JSP page.
Syntax
<%@page attribute="value" %>
Example
<%@page import="java.util.Date,java.util.List,java.io.*" %>
<%@page contentType="text/html; charset=US-ASCII" %>
82
Unit 4 – Java Server Pages
isELIgnored We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute.
By default its value is false i.e. EL is enabled by default.
<%@ page isELIgnored="true" %>//Now EL will be ignored
autoFlush The autoFlush attribute specifies whether buffered output should be flushed
automatically when the buffer is filled.Bydefault it is true.
<%@ page autoFlush="true" %>
isThreadSafe This option marks a page as being thread-safe. By default, all JSPs are considered
thread-safe(true). If you set the isThreadSafe = false, the JSP engine makes sure
that only one thread at a time is executing your JSP.
<%@ page isThreadSafe ="false" %>
session The session attribute indicates whether or not the JSP page uses HTTP sessions.
<%@ page session="true" %>//Bydefault it is true
pageEncoding We can set response encoding type with this page directive attribute, its default
value is “ISO-8859-1”.
<%@ page pageEncoding ="US-ASCII" %>
errorPage It is used to define the error page, if exception occurs in the current page, it will
be redirected to the error page.
<%@ page errorPage="myerrorpage.jsp" %>
isErrorPage The isErrorPage attribute is used to declare that the current page is the error
page.
<%@ page isErrorPage="true" %>
83
Unit 4 – Java Server Pages
Q7. Explain JSP implicit objects with appropriate example.
Ans. There are 9 jsp implicit objects.
These objects are created by the web container that are available to all the jsp pages.
Sr.No. Implicit Object Example
1. out For writing any data to the buffer, JSP provides an implicit object
named out.
It is an object of JspWriter
<html>
<body>
<% out.print(“DIET”); %>
</body>
</html>
2. request Instance of javax.servlet.http.HttpServletRequest object associated
with the request.
Each time a client requests a page the JSP engine creates a new
object to represent that request.
The request object provides methods to get HTTP header
information including from data, cookies, HTTP methods etc.
<%
out.println(request.getParameter("login"));%>
<%response.sendRedirect("www.darshan.ac.in");
%>
4. config Config is an implicit object of type javax.servlet.ServletConfig.
This object can be used to get initialization parameter for a
particular JSP page.
String c_name=
config.getInitParameter("College");
out.print("<p>College name
is="+c_name+"</p>");%>
84
Unit 4 – Java Server Pages
5. session In JSP, session is an implicit object of type
javax.servlet.http.HttpSession.
The Java developer can use this object to set, get or remove
attribute or to get session information.
<html> <body>
85
Unit 4 – Java Server Pages
</body> </html>
Q8. Explain JSP Action elements with appropriate example.
Ans. JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
We can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin.
Syntax
<jsp:action_name attribute="value" />
2. <jsp:include>
The jsp:include action tag is used to include the content of another resource it may be jsp,
html or servlet.
The jsp:include tag can be used to include static as well as dynamic pages
Attribute Description
flush The boolean attribute determines whether the included resource has its buffer
flushed before it is included. By default value is false.
Syntax
<jsp:include page="relative URL" flush="true" />
Example
<jsp:include page="2.jsp" />
86
Unit 4 – Java Server Pages
3. <jsp:forward>
Forwards the request and response to another resource.
Syntax
<jsp:forward page="Relative URL" />
Example
<jsp:forward page="2.jsp" />
4. <jsp:plugin>
This tag is used when there is a need of a plugin to run a Bean class or an Applet.
The <jsp:plugin> action tag is used to embed applet in the jsp file.
The <jsp:plugin> action tag downloads plugin at client side to execute an applet or bean.
Syntax
<jsp:plugin type="applet|bean"
code="nameOfClassFile"
codebase= "URL"
/>
Example
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome in Java Applet.",40,20);
}}
MyPlugin.jsp
<html> <body>
<jsp:plugin
type="applet"
code="MyApplet.class"
codebase="/JSPClass/MyApplet"/>
</body></html>
87
Unit 4 – Java Server Pages
Q9. What is EL Scripting? Explain EL implicit object and EL operator with
appropriate example.
Ans. What is EL Scripting?
Expression Language(EL) Scripting.
The Java Expression Language is a special purpose programming language mostly used in Java web
applications for embedding expressions into web pages.
It is the newly added feature in JSP technology version 2.0.
The purpose of EL is to produce script less JSP pages.
Syntax ${expr}
Example
EL Output
${a=10} 10
${10+20} 30
${20*2} 40
${10==20} false
${'a'<'b'} true
EL Implicit Object
pageScope It is used to access the value of any variable which is set in the Page scope
requestScope It is used to access the value of any variable which is set in the Request
scope.
sessionScope It is used to access the value of any variable which is set in the Session scope
applicationScope It is used to access the value of any variable which is set in the Application
scope
pageContext It represents the PageContext object.
88
Unit 4 – Java Server Pages
An expression can be mixed with static text/values and can also be combined with other
expressions
Example1
${param.name}
${sessionScope.user}
Example2
EL1.jsp
1. <form action="EL1.jsp">
2. Enter Name:<input type="text" name="name" >
3. <input type="submit" value="go">
4. </form>
EL2.jsp
1. Welcome, ${ param.name }
Example3:
Cookie_Session1.jsp
1. <form action="EL2.jsp">
2. <% Cookie ck=new Cookie("c1","abc");
3. response.addCookie(ck);
4. session.setAttribute("sid","054"); //for session
5. %>
6. Enter Name:<input type="text" name="name" >
7. Enter Address:<input type="text" name="address" >
8. <input type="submit" value="submit">
9. </form>
Cookie_Session2.jsp
1. <p>Name is : ${param.name}</p>
2. <p>Address is : ${param.address}</p>
3. <p>Cookie Name : ${cookie.c1.name}</p>
4. <p>Cookie value : ${cookie.c1.value}</p>
5. <p>Session id : ${sessionScope.sid}</p>
89
Unit 4 – Java Server Pages
JSP EL Operator
JSP EL Arithmetic Operators
Arithmetic operators are provided for simple calculations in EL expressions.
They are +, -, *, / or div, % or mod.
JSP EL Logical Operators
They are && (and), || (or) and ! (not).
JSP EL Relational Operators
They are == (eq), != (ne), < (lt), > (gt), <= (le) and >= (ge).
90
Unit 4 – Java Server Pages
Example2:web.xml
<error-page>
<exception-type>
java.lang.ArithmeticException
</exception-type>
<location>/error.jsp</location>
</error-page>
Example3:web.xml
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
91
Unit 4 – Java Server Pages
Q11. Write a JSP program to retrieve record from database.
Ans. 1. <%@page import="java.sql.*" %>
2. <%
3. Class.forName("com.mysql.jdbc.Driver");
4. Connection con=DriverManager.getConnection(
5. "jdbc:mysql://localhost:3306/GTU","root","pwd");
6. Statement stmt=con.createStatement();
7. ResultSet rs=stmt.executeQuery("select * from diet");
8. while(rs.next()) {
9. out.println("<p>"+rs.getString(1));
10. out.println(rs.getString(2));
11. out.println(rs.getString(3)+"</p>");
12. }
13. con.close();
14. %>
1 c:out It display the result of an expression, similar to the way <%=...%> tag
work.
E.g. <c:out value="${'Welcome to JSTL'}"/>
2 c:import It is similar to jsp 'include', with an additional feature of including the
content of any resource either within server or outside the server.
E.g.<c:import var="data"
url="http://www.darshan.ac.in"/>
3 c:set It is used to set the result of an expression evaluated in a 'scope'. This
tag is similar to jsp:setProperty action tag.
<c:set var="Income" scope="session"
value="${4000*4}"/>
4 c:remove It is used for removing the specified scoped variable from a particular
scope
<c:set var="income" scope="session"
value="${4000*4}"/>
<c:remove var="income"/>
92
Unit 4 – Java Server Pages
5 c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.
E.g.
<c:if test="${income > 8000}">
<p>My income is: <c:out
value="${income}"/><p>
</c:if>
6 c:catch It is used for catching any Throwable exceptions that occurs in the
body and optionally exposes it.
E.g.
<c:catch var ="MyException">
<% int x = 2/0;%>
</c:catch>
E.g.
<c:choose>
<c:when test="${marks > 75}">
Congratulations! you hold Distinction
</c:when>
<c:otherwise>
Sorry! Result is unavailable.
</c:otherwise>
</c:choose>
8 c:forEach It is an iteration tag used for repeating the nested body content for
fixed number of times. The < c: for each > tag is most commonly
used tag because it iterates over a collection of object.
E.g.<c:forEach var="i" begin="0" end="5">
count <c:out value="${i}"/><p>
</c:forEach>
93
Unit 4 – Java Server Pages
12 c:redirect This tag redirects the browser to a new URL. It is used for redirecting
the browser to an alternate URL by using automatic URL rewriting.
E.g.
<c:redirect url="http://darshan.ac.in"/>
fn:startsWith It is used for checking whether the given string is started with a
particular string value.
fn:toLowerCase It converts all the characters of a string to lower case.
94
Unit 4 – Java Server Pages
fn:trim It removes the blank spaces from both the ends of a string.
Example
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"
prefix="fn" %>
<c:set var="String1" value=" Welcome to diet CE Department "/>
<c:if test="${fn:contains(String1, 'diet')}">
<p>Found diet string<p>
<p>Index of DIET : ${fn:indexOf(String1, "diet")}</p>
<c:set var="str2" value="${fn:trim(String1)}" />
<p>trim : ${str2}</p>
The string starts with "Welcome":
${fn:startsWith(String1, 'Welcome')}
<p>To UPPER CASE: ${fn:toUpperCase(String1)}</p>
<p>To lower case: ${fn:toLowerCase(String1)}</p>
</c:if>
Output:
95
Unit 4 – Java Server Pages
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
<fmt:formatDate type="date" value="${Date}" />
<fmt:formatDate type="time" value="${Date}" />
fmt:parseDate It parses the string representation of a time and date.
E.g.
<fmt:parseDate value="${date}" var="parsedDate"
pattern="dd-MM-yyyy" />
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
E.g.
<fmt:setTimeZone value="IST" />
<c:set var="date" value="<%=new java.util.Date()%>"
/>
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time
formatting.
E.g.
<c:set var="timeZone" value="GMT-8"/>
<fmt:timeZone value="${timeZone}">
fmt:message It display an internationalized message.
E.g. <fmt:message key="String"/>
96
Unit 4 – Java Server Pages
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
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 to set the parameter in an SQL statement to the specified value.
Q16. Write a JSP program using JSTL SQL taglib to display student details in
tabular form by iterating through the database table student.
Ans. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
97
Unit 4 – Java Server Pages
</c:forEach>
</table>
Output:
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.
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.
98
Unit 4 – Java Server Pages
Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<c:set var="myBook">
<books>
<myBook>
<title>TheSecret</title>
<author>RhondaByrne</author>
</myBook>
<myBook>
<title>Meluha</title>
<author>Amish</author>
</myBook>
</books>
</c:set>
<x:parse xml="${myBook}" var="output"/>
<b>Name of the Book is</b>:
<x:out select="$output/books/myBook[1]/title" />
<p><b>Author of the Meluha is</b>:
<x:out select="$output/books/myBook[2]/author" /> </p>
<x:set var="myTitle"
select="$output/books/myBook[2]/title"/>
<p>x:set:<x:out select="$myTitle" /></p>
Output:
99
Unit 4 – Java Server Pages
Q18. Explain steps to create JSP Custom Tag?
Ans. A custom tag is a user-defined JSP language element.
When a JSP page containing a custom tag is translated into a servlet, the tag is converted to
operations on an object called a tag handler.
The Web container then invokes those operations when the JSP page's servlet is executed.
JSP tag extensions let you create new tags that you can insert directly into a Java Server Page
just as you would the built-in tags.
HelloTag.java
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport
{
public void doTag() throws JspException,
IOException
{
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}}
100
Unit 4 – Java Server Pages
Output:
101
Unit 5 – Java Server Faces
Q1. Draw the JSF request processing life cycle and briefly give the function of
each phase.
Ans. JSF application lifecycle consist of six phases which are as follows:
Phase-I: Restore View (RV)
Phase-II: Apply Request Values (ARV)
Phase-III: Process Validations (PV)
Phase-IV: Update Model Values (UMV)
Phase-V: Invoke Application (IA)
Phase-IV: Render Response (RR)
Example
<h:body>
<div id="top" class="top">
<ui:insert name="top">Top Section</ui:insert>
</div>
<ui:define name="top">
Welcome to Template Client Page
</ui:define>
</h:body>
</html>
Q4. List the JSF validation tags and explain any two.
Ans. JSF provides inbuilt validators to validate its UI components. These tags can validate the
length of the field, the type of input which can be a custom object.
For these tags you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
Q6. Write a JSF program to authenticate user with given UID and Password
Ans. LoginBean.java
import javax.faces.bean.ManagedBean;
@ManagedBean
public class LoginBean {
String username;
String password;
public String getUsername() {return username;}
public void setUsername(String username) {
this.username = username;}
public String getPassword() {return password;}
public void setPassword(String password) {
this.password = password;}
public String login() {
if(username.equals("java") && password.equals("jsf"))
return "success";
else{return "failure";} }}
Output:
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form><center>
success.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
Welcome Home: query executed
</h:body>
</html>
fail.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
Login Failed
</h:body>
</html>
<faces-config version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
facesconfig_2_1.xsd">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-action> #{authenticationBean.validateFromDB}</from-
action>
<from-outcome>success</from-outcome>
<to-view-id>/success.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-action> #{authenticationBean.validateFromDB}</from-
action>
<from-outcome>failure</from-outcome>
<to-view-id>/fail.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Output:
JDBC Hibernate
JDBC maps Java classes to database tables Hibernate automatically generates the
(and from Java data types to SQL data types) queries.
With JDBC, developer has to write code to Hibernate is flexible and powerful ORM to
map an object model's data to a relational map Java classes to database tables.
data model.
With JDBC, it is developer’s responsibility to Hibernate reduces lines of code by
handle JDBC result set and convert it to Java. maintaining object-table mapping itself and
So with JDBC, mapping between Java objects returns result to application in form of Java
and database tables is done manually. objects, hence reducing the development
time and maintenance cost.
Require JDBC Driver for different types of Makes an application portable to all SQL
database. databases.
Handles all create-read-update-delete Handles all create-read-update-delete
(CRUD) operations using SQL Queries. (CRUD) operations using simple API; no SQL
Working with both Object-Oriented software Hibernate itself takes care of this mapping
and Relational Database is complicated task using XML files so developer does not need
with JDBC. to write code for this.
JDBC supports only native Structured Query Hibernate provides a powerful query
Language (SQL) language Hibernate Query Language-HQL
(independent from type of database)
For creating the first hibernate application, we must know the objects/elements of Hibernate
architecture.
They are as follows:
i. Configuration
ii. Session factory
iii. Session
iv. Transaction factory
v. Query
vi. Criteria
1. Configuration Object
The Configuration object is the first Hibernate object you create in any Hibernate
application.
It is usually created only once during application initialization.
Q3. What is HQL? How does it different from SQL? List its advantages.
Ans. What is HQL?
The Hibernate ORM framework provides its own query language called Hibernate Query
Language.
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't
depends on the table of the database. Instead of table name, we use class name in HQL.
Therefore, it is database independent query language.
Advantages of HQL:
Provides full support for relation operations
Returns results as objects
Support polymorphic queries
Easy to learn and use
Supports for advanced features
Provides database independency
Collections Mappings
If an entity or class has collection of values for a particular variable, then we can map those
values using any one of the collection interfaces available in java.
Hibernate can persist instances of java.util.Map, java.util.Set, java.util.SortedMap,
java.util.SortedSet, java.util.List, and any array of persistent entities or values.
Association Mappings:
The mapping of associations between entity classes and the relationships between tables is
the soul of ORM.
There are the four ways in which the cardinality of the relationship between the objects can
be expressed.
An association mapping can be unidirectional as well as bidirectional.
Component Mappings:
If the referred class does not have its own life cycle and completely depends on the life cycle of the
owning entity class, then the referred class hence therefore is called as the Component class.
The mapping of Collection of Components is also possible in a similar way just as the mapping of
regular Collections with minor configuration differences.
package hibernatetest;
public class Customer {
private String customerName;
private int customerID;
private String customerAddress;
private String customerEmail;
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;}
public void setCustomerID(int customerID) {
this.customerID = customerID; }
public void setCustomerName(String customerName) {
this.customerName = customerName; }
public String getCustomerAddress() {
return customerAddress; }
public String getCustomerEmail() {
return customerEmail; }
public int getCustomerID() {
return customerID; }
public String getCustomerName() {
return customerName; }}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver </property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/retailer</property>
<property name="hibernate.connection.username">
root</property>
<property name="hibernate.connection.password">
root</property>
<property name="hibernate.connection.pool_size">
10</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">
thread</property>
org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">
update</property>
<mapping resource="hibernate.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<hibernate-mapping>
<class name="hibernatetest.Customer" table="customers">
<id column="C_ID" name="customerID" type="int">
<generator class="native"> </generator></id>
<property name="customerName">
<column name="name"> </column>
</property>
<property name="customerAddress">
<column name="address"> </column>
</property>
<property name="customerEmail">
<column name="email"> </column>
</property>
</class>
</hibernate-mapping>
session.save(customer);
session.getTransaction().commit();
System.out.println("Done!");
session.flush();
session.close();
}catch(Exception e){System.out.println(e.toString());
} } }
jdbc:mysql://localhost:3306/retailer</property>
<property name="hibernate.connection.username">
root</property>
<property name="hibernate.connection.password">
root</property>
<property name="hibernate.connection.pool_size">
10</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">
thread</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">
update</property>
<mapping resource="hibernate.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<hibernate-mapping>
<class name="hibernatetest.Customer" table="customers">
<id column="C_ID" name="customerID" type="int">
<generator class="native"> </generator></id>
<property name="customerName">
<column name="name"> </column>
</property>
<property name="customerAddress">
<column name="address"> </column>
</property>
<property name="customerEmail">
<column name="email"> </column>
</property>
</class>
</hibernate-mapping>
Swati Sharma, CE Department | 2160707 – Advanced Java 123
Unit 6 – Hibernate
Q8. Explain Hibernate Annotation.
Ans. Hibernate Annotations is the powerful way to provide the metadata for the Object and
Relational Table mapping.
Consider we are going to use following EMPLOYEE table to store our objects:
Q2. What is Spring Web MVC framework? List its key features.
Ans. Spring links objects together instead of the objects linking themselves together.
Spring object linking is defined in XML files, allowing easy changes for different application
configurations thus working as a plug in architecture.
In an MVC architecture your controllers handle all requests.
Spring uses a “DispatcherServlet” defined in the web.xml file to analyze a request URL
pattern and then pass control to the correct Controller by using a URL mapping defined in
a “spring bean” XML file. All frameworks integrate well with spring.
Consistent Configuration, open plug-in architecture
Integrates well with different O/R Mapping frameworks like Hibernate
Easier to test applications with.
Less complicated than other frameworks.
Active user community.
Spring is well organized and seems easier to learn comparatively
Spring also supports JDBC Framework that makes it easier to create JDBC Apps.
public TextEditor() {
spellChecker = new SpellChecker();
}
}
Example: Code with Dependency Injection
public class TextEditor {
private SpellChecker spellChecker;
index.jsp
<a href="hello.html">click</a>
HelloWorldController.java
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "HELLO SPRING MVC HOW R U";
return new ModelAndView("hellopage", "message", message);
}
}
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"