Advanced Java - BSc(CS) v Sem-1
Advanced Java - BSc(CS) v Sem-1
Advanced Java - BSc(CS) v Sem-1
Unit-I
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We have discussed the above four drivers in the next chapter.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces
for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the
following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
Class.forName("oracle.jdbc.driver.OracleDriver");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
To connect java application with the oracle database, we need to follow 5 following steps. In this
example, we are using Oracle 10g as the database. So we need to know following information for
the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name. You may get
all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.
create table emp(id number(10),name varchar2(40),age number(3));
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";//Here database exists in the current directory
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}}
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
6
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}}
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Method Description
2) public static void is used to deregister the given driver (drop the
deregisterDriver(Driver driver): driver from the list) with DriverManager.
Connection interface
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like commit(),
rollback() etc..
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int
7
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns
the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
3) public boolean first(): is used to move the cursor to the first row in
result set object.
8
Course Code :CS511T Advanced Java BSc(CS)-V Sem
4) public boolean last(): is used to move the cursor to the last row in
result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row
number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be
positive or negative.
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Method Description
public void setInt(int sets the integer value to the given parameter index.
paramIndex, int value)
public void setString(int sets the String value to the given parameter index.
9
Course Code :CS511T Advanced Java BSc(CS)-V Sem
public void setFloat(int sets the float value to the given parameter index.
paramIndex, float value)
public void setDouble(int sets the double value to the given parameter index.
paramIndex, double value)
public int executeUpdate() executes the query. It is used for create, drop, insert, update,
delete etc.
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be Exception handling using try/catch can't be
used in stored procedures. used in user defined functions.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11
Course Code :CS511T Advanced Java BSc(CS)-V Sem
System.out.println("success");
}
}
Socket Programming -
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
12
Course Code :CS511T Advanced Java BSc(CS)-V Sem
6) Socket
A socket is an endpoint between two way communication.
Visit next page for java socket programming.
java.net package
The java.net package provides many classes to deal with networking applications in Java. A list
of these classes is given below:
13
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.
Important methods
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.
14
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Let's see a simple of Java socket programming where client sends a text and server receives and
prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.
15
Course Code :CS511T Advanced Java BSc(CS)-V Sem
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
16
Course Code :CS511T Advanced Java BSc(CS)-V Sem
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:
17
Course Code :CS511T Advanced Java BSc(CS)-V Sem
URL(String spec)
Creates an instance of a URL from the String representation.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given
context.
The java.net.URL class provides many methods. The important methods of URL class are given
below.
Method Description
public boolean equals(Object it compares the URL with the given object.
obj)
18
Course Code :CS511T Advanced Java BSc(CS)-V Sem
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sour
ceid=chrome&ie=UTF-8");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("Query String: "+url.getQuery());
System.out.println("Path: "+url.getPath());
System.out.println("File: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: https
Host Name: www.google.com
Port Number: -1
19
Course Code :CS511T Advanced Java BSc(CS)-V Sem
The URLConnection class provides many methods, we can display all the data of a webpage by
using the getInputStream() method. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with
the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram
socket and binds it with the specified port number and host address.
Java DatagramSocket Class
Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void connect(InetAddress address, It connects the socket to a remote address for the socket.
int port)
DatagramChannel getChannel() It returns the unique DatagramChannel object associated with the
datagram socket.
InetAddress getLocalAddress() It gets the local address to which the socket is connected.
int getLocalPort() It returns the port number on the local host to which the socket is
bound.
SocketAddress It returns the address of the endpoint the socket is bound to.
getLocalSocketAddress()
int getPort() It returns the port number to which the socket is connected.
int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this DatagramSocket
that is the buffer size used by the platform for input on the
DatagramSocket.
21
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Unit-II
Applet
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is
the subclass of Component.
22
Course Code :CS511T Advanced Java BSc(CS)-V Sem
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
23
Course Code :CS511T Advanced Java BSc(CS)-V Sem
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
24
Course Code :CS511T Advanced Java BSc(CS)-V Sem
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
import java.applet.Applet;
import java.awt.*;
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:
import java.awt.*;
import java.applet.*;
public class AniEx extends Applet
{
Image picture;
public void init()
{
picture=getImage(getDocumentBase(),"abc.jpg");
}
26
Course Code :CS511T Advanced Java BSc(CS)-V Sem
/*
<applet code="AniEx.class" width="300" height="300">
</applet>
*/
O/p –
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method
named getParameter(). Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
27
Course Code :CS511T Advanced Java BSc(CS)-V Sem
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Servlets
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
28
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Terminology
Website: static vs It is a collection of related web pages that may contain text, images, audio
dynamic and video.
HTTP Requests It is the request send by the computer to a web server that contains all sorts of
potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the server side.
Server: Web vs It is used to manage the network resources and for running the program or
Application software that provides services.
Content Type It is HTTP header that provides the description about what are you sending to
the browser.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface defines methods
that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.
30
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.
public void destroy() is invoked only once and indicates that servlet is
being destroyed.
GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
31
Course Code :CS511T Advanced Java BSc(CS)-V Sem
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is
being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to
call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file
and a stack trace.
}
}
HttpServlet class
1. HttpServlet class
2. Methods of HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specifi
methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
32
Course Code :CS511T Advanced Java BSc(CS)-V Sem
33
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Unit-III
JSP
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to Servlet because it provides more functionality than servlet such as
expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet
in JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
ADVERTISEMENT
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
34
Course Code :CS511T Advanced Java BSc(CS)-V Sem
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating the
JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted
into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later
like initialization, committing response to the browser and destroy.
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside
_jspService() method. the _jspService() method.
39
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
For writing any data to the buffer, JSP provides an implicit object named out. It is the object of
JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.
40
Course Code :CS511T Advanced Java BSc(CS)-V Sem
41
Course Code :CS511T Advanced Java BSc(CS)-V Sem
42
Course Code :CS511T Advanced Java BSc(CS)-V Sem
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Output
45
Course Code :CS511T Advanced Java BSc(CS)-V Sem
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Output
47
Course Code :CS511T Advanced Java BSc(CS)-V Sem
48
Course Code :CS511T Advanced Java BSc(CS)-V Sem
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
Output
50
Course Code :CS511T Advanced Java BSc(CS)-V Sem
</body>
</html>
To get the full example, click here full example of exception handling in jsp. But, it will be better
to learn it after the JSP Directives.
JSP directives
1. JSP directives
1. page directive
51
Course Code :CS511T Advanced Java BSc(CS)-V Sem
52
Course Code :CS511T Advanced Java BSc(CS)-V Sem
</html>
extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
Example of info attribute
<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.
Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".
isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e.
Expression Language is enabled by default. We see Expression Language later.
<%@ page isELIgnored="true" %>//Now EL will be ignored
isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false, the web
container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before
passing another request to it.If you make the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
53
Course Code :CS511T Advanced Java BSc(CS)-V Sem
errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
54
Course Code :CS511T Advanced Java BSc(CS)-V Sem
The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so
it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request scope
sessionScope it maps the given attribute name with the value set in the session scope
applicationScope it maps the given attribute name with the value set in the application scope
57
Course Code :CS511T Advanced Java BSc(CS)-V Sem
EL param example
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input
from the user and sends the request to the process.jsp which in turn prints the name of the user
using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
EL sessionScope example
In this example, we printing the data stored in the session scope using EL. For this purpose, we
have used sessionScope object.
index.jsp
<h3>welcome to index page</h3>
<%
session.setAttribute("user","sonoo");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }
EL cookie example
index.jsp
<h1>First JSP</h1>
<%
Cookie ck=new Cookie("name","abhishek");
response.addCookie(ck);
%>
<a href="process.jsp">click</a>
process.jsp
58
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Hello, ${cookie.name.value}
Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence
are as follows:
[] .
()
-(unary) not ! empty
* / div % mod
+ - (binary)
< <= > >= lt le gt ge
== != eq ne
&& and
|| or
?:
Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null
JSTL Tags
There JSTL mainly provides five types of tags:
Tag Description
Name
Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL for
the core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.
Function The functions tags provide support for string manipulation and string length. The URL for the
tags functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.
Formatting The Formatting tags provide support for message formatting, number and date formatting, etc.
tags The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
XML tags The XML tags provide flow control, transformation, etc. The URL for the XML tags
is http://java.sun.com/jsp/jstl/xml and prefix is x.
59
Course Code :CS511T Advanced Java BSc(CS)-V Sem
SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
fn:contains() It is used to test if an input string containing the specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case
insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a particular string
value.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:length() It returns the number of characters inside a string, or the number of items in a
collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.
The fn:contains() is used for testing if the string containing the specified substring. If the
specified substring is found in the string, it returns true otherwise false.
The syntax used for including the fn:contains() function is:
boolean contains(java.lang.String, java.lang.String)
Let's see the simple example to understand the functionality of fn:contains() function:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var="String" value="Welcome to javatpoint"/>
<c:if test="${fn:contains(String, 'javatpoint')}">
<p>Found javatpoint string<p>
</c:if>
<c:if test="${fn:contains(String, 'JAVATPOINT')}">
<p>Found JAVATPOINT string<p>
</c:if>
</body>
</html>
Output:
Found javatpoint string
61
Course Code :CS511T Advanced Java BSc(CS)-V Sem
Formatting Descriptions
Tags
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time
formatting.
fmt:formatNumber It is used to format the numerical value with specific format or precision.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their tag
body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable or the
named scoped variable.
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag body or an attribute.
62
Course Code :CS511T Advanced Java BSc(CS)-V Sem
x: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.
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
sql:query It is used for executing the SQL query defined in its sql attribute or the body.
sql:update It is used for executing the SQL update defined in its sql attribute or in the tag body.
sql:param It is used for sets the parameter in an SQL statement to the specified value.
sql:dateParam It is used for sets the parameter in an SQL statement to a specified java.util.Date value.
sql:transaction It is used to provide the nested database action with a common connection.
63