Advance Java Notes
Advance Java Notes
dev
JDBC
1) JDBC:
JDBC stands for java database connectivity.
JDBC is a specification for developing database applications by using Java programming
language.
Database Application:
An application that communicates with a database is known as database application.
Application:
An application is a program in which we interact with on the desktop.
https://jfs.pages.dev 1/101
4/21/23, 3:34 PM https://jfs.pages.dev
Database:
A database is a software and it is an organized collection of data.
Driver:
A driver is a software and it is used to connect applications and databases.
⇒ Drivers are developed by first party vendors, second part vendors, & third party vendors.
Example:
In the above example, Sun Microsystems is a first party vendor, oracle corporation is a second
party vendor, other than Sun Microsystems and oracle corporation is a third party vendor.
⇒ There are two categories of drivers.
1) ODBC drivers
2) JDBC drivers
https://jfs.pages.dev 2/101
4/21/23, 3:34 PM https://jfs.pages.dev
Java instructions ODBC drivers cannot understand because ODBC drivers existed before Java.
(That compatibility was not there.)
⇒ To solve the above problem JDBC drivers were introduced.
There are four types of JDBC Drivers :
1) Type -1 Driver (JDBC ODBC Bridge Driver)
2) Type -2 Driver (JDBC Native API Driver)
3) Type -3 Driver (JDBC Network Protocol Driver)
4) Type -4 Driver (JDBC 100% Pure Java Driver)
There are two ways to connect Java Application & Database.
1) By using JDBC drivers & ODBC drivers.
2) By using only JDBC drivers.
Note:
All JDBC drivers are classes in Java.
Specification:
It is a set of rules & guidelines that are used to develop applications & environments.
Driver Location:
C:/Program Files/Java/jdk-1.7/lib
JDBC API:
JDBC API is a Java API that can access any kind of tabular data & data especially stored in
RDBMS (Relational database Management system)
⇒ Java library is called Java API because it is an interface between application and
programming language.
JDBC API Contains the following packages:
1) java.sql package
2) javax.sql package
3) javax.sql.rowset package
java.sql package:
To get service I'd , use the following sql query at sql prompt:
https://jfs.pages.dev 5/101
4/21/23, 3:34 PM https://jfs.pages.dev
SQL> select*from global_name;
Steps to load driver & get connection:
/* Program to established a connection between java application
and oracle database by using Type 2 JDBC driver... */
import java.sql.*;
public class DriverConnectionDemo {
⇒There are two ways to set the classpath to access jdbc driver class:
1) Temporary classpath
2) Permanent classpath
Note : if the classpath variable already present then select the classpath
variable & click on Edit button , click on New button type the following ->
https://jfs.pages.dev 6/101
4/21/23, 3:34 PM https://jfs.pages.dev
4) It is platform dependent.
https://jfs.pages.dev 7/101
4/21/23, 3:34 PM https://jfs.pages.dev
⇒ if the database software is installed on the same computer then use localhost
as a domain name otherwise use computer name as a domain name.
Port number :
It is used to identify the service.
⇒Port numbers range from 0 to 65535.
⇒Reserved port numbers range from 0 to 1023.
⇒Free port numbers range from 1024 to 65535.
⇒To view port number open tnsnames.ora file from the following location:
https://jfs.pages.dev 8/101
4/21/23, 3:34 PM https://jfs.pages.dev
⇒To get service-id use the following sql query at the SQL prompt:
⇒ There are 3 statements in JDBC that are used to send SQL & PL/SQL
statements to the database to get the data from the database.
1) Statement interface
2) PreparedStatement interface
3) CallableStatement interface
Note : all JDBC interfaces are implemented in driver software by the driver
vendor.
Statement interface :
It is used to execute static SQL queries.
PreparedStatement interface :
It is used to execute dynamic SQL queries.
CallableStatement interface:
https://jfs.pages.dev 9/101
4/21/23, 3:34 PM https://jfs.pages.dev
execute() method:
⇒it is suitable to execute DDL queries.
⇒ DDL stands for data definition language.
Example : create , alter , drop, etc…
executeUpdate() method;
⇒ it is suitable to execute DML queries.
⇒ DML stands for data manipulation language
Example : insert, update, delete, …etc
executeQuery() method;
⇒ it is suitable to execute DQL queries.
⇒ DQL stands for data query language.
Example: select
https://jfs.pages.dev 10/101
4/21/23, 3:34 PM https://jfs.pages.dev
⇒ Java code executed under Java Runtime Environment (JRE) & SQL code
executed under Database Environment
ResultSet:
A result set is an object that encapsulates a set of rows from a database.
ResultSet is generated based on sql query.
⇒ whenever ResultSet is generated then ResultSet pointer or cursor points
before the first record.
Metadata:
It means data about data.
ResultSetMetaData:
It means data about ResultSet.
DatabaseMetaData:
It means data about databases.
https://jfs.pages.dev 11/101
4/21/23, 3:34 PM https://jfs.pages.dev
ECLIPSE:
Eclipse is an IDE (integrated development environment) for developing
applications by using Java programming language & other's programming
language like c,c++,perl,...etc
⇒IDE contains compiler, interpreter, debugger, editors, plugins,...etc.
⇒ A plugin is a software component that can be used to extend the functionality
of an IDE.
⇒ Eclipse IDE software developed by Eclipse foundation and released in 2001.
⇒ Eclipse IDE software developed in Java Language.
⇒ There are two Eclipse software for Java.
1) Eclipse for Java
2) Eclipse for JavaEE
⇒ Eclipse for Java supports JavaSE applications only.
⇒ Eclipse for javaEE supports both javaSE & JavaEE applications.
⇒ Eclipse's official website is Here Eclipse .
https://jfs.pages.dev 12/101
4/21/23, 3:34 PM https://jfs.pages.dev
⇒ To start Eclipse:
Double click on Eclipse icon from the following folder 9
Select the workspace by click on browse button (Eclipse stores your projects in a
9
folder is called workspace)
⇒Default workspace is
https://jfs.pages.dev 13/101
4/21/23, 3:34 PM https://jfs.pages.dev
PreparedStatement interface:
It is used to execute dynamic SQL queries.
Example:
1) insert into student values (?,?,?);
2) update student set marks=? Where rollno = ?;
3) delete from student where rollno =?;
If we use these types of queries with PreparedStatement interface only one time
compiled and many times executed.
https://jfs.pages.dev 14/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 15/101
4/21/23, 3:34 PM https://jfs.pages.dev
ResultSet Enhancement:
ResultSet Enhancements divided into two categories:
1) ResultSet Types
2) Concurrency Types
https://jfs.pages.dev 16/101
4/21/23, 3:34 PM https://jfs.pages.dev
ResultSet Types:
There are three types of ResultSet.
1) public static final int TYPE_FORWARD_ONLY;
2) public static final int TYPE_SCROLL_INSENSITIVE;
3) public static final int TYPE_SCROLL_SENSITIVE;
The above 3 ResultSet Types are static members (variables) in the ResultSet
interface.
Concurrency Types:
There are two types of concurrency control on ResultSet.
1) public static final int CONCUR_READ_ONLY;
2) public static final int CONCUR_UPDATABLE;
ResultSet Types:
A ResultSet is an object that encapsulates a set of rows from a database.
ResultSet is generated based on sql query.
Whenever ResultSet is generated then ResultSet pointer/cursor points before the
first record.
1) TYPE_FORWARD_ONLY:
It is introduced in JDBC 1.0 version only
It supports only forward direction to iterate records in a ResultSet.
It does not support absolute & relative positions.
It is a default result set type.
2) TYPE_SCROLL_INSENSITIVR:
It is introduced in JDBC 2.0 version.
It supports both forward & backward
directions to iterate records in ResultSet.
It supports both absolute & relative position in a ResultSet.
It will not show changes made by others in a Distributed Database Management
System (DDBMS).
3) TYPE_SCROLL_SENSITIVE:
It is introduced in JDBC 2.0 version.
It supports both forward & backward
directions to iterate records in ResultSet.
It supports both absolute & relative position in a ResultSet.
It will show changes made by others in a Distributed Database Management
System (DDBMS).
In the above example, client 1 update the data in the database then immediately
if it will be shown in client 2 because ResultSet type is SENSITIVE and it will not
be shown in client 3 because ResultSet type is INSENSITIVE.
1) CONCUR_READ_ONLY:
It allows only read operation concurrently.
2) CONCUR_UPDATABLE:
It allows all operations concurrently.
https://jfs.pages.dev 17/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 18/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 19/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 20/101
4/21/23, 3:34 PM https://jfs.pages.dev
Batch Updates:
This features introduced in JDBC 2.0 version to execute more than one SQL
query at a time.
It is also called as Batch Processing.
This feature used to reduce the network traffic.
A. BLOB :
BLOB stands for Binary Large Object.
It can be used to store/retrieve large amount of binary data as a single entity
in/from database.
It supports all types of data (text, image, graphics, animation, audio, video,... etc.)
It is mapped into java.sql.Blob interface in Java language.
B. CLOB:
CLOB stands for Character Large Object.
It can be used to store/retrieve large amount of Character data as a single entity
in/from database.
It supports text only.
It is mapped into java.sql.Clob interface in Java language.
https://jfs.pages.dev 21/101
4/21/23, 3:34 PM https://jfs.pages.dev
RowSets:
A RowSets is an object that encapsulates set of rows from database.
RowSets is generated based on sql query.
Whenever RowSet in generated then RowSet pointer/cursor points to before first
record.
There are five RowSets:
1) JdbcRowSet
2) CachedRowSet
3) WebRowSet
4) FilteredRowSet
5) JoinRowSet
The above all RowSets are interfaces in javax.sql.rowset package.
Differences between ResultSet & RowSets:
ResultSet RowSets
A ResultSet is non serializable object All RowSets are serializable objects.
ResultSet is connected object JdbcRowSet is a connected object
and remaining RowSets are
https://jfs.pages.dev 22/101
4/21/23, 3:34 PM https://jfs.pages.dev
disconnected objects.
ResultSet is not a Java bean All RowSets are Java beans.
In other to get ResultSet we need In other to get RowSet we need
connection interface, DriverManager RowSet implemention class only.
class & Statement interface.
Serialization:
It is a process of converting an object into a series of bits.
In Java, object must be serializable to do the following operations.
1) Writing an object into a file.
2) Reading an object from a file
3) Writing an object to a network.
4) Reading an object from a network.
Class must implements java.io.Serializable interface to make serializable object.
Connected object:
It means the object always been connected to a database.
Java Bean:
A Java bean is a reusable software component.
A Java class is set to be Java bean if it is follows the following rules:
1) Class must be public.
2) Class must implements java.io.Serializable interface.
3) Class must be in a package.
4) Class must contain public default constructor.
5) Instance variables of a class must be private. (Instance variables are
called property)
6) Each & every property must contain setter & getter Methods.
7) All setter & getter Methods must be public.
https://jfs.pages.dev 23/101
4/21/23, 3:34 PM https://jfs.pages.dev
JDBCRowSet:
It is a serializable object.
It is a Connected object.
It is a Java bean.
In other to get JDBCRowSet, we require JDBCRowSet implemention class
(OracleJDBCRowSet) only.
Explainer Program here :
https://jfs.pages.dev 24/101
4/21/23, 3:34 PM https://jfs.pages.dev
CachedRowSet:
It is a serializable object.
It is a disconnected object.
It is a Java bean.
In other to get CachedRowSet, we require CachedRowSet implemention class
(OracleCachedRowSet) only.
Explainer Program here :
WebRowSet:
It is a serializable object.
It is a disconnected object.
It is a Java bean.
It allows to write WebRowSet data to xml file.
Generated XML file can be used in web applications.
(XML stands for eXtensible Markup Language).
In other to get WebRowSet, we require WebRowSet implementation class
(OracleWebRowSet) only.
https://jfs.pages.dev 25/101
4/21/23, 3:34 PM https://jfs.pages.dev
FilteredRowSet :
It is a serializable object.
It is a disconnected object.
It is a Java bean.
It allows filtering operations on RowSet data.
In other to get FilteredRowSet, we require FilteredRowSet implemention class
(OracleFilteredRowSet) only.
JoinRowSet :
It is a serializable object.
It is a disconnected object.
It is a Java bean.
It allows to join two or more RowSets data.
In other to get JoinRowSet, we require JoinRowSet implemention class
(OracleJoinRowSet) only.
https://jfs.pages.dev 26/101
4/21/23, 3:34 PM https://jfs.pages.dev
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class EnterDataToDBByScanner {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.println("Enter Roll Number: ");
int rollno = s.nextInt();
System.out.println("Enter Name: ");
String name = s.next();
System.out.println("Enter Marks: ");
int marks = s.nextInt();
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "sam",
"tiger");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("insert into student
values(?,?,?)");
ps.setInt(1, rollno);
ps.setString(2, name);
ps.setInt(3, marks);
ps.executeUpdate();
System.out.println("Enter Save/Cancel to Commit : ");
String option = s.next();
if (option.equalsIgnoreCase("Save")) {
con.commit();
} else if (option.equalsIgnoreCase("Cancel")) {
con.rollback();
} else {
System.out.println("Invalid options !!! ");
}
System.out.println("One record inserted successfully");
}
}
https://jfs.pages.dev 27/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 28/101
4/21/23, 3:34 PM https://jfs.pages.dev
SERVLETS
SERVLETS:
Servlets is a specification for developing web applications with Java programming language.
Web Application:
A Web application is a Distributed application which runs on browser & server.
Distributed Application :
An application that is installed on one computer & runs on many computers is called as
distributed application.
Browser:
https://jfs.pages.dev 29/101
4/21/23, 3:34 PM https://jfs.pages.dev
A browser is a software that executes web pages containing text, image, graphics, animation,
audio and, video, …etc.
Browser is called as web client.
Server:
A server is a software which recieves request from the client, process the request, constructs
the response & sends the response back to a client.
There are two types of servers:
1) Web servers
2) Application servers
1. Web servers:
A server is a server which contains only web container.
https://jfs.pages.dev 30/101
4/21/23, 3:34 PM https://jfs.pages.dev
CGI Servlets
CGI is a specification for developing web Servlets specification for developing web
applications with c, c++, Perl, …etc. applications with Java programming
language.
CGI based web server creates a new process Servlets based web server creates a new
for every request. process for very first request only.
(Remaining requests are handled by child
process).
Applets vs Servlets :
Applets Servlets
An applet is a Java program that resides in A servlets is a Java program that resides in
server & runs in browser. server & runs in server only.
Applets are used to extend the functionality of Servlets are used to extend the functionality
browser. of server.
Applets do not have main() method because Servlets do not have main() method because
applet runs in browser. Servlet runs in server.
Applet has a life cycle methods to run in Servlets has a life cycle methods to run in
browser. server.
Life cycle methods of an Applets: Life cycle methods of a Servlet:
https://jfs.pages.dev 31/101
4/21/23, 3:34 PM https://jfs.pages.dev
init() method called by browser whenever an init() method called by Web container
applet is opened. whenever first request comes to a Servlet.
start() method called by browser whenever service() method called by Web container for
applet is opened and activated. every request.
paint() method called by browser whenever destroy() method called by Web container
applet is opened and activated. whenever servlets instance is removed from
web container.
stop() method called by browser whenever Servlet instance is removed from web
applet is deactivated and closed. container Whenever web application is
undeployed or server shuts down.
destroy() method called by browser whenever
an applet is closed.
The above life cycle methods are the part of The above life cycle methods are the part of
java.applet.Applet class. javax.servlet.Servlet interface
Every applet must extends java.applet.Applet Every servlets must implements
class to derive life cycle methods. javax.servlet.Servlet interface to derive life
cycle methods.
Every Applet class must be public because it Every Servlet class must be public because it
should be accessible to browser to create an it should be accessible to web container to
object to call life cycle methods. create an object to call life cycle methods.
Classes Interfaces
GenericServlet Servlet
ServletInputStream ServletRequest
ServletOutputStream ServletResponse
ServletException ServletConfig
UnavailableException ServletContext
RequestDispatcher
SingleThreadModel
Classes Interfaces
HttpServlet HttpServletRequest
Cookie HttpServletResponse
HttpSession
jakarta.servlet.Servlet
public abstract void init(ServletConfig) throws ServletException;
public abstract ServletConfig getServletConfig();
public abstract void service(ServletRequest, ServletResponse) throws
ServletException, IOException;
public abstract java.lang.String getServletInfo();
public abstract void destroy();
https://jfs.pages.dev 33/101
4/21/23, 3:34 PM https://jfs.pages.dev
jar:
It is a jdk tool and it is used to create JAR (Java Archive) files, WAR(Web Archive) files ,
EAR(Enterprise Archive) files & RAR (Resource Archive) files.
To start Tomcat Web Server:
1) Open the following folder
C:\Program Files\Apache Software Foundation\Tomcat 10.0\bin
2) Double click on Tomcat10.exe icon
To open Tomcat Homepage:
1) Open the browser
2) Type the following in address bar
http://localhost:8082/
https://jfs.pages.dev 34/101
4/21/23, 3:34 PM https://jfs.pages.dev
http:
HTTP stands for Hyper Text Transfer Protocol.
It transfer hyper text.
Hyper text means HTML text.
HTML stands for Hyper Text Markup Language.
This Protocol used by browser & server to communicate on the web.
localhost:
It is called domain name.
If the server is installed on same computer then use localhost as a domain name.
If the server is installed on other computer then use computer name as a domain name.
8082:
It is a port number and it is used to identify the service.
Tomcat server default port number is 8080.
To change the port number of Tomcat Web Server:
1) Open server.xml file from the following location:
C:/Program Files/Apache Software Foundation/Tomcat 10.0/conf
2) Change the port number 8080 to 8082 in the following link where <Connector port =
"8080" ……/>
web.xml:
It is called as configuration file and it is used to configure servlets, listeners, filters, JSPs,
welcome files, initialization parameters , context parameter, ….etc.
https://jfs.pages.dev 35/101
4/21/23, 3:34 PM https://jfs.pages.dev
In the above application servlet code executed in server, html code transferred to browser &
*html code executed in browser.
To configure Tomcat Web Server in eclipse:
1) Open JavaEE perspective.
2) Click on servers view
3) Right click in a servers view.
4) Click on new.
5) Click on server
6) Expand Apache
7) Select Tomcat v10.0 server
8) Click on next button
9) Select Tomcat installation directory by clicking on browse button.
Example: C:\Program Files\Apache Software Foundation\Tomcat 10.0
10) Click on select folder button.
11) Click on next button
12) Click on finish button.
To check port numbers:
1) Double click on Tomcat v10.0 server at localhost in a Servers view.
2) Tomcat admin port number must be 8005.
3) HTTP/1.1 pretty number be 1024 to 65535 (example :8082)
Note : default port number is 8080
package basics;
import java.io.*;
import java.time.LocalTime;
https://jfs.pages.dev 37/101
4/21/23, 3:34 PM https://jfs.pages.dev
import jakarta.servlet.*;
public class TimeServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
LocalTime lt = LocalTime.now();
int h = lt.getHour();
int m = lt.getMinute();
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=red text=yellow><h1>");
pw.println("Present Time: " + h + ":" + m);
pw.println("</h1></body></html>");
}
}
package basics;
import java.io.*;
import jakarta.servlet.*;
public class CounterServlet extends GenericServlet {
int count;
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
count++;
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=blue><h1>");
pw.println("This page has been accessed "+count+" times");
pw.println("</h1></body></html>");
}
}
MIME types:
MIME stands for multipurpose internet mail extensions.
These types are used by browsers & servers to identify the content.
List of MIME types:
1) "text/html"
2) "text/xml"
3) "text/pdf"
4) "application/ms-word"
5) "application/vnd.ms-excel"
6) "image/jpg"
7) "image/bmp" ….etc.
⇒ Default MIME type is "text/html"
⇒ to change the MIME type use setContentType() method of jakarta.servlet.ServletResponse
interface.
https://jfs.pages.dev 38/101
4/21/23, 3:34 PM https://jfs.pages.dev
Annotations :
Annotations are meta tags that are used to pass some additional information to web container
about servlets, listeners & filters.
All annotations begins with @symbols.
The following annotations are used in servlets:
1) @WebServlet
2) @WebListener
3) @WebFilter
The above all annotations are in jakarta.servlet.annotation package.
In the above example @WebServlet annotation informs the following to web container.
"/test" is a url-pattern of DemoServlet.
In HTML, default Functionality available for submit & reset buttons only.
The value of action structure is executed whenever submit button is clicked.
All fields data erased whenever reset button is clicked.
https://jfs.pages.dev 40/101
4/21/23, 3:34 PM https://jfs.pages.dev
</head>
<body bgcolor=green text=yellow>
<center>
<h1><u>Login Form</u></h1>
<form method=POST action=login>
Username <input type=text name=uname><br>
Password <input type=password name=pword><br><br>
<input type=submit><input type=reset>
</form>
</center>
</body>
</html>
GET vs POST:
GET POST
It includes the request parameter in a request It includes the request parameters in a
header in a packet. request body in a packet.
In this approach request parameter are In this approach request parameter are not
displayed in address bar. displayed.
Here size of the data is limited Here size of the data is not limited.
It is not suitable for uploading files It is suitable for uploading files also.
It is little bit fast as compared to POST It is little bit slow as compared to GET
method. method.
Use this method if the data is not confidential Use this method if the data is confidential
https://jfs.pages.dev 41/101
4/21/23, 3:34 PM https://jfs.pages.dev
It handles POST type requests only.
service() method:
It handles both GET & POST type requests.
Create table in oracle first to add values dynamically from html forms…
create table uinfo (fname varchar2(12),lname varchar2(12),uname
varchar2(12),pword varchar2(12));
RegServlet.java
package login;
import java.io.*;
import java.sql.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
https://jfs.pages.dev 42/101
4/21/23, 3:34 PM https://jfs.pages.dev
e.printStackTrace();
}
}
LoginServlet.java
package login;
import java.io.*;
import java.sql.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
https://jfs.pages.dev 43/101
4/21/23, 3:34 PM https://jfs.pages.dev
try {
String s1 = request.getParameter("uname");
String s2 = request.getParameter("pword");
PreparedStatement pstmt = con.prepareStatement("select *
from uinfo where uname=? and pword=?");
pstmt.setString(1, s1);
pstmt.setString(2, s2);
ResultSet rs = pstmt.executeQuery();
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=cyan text=blue><h1>");
if (rs.next()) {
pw.println("welcome : " + s1);
} else {
pw.println("invalid username or password");
}
pw.println("</h1></body></html>");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Before executing the above application copy ojdbc6_g.jar or ohdbc8_g.jar file into tomcat lib
folder.
User defined servlet object is created by Web container to call lifecycle methods.
ServletRequest is used to get the request parameters from html page.
ServletResponse is used to create byte stream, character stream & it is also used to set the
MIME type.
ServletConfig :
It is used to get the initialisation parameters from web.xml
https://jfs.pages.dev 44/101
4/21/23, 3:34 PM https://jfs.pages.dev
initialisation parameters:
initialisation parameters are specific to servlet.
initialisation parameters are used to initialise the servlet.
To configure initialisation parameters we use <init-param> , <param-name> & <param-value>
tags in web.xml
Example :
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>login.LoginServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>manager</param-value>
</init-param>
</servlet>
</web-app>
To get the above initialisation parameters from web.xml , we use the following method of
ServletConfig interface.
Example :
public void init(ServletConfig config) throws ServletException {
try {
String s1 = config.getInitParameter("driver");
String s2 = config.getInitParameter("url");
String s3 = config.getInitParameter("username");
String s4 = config.getInitParameter("password");
Class.forName(s1);
this.con = DriverManager.getConnection(s2, s3, s4);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
Context Parameters:
Context Parameters are common to all servlets in a war file.
Context Parameters are used to initialise servlet.
To configure context parameters, we use <context-param>,<param-name> & <param-value>
tags in web.xml
</welcome-file-list>
https://jfs.pages.dev 45/101
4/21/23, 3:34 PM https://jfs.pages.dev
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:orcl</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>sam</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet>
The above context parameters can be retrieved from web.xml by using getInitParameter()
method of jakarta.servlet.ServletContext interface.
Example :
public void init(ServletConfig config) throws ServletException {
try {
ServletContext sc = config.getServletContext();
String s1 = sc.getInitParameter("driver");
String s2 = sc.getInitParameter("url");
String s3 = sc.getInitParameter("username");
String s4 = sc.getInitParameter("password");
Class.forName(s1);
con = DriverManager.getConnection(s2, s3, s4);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
ServletConfig ServletContext
https://jfs.pages.dev 46/101
4/21/23, 3:34 PM https://jfs.pages.dev
ServletConfig ServletContext
It is an interface in jakarta.servlet package. It is also an interface in jakarta.servlet
package.
It is created by Web container whenever init() It is created by Web container whenever web
method is called. application is deployed on server.
Web container creates ServletConfig one per Web container creates ServletConfig one per
servlet web application (.war file)
It is used to retrieve initialization parameters It is used to retrieve context parameters from
from web.xml web.xml
Servlet Forwarding :
Forwarding request & response of one servlet to another servlet is called as servlet forwarding.
In this program we are going to use servlet (including & forwarding) methods…
https://jfs.pages.dev 47/101
4/21/23, 3:34 PM https://jfs.pages.dev
pw.println("<font color=yellow> Invalid
Username/Password </font>");
RequestDispatcher rd =
request.getRequestDispatcher("/login.html");
rd.include(request, response);
}
Forwarding Including
Forwarding request & response of one servlet Including request & response of one servlet
to another servlet is called as servlet into another servlet is called as servlet
forwarding. including.
The main advantage of servlet forwarding is The main advantage of servlet including is
modularity. reusability.
In servlet forwarding web container creates In servlet including also web container
only one pair of request & response. creates only one pair of request & response.
Forward statement must be the last statement Include statements can be anywhere in a
in a task code. task code.
Forwarding works within the server only. Including also works within the server only.
Servlet Redirecting :
Passing control from one servlet to another servlet is called as servlet redirecting.
In servlet redirecting , web container instructs the browser to execute next url.
https://jfs.pages.dev 48/101
4/21/23, 3:34 PM https://jfs.pages.dev
Forwarding Redirecting
Forwarding one servlet to another servlet is Passing control from one servlet to another
called as servlet forwarding. servlet is called as servlet redirecting.
In servlet forwarding, server implicitly In servlet redirecting, server instructs the
passes the request & response from one browser to execute next url.
servlet to another servlet.
In servlet forwarding both data & control In servlet redirecting only control passed to
passed to next servlet. next servlet.
In servlet forwarding only one pair of request In servlet redirecting separate pair of request &
& response created by Web container. response created by Web container for every
servlets.
https://jfs.pages.dev 49/101
4/21/23, 3:34 PM https://jfs.pages.dev
2) Url Rewriting
3) Http session
4) Hidden form fields.
Cookies :
A cookie is a piece of information stored at client side to maintain client state information.
jakarta.servlet.http.Cookie
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class SetCookie extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
https://jfs.pages.dev 50/101
4/21/23, 3:34 PM https://jfs.pages.dev
String s1= request.getParameter("book1");
String s2= request.getParameter("book2");
String s3= request.getParameter("book3");
if(s1!=null) {
Cookie c1= new Cookie("book1",s1);
response.addCookie(c1);
}
if(s2!=null) {
Cookie c2= new Cookie("book2",s2);
response.addCookie(c2);
}
if(s3!=null) {
Cookie c3= new Cookie("book3",s3);
response.addCookie(c3);
}
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=blue><center>");
pw.println("<h1>Your Books are Added to Cart</h1>");
pw.println("<a href=get>Next</a>");
pw.println("</center></body></html>");
}
}
Note: In the above example cookies vanish whenever the browser window is closed.
Use the setMaxAge() method to set the time interval.
https://jfs.pages.dev 51/101
4/21/23, 3:34 PM https://jfs.pages.dev
equals() method is String class compares the contents of String objects where as == operator
compares hash codes.
equals() method of Object class compares hash codes.
Url Rewriting:
In this session tracking method , client state information(data) appended to URL.
https://jfs.pages.dev 52/101
4/21/23, 3:34 PM https://jfs.pages.dev
</form>
</body>
</html>
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class SetUrl extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= request.getParameter("book1");
String s2= request.getParameter("book2");
String s3= request.getParameter("book3");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=blue><center>");
pw.println("<h1>Your Books are Added to Cart</h1>");
pw.println("<a href=get?
book1="+s1+"&book2="+s2+"&book3="+s3+">Next</a>");
pw.println("</center></body></html>");
}
}
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class GetUrl extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= request.getParameter("book1");
String s2= request.getParameter("book2");
String s3= request.getParameter("book3");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=green text=yellow><center>");
pw.println("<h1><u>Your Selected Books: </u></h1>");
if(!s1.equals("null"))
pw.println(s1+"<br>");
if(!s2.equals("null"))
pw.println(s2+"<br>");
if(!s3.equals("null"))
pw.println(s3+"<br>");
pw.println("</center></body></html>");
}
}
https://jfs.pages.dev 53/101
4/21/23, 3:34 PM https://jfs.pages.dev
Here it is possible to set the time interval by Here it is not possible to set the time interval.
using setMaxAge() method of Cookie class.
This session tracking method fails if the This session tracking method always works.
cookies are disabled.
Http sessions:
In this session tracking method client state information stored at server side.
In this session tracking method session id created by Web container & passed to client system
to identify the client.
To maintain session id there are two ways.
1) By using cookies.
2) By using url Rewriting.
This session tracking method can be implemented in two ways:
1) Http session with cookies
2) Http session with URL Rewriting
Http session with cookies:
In this session tracking method client state information stored at server side.
Here session id created by Web container, passed to client system & stored in cookie variable at
client side.
jakarta.servlet.http.HttpSession
Methods:
public abstract long getCreationTime();
public abstract String getId();
public abstract long getLastAccessedTime();
public abstract void setMaxInactiveInterval(int);
==> it is used to set the time interval in seconds.
public abstract int getMaxInactiveInterval();
public abstract Object getAttribute(String);
==> it is used to get the session variable value.
public abstract void setAttribute(String, Object);
==> it is used to create session variable with name & value pair.
public abstract void removeAttribute(String);
==> it is used to remove session variable
public abstract void invalidate();
==> it is used to vanish the session id
Note : By default sessions vanish after 30 minutes in a tomcat server.
package session1;
import java.io.*;
import java.util.Date;
https://jfs.pages.dev 54/101
4/21/23, 3:34 PM https://jfs.pages.dev
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class DemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw = response.getWriter();
HttpSession hs = request.getSession();
pw.println("<html><body bgcolor=green text=white><h1>");
pw.println("Session Id : "+hs.getId()+"<br>");
pw.println("Creation Time: "+new Date(hs.getCreationTime())+"
<br>");
pw.println("Last Access time:
"+new Date(hs.getLastAccessedTime())+"<br>");
pw.println("Time Interval: "+hs.getMaxInactiveInterval()+"
Seconds <br>");
pw.println("</h1></body></html>");
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor=cyan text=blue>
<h1><u>Java Books:</u></h1>
<form action=set>
<input type=checkbox name=book1 value=Java2CompleteReference>Java 2
Complete Reference<br>
<input type=checkbox name=book2 value=HeadFirstJava>Head First Java<br>
<input type=checkbox name=book3 value=SCJPByKathySierra>SCJP By Kathy
Sierra<br><br>
<input type=submit><input type=reset>
</form>
</body>
</html>
package session2;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class SetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1 = request.getParameter("book1");
String s2 = request.getParameter("book2");
String s3 = request.getParameter("book3");
HttpSession hs = request.getSession();
hs.setAttribute("book1", s1);
hs.setAttribute("book2", s2);
hs.setAttribute("book3", s3);
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=cyan text=blue><center>");
pw.println("<h1>Your books are added to Cart: </h1>");
pw.println("<a href=get>Next</a>");
pw.println("</center></body></html>");
}
}
https://jfs.pages.dev 55/101
4/21/23, 3:34 PM https://jfs.pages.dev
package session2;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class GetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = request.getSession();
String s1= (String)hs.getAttribute("book1");
String s2= (String)hs.getAttribute("book2");
String s3= (String)hs.getAttribute("book3");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=red text=yellow>");
pw.println("<h1>Selected books: </h1>");
if(s1!=null)
pw.println(s1+"<br>");
if(s2!=null)
pw.println(s2+"<br>");
if(s3!=null)
pw.println(s3+"<br>");
pw.println("</body></html>");
}
}
⇒ In the above example, session id created by web container, passed to client system
and stored in cookie variable at client side.
jakarta.servlet.http.HttpServletResponse
Method:
public abstract String encodeURL(String);
⇒ it is used to append a session id to url.
package session2;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class SetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1 = request.getParameter("book1");
String s2 = request.getParameter("book2");
String s3 = request.getParameter("book3");
HttpSession hs = request.getSession();
hs.setAttribute("book1", s1);
hs.setAttribute("book2", s2);
hs.setAttribute("book3", s3);
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=cyan text=blue><center>");
pw.println("<h1>Your books are added to Cart: </h1>");
String s =response.encodeURL("get");
pw.println("<a href="+s+">Next</a>");
pw.println("</center></body></html>");
}
}
This session tracking method fails This session tracking method always
if the cookies are disabled. works.
Cookies Sessions
A cookies is a piece of A session is a piece of information
information stored at client side stored at server side to maintain
to maintain client state client state information.
information.
In this session tracking method, In this session tracking method ,
session id not created. session id created by web
container.
It supports string type data only. It supports all types of data.
Here size of the data is limited Here size of the data is not
limited.
Cookies are not secure because Sessions are secure because stored
stored at client side. at server side.
By default cookies are vanished By default sessions are vanished
whenever browser window is closed after 30 minutes in a tomcat server
import java.io.*;
import jakarta.servlet.ServletException;
https://jfs.pages.dev 57/101
4/21/23, 3:34 PM https://jfs.pages.dev
import jakarta.servlet.http.*;
public class SetFields extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= request.getParameter("book1");
String s2= request.getParameter("book2");
String s3= request.getParameter("book3");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=blue><center>");
pw.println("<form action=get>");
pw.println("<input type=hidden name=book1 value="+s1+">");
pw.println("<input type=hidden name=book2 value="+s2+">");
pw.println("<input type=hidden name=book3 value="+s3+">");
pw.println("<h1>Your books are added to cart: </h1>");
pw.println("<input type=submit value=next>");
pw.println("</form></center></body></html>");
}
}
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;
public class GetFields extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= request.getParameter("book1");
String s2= request.getParameter("book2");
String s3= request.getParameter("book3");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=red text=white><center>");
pw.println("<h1><u>Your Selected Books: </u></h1>");
if(!s1.equals("null"))
pw.println(s1+"<br>");
if(!s2.equals("null"))
pw.println(s2+"<br>");
if(!s3.equals("null"))
pw.println(s3+"<br>");
pw.println("</center></body></html>");
}
}
jakarta.servlet.http.HttpServletRequest
Methods:
public abstract HttpSession getSession(boolean);
public abstract HttpSession getSession();
https://jfs.pages.dev 58/101
4/21/23, 3:34 PM https://jfs.pages.dev
Here the WAR file name is called context path and <url-pattern> of a
servlet is called servlet path.
The above uri is called the absolute path.
Directory Match:
Extension Match:
https://jfs.pages.dev 59/101
4/21/23, 3:34 PM https://jfs.pages.dev
================
</web-app>|
Servlet Listeners
Servlet Listeners:
⇒Servlet listeners are interfaces that contain event handlers(methods) to handle events
(classes) which are generated by a web container.
1) jakarta.servlet.ServletContextListener
2) jakarta.servlet.ServletContextAttributeListener
3) jakarta.servlet.http.HttpSessionListener
4) jakarta.servlet.http.HttpSessionAttributeListener ,,,,etc.
https://jfs.pages.dev 60/101
4/21/23, 3:34 PM https://jfs.pages.dev
jakarta.servlet.ServletContextListener
Methods:
public default void contextInitialized(ServletContextEvent);
public default void contextDestroyed(ServletContextEvent);
The above event handlers (method) handle ServletContextEvent.
MyListener.java in scl package (servlet context listener) for servlet listener 1st program
package scl;
import java.sql.*;
import jakarta.servlet.*;
public class MyListener implements ServletContextListener {
Connection con;
public void contextInitialized(ServletContextEvent sce) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"sam", "oracle");
ServletContext sc = sce.getServletContext();
sc.setAttribute("oracle", con);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
M S l tj i l k ( l t t t li t )f l t li t 1 t
https://jfs.pages.dev 61/101
4/21/23, 3:34 PM https://jfs.pages.dev
MyServlet.java in scl package (servlet context listener) for servlet listener 1st program
package scl;
import java.io.*;
import java.sql.Connection;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = request.getServletContext();
Connection con =(Connection)sc.getAttribute("oracle");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=cyan text=red><center> <h1>");
pw.println("Connection Object Obtained Successfully");
pw.println("</h1><center></body></html>");
}
}
The following series of actions will be done by Web container whenever a web application is
deployed on server.
1) ServletContext is created.
2) ServletContectEvent is generated.
3) ServletContectEvent is passed to contextInitialized() method.
4) contextInitialized() method body is executed (Connection Established & Connection
object placed in ServletContext memory).
The following series of actions will be done by Web container whenever a web application is
undeployed from server.
1) ServletContext is destroyed.
2) ServletContectEvent is generated.
3) ServletContectEvent is passed to contextDestroyed() method.
4) contextDestroyed() method body executed (Connection Closed).
ServletContextAttributeListener:
ServletContextAttributeEvent:
HttpSessionListener:
https://jfs.pages.dev 62/101
4/21/23, 3:34 PM https://jfs.pages.dev
HttpSessionEvent:
HttpSessionAttributeListener:
jakarta.servlet.ServletContextAttributeListener
Methods:
public default void attributeAdded(HttpSessionBindingEvent);
public default void attributeRemoved(HttpSessionBindingEvent);
public default void attributeReplaced(HttpSessionBindingEvent);
HttpSessionBindingEvent:
package hsl;
import jakarta.servlet.http.*;
public class MyListener implements HttpSessionListener {
int count = 0;
public void sessionCreated(HttpSessionEvent hse) {
count++;
HttpSession hs = hse.getSession();
hs.setAttribute("users", count);
}
public void sessionDestroyed(HttpSessionEvent hse) {
count--;
HttpSession hs = hse.getSession();
hs.setAttribute("users", count);
}
}
package hsl;
import java.io.*;
import java.sql.Connection;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
https://jfs.pages.dev 63/101
4/21/23, 3:34 PM https://jfs.pages.dev
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession hs = request.getSession();
hs.setMaxInactiveInterval(30); //30sec
int count =(Integer)hs.getAttribute("users");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=cyan text=red><center> <h1>");
pw.println("At present "+count+" users are accessing server");
pw.println("</h1><center></body></html>");
}
}
In the above example, a session is created by a web container whenever the getSession()
method of HttpServletRequest is called and the session is destroyed after a time interval.(1
minute).
The following series of actions done by web container whenever session is created:
1) HttpSessionEvent is generated.
2) HttpSessionEvent is passed to sessionCreated() method.
3) sessionCreated() method is called.
4) sessionCreated() method body is executed.
The following series of action done by web container whenever session is destroyed:
1) HttpSessionEvent is generated.
2) HttpSessionEvent is passed to sessionDestroyed() method.
3) sessionDestroyed() method is called.
4) sessionDestroyed() method body is executed.
https://jfs.pages.dev 64/101
4/21/23, 3:34 PM https://jfs.pages.dev
Filters
FILTERS
⇒ A filter is an object that can be declaratively inserted in a container process.
⇒ Filter provides the only mechanism by which we can plugin code between request &
response.
⇒ Servlet supports static dispatching whereas filter supports dynamic dispatching.
1. init()
2. doFilter()
3. destroy()
init() method is called by the web container whenever the first request comes to a filter.
doFilter() method is called by the web container for every request.
destroy() method is called by the web container whenever the filter instance is removed from the
web Page 1 of 2 container.
Filter instance is removed from web application, is undeployed or server shuts down.
The above life cycle methods are the part of jakarta.servlet.Filter interface.
jakarta.servlet.Filter
Methods:
public default void init(FilterConfig) throws ServletException;
public abstract void doFilter(ServletRequest, ServletResponse,
FilterChain) throws IOException ,ServletException;
public default void destroy();
https://jfs.pages.dev 65/101
4/21/23, 3:34 PM https://jfs.pages.dev
jakarta.servlet.http.HttpFilter
Methods:
public void doFilter(ServletRequest, ServletResponse, FilterChain)
throws IOException ,ServletException;
protected void doFilter(HttpServletRequest, HttpServletResponse,
FilterChain) throws IOException ,ServletException;
Every filter must implement jakarta.servlet.Filter interface to derive life cycle methods.
Every filter class must be public because it should be accessible to web containers to create an
object to call life cycle methods.
Use HttpFilter to utilize http specific services & common services.
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body bgcolor=green text=yellow>
<center>
<h1><u>Login Form</u></h1>
<form action=welcome method=POST>
Username <input type=text name=uname><br>
Password <input type=password name=pword><br><br>
<input type=submit><input type=reset>
</form>
</center>
</body>
</html>
package filter;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=red><center>");
pw.println("<h1>welcome...</h1>");
pw.println("</center><body><html>");
}
}
package filter;
import java.io.*;
import java.sql.*;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpFilter;
public class LoginFilter extends HttpFilter implements Filter {
Connection con;
https://jfs.pages.dev 66/101
4/21/23, 3:34 PM https://jfs.pages.dev
public void destroy() {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain) {
try {
String s1 = request.getParameter("uname");
String s2 = request.getParameter("pword");
PreparedStatement pstmt = con.prepareStatement("select *
from uinfo where uname=? and pword=?");
pstmt.setString(1, s1);
pstmt.setString(2, s2);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
chain.doFilter(request, response);
} else {
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=red text=yellow><h1>");
pw.println("invalid username/password");
pw.println("</h1><body><html>");
}
} catch (SQLException | IOException | ServletException e) {
e.printStackTrace();
}
}
public void init(FilterConfig fConfig) throws ServletException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"sam", "oracle");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
https://jfs.pages.dev 67/101
4/21/23, 3:34 PM https://jfs.pages.dev
</filter-mapping>
</web-app>
<html>
<head>
<title>Homepage</title>
</head>
<body bgcolor=green text=yellow>
<h1>Click <a href=count>here</a> to see the number of views</h1>
</body>
</html>
package count;
import java.io.IOException;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class CounterFilter extends HttpFilter implements Filter {
int count=0;
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws IOException,
ServletException {
count++;
https://jfs.pages.dev 68/101
4/21/23, 3:34 PM https://jfs.pages.dev
ServletContext sc = request.getServletContext();
sc.setAttribute("views", count);
chain.doFilter(request, response);
}
}
package count;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class CounterServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
ServletContext sc = request.getServletContext();
int count =(Integer)sc.getAttribute("views");
PrintWriter pw = response.getWriter();
pw.println("<html><body bgcolor=yellow text=red><h1>");
pw.println("The homepage has been accessed " + count + "
times.");
pw.println("</h1></body></html>");
}
}
JSP
JSP
⇒JSP stands for Java Server Page.
⇒ JSP is a specification for developing web applications with the Java programming language.
⇒ Java Server Pages renamed as Jakarta Server Pages.
https://jfs.pages.dev 69/101
4/21/23, 3:34 PM https://jfs.pages.dev
JSP Architecture:
1) Conversion
2) Compilation
3) Execution
JSP Elements:
1. Scripting Elements.
2. Directives
3. Actions
https://jfs.pages.dev 70/101
4/21/23, 3:34 PM https://jfs.pages.dev
Scripting Elements:
There are four Scripting Elements and used to write basic JSP Programs.
1. Scriptlets
2. Declarations
3. Expressions
4. Comments
Scriptlets:
Declarations:
Expressions:
Comments:
demo.jsp file
test.jsp file
<html>
<body bgcolor=yellow text=blue>
<h1>
<% out.println("Welcome to Naresh iTechnologies Ameerpet, Hyderabad");
%>
</h1>
</body>
</html>
<html>
<body bgcolor=green text=white>
<h1>
<jsp:scriptlet>
out.println("Welcome to Naresh I technologies");
</jsp:scriptlet>
</h1>
</body>
</html>
https://jfs.pages.dev 72/101
4/21/23, 3:34 PM https://jfs.pages.dev
JSP to Servlet:
Declarations:
Scriptlets:
Expressions:
https://jfs.pages.dev 73/101
4/21/23, 3:34 PM https://jfs.pages.dev
<html>
<body bgcolor=red text=yellow>
<% java.time.LocalTime lt = java.time.LocalTime.now(); %>
<%= lt %>
</body>
</html>
<html>
<body bgcolor=blue text=yellow>
<h1>
<%! int count=0; %>
This page has been accessed <%= ++count %> times
</h1>
</body>
</html>
<html>
<body bgcolor=yellow text=red>
<table border=20>
<% for (int i=1;i<=100; i++){ %>
<tr>
<td>5</td>
<td>x</td>
<td><%= i %></td>
<td>=</td>
<td><%= 5*i %></td>
</tr>
<% } %>
</table>
</body>
</html>
l i ht l fil f l i f i ht l it i j j t
https://jfs.pages.dev 74/101
4/21/23, 3:34 PM https://jfs.pages.dev
login.html file for login form in html its in jsp project
<html>
<body bgcolor=yellow text=red>
<center>
<h1><u>Login Form</u></h1>
<form action="login.jsp">
Username <input type=text name=uname><br>
Password <input type=password name=pword><br><br>
<input type=submit><input type=reset>
</form>
</center>
</body>
</html>
<html>
<body bgcolor=red text=yellow>
<%
String s1=request.getParameter("uname");
String s2=request.getParameter("pword");
if(s1.equals("abc")&& s2.equals("xyz")){
out.println("Welcome");
}else{
out.println("Invalid username/password");
}
%>
</body>
</html>
Directives:
1. Include Directive
2. Page Directive
3. Taglib Directive
Include Directive:
Attributes:
1) file= ”......” //html file or jsp file only.
<html>
<body bgcolor=green text=yellow>
<h1><u><% out.println("include directive example"); %></u></h1>
<%@ include file="count.jsp" %>
https://jfs.pages.dev 75/101
4/21/23, 3:34 PM https://jfs.pages.dev
<%@ include file="time.jsp" %>
<%@ include file="table.jsp" %>
</body>
</html>
Page Directive:
1. language
2. import
3. buffer
https://jfs.pages.dev 76/101
4/21/23, 3:34 PM https://jfs.pages.dev
4. autoFlush
@The above buffer & autoFlush attributes are used to manage buffer memory efficiently.
5. errorPage
6. isErrorPage
In the above example error.jsp program executed whenever exception occurs in a demo.jsp.
<!DOCTYPE html>
<html>
<body bgcolor=green text=yellow>
<h1><u>Arithmetic Application</u></h1>
<form action=arithmetic.jsp>
Enter First Number <input type=text name=first><br>
Enter Second Number <input type=text name=second><br><br>
<input type=submit><input type=reset>
</form>
</body>
</html>
<html>
<body bgcolor=yellow text=blue>
<%@ page errorPage="error.jsp"%>
<%
String s1 = request.getParameter("first");
String s2 = request.getParameter("second");
int x= Integer.parseInt(s1);
int y= Integer.parseInt(s2);
int z=x/y;
out.println("output : "+ z);
%>
</body>
</html>
<html>
<body bgcolor=red text=yellow>
<%@ page isErrorPage="true" %>
<% out.print("please pass second number except 0"); %>
</body>
</html>
7. contentType
8. isELIgnored
This statement indicates a web container to ignore JSP Expression Language in a JSP.
9. session
This statement indicates web containers that do not create sessions for this application.
It does not allow access to implicit session objects in this application.
<html>
<body bgcolor=green text=white>
<h1>
<%@ page import= "java. util. *" %>
<%= "Session ID: "+session. getId() %><br>
https://jfs.pages.dev 78/101
4/21/23, 3:34 PM https://jfs.pages.dev
<%= "Session Creation Time: "+new Date(session.getCreationTime()) %>
<br>
<%= "Session Last Accessed Time: "+new Date(session.
getLastAccessedTime ()) %><br>
<%= "Default Time Interval: " +session.getMaxInactiveInterval()+"
Seconds" %>
</h1>
</body>
</html>
JSP Elements
10. isThreadSafe
TagLib Directive :
The above taglib directive required to include tag library while using JSTL
JSTL stands for JSP Standard Tag Library.
1. <jsp:forward>
It is used to forward the request & response of one JSP to another JSP.
It is equivalent to servlet forwarding.
<!DOCTYPE html>
<html>
<body bgcolor=green text=yellow><center>
<h1><u>Arithmetic Application</u></h1>
<form action=arithmetic.jsp>
First Number <input type=text name=first><br>
Second Number <input type=text name=second><br><br>
<input type=submit name=operation value=addition>
<input type=submit name=operation value=subtraction>
<input type=submit name=operation value=multiplication>
<input type=submit name=operation value=division>
</form>
</center>
</body>
</html>
<html>
<body bgcolor=yellow text=blue>
<%
String s1 = request.getParameter("operation");
if (s1.equals("addition")) {
%><jsp:forward page="add.jsp"/><%
} else if (s1.equals("subtraction")) {
%><jsp:forward page="sub.jsp"/><%
} else if (s1.equals("multiplication")) {
%><jsp:forward page="mul.jsp"/><%
} else
https://jfs.pages.dev 80/101
4/21/23, 3:34 PM https://jfs.pages.dev
%><jsp:forward page="div.jsp"/><%
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Addition Result</h1>
<%
String s1 = request.getParameter("first");
String s2 = request.getParameter("second");
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
out.println("Output: "+(x+y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Subtraction Result</h1>
<%
String s1 = request.getParameter("first");
String s2 = request.getParameter("second");
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
out.println("Output: "+(x-y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Multiplication Result</h1>
<%
String s1 = request.getParameter("first");
String s2 = request.getParameter("second");
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
out.println("Output: "+(x*y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Division Result</h1>
<%
String s1 = request.getParameter("first");
String s2 = request.getParameter("second");
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
out.println("Output: "+(x/y));
%>
</body>
</html>
https://jfs.pages.dev 81/101
4/21/23, 3:34 PM https://jfs.pages.dev
2. <jsp:include>
It is used to include the request & response of one jsp into another jsp
header.jsp file for including jsp to another jsp it’s in jsp project.
<html>
<body>
https://jfs.pages.dev 82/101
4/21/23, 3:34 PM https://jfs.pages.dev
<center><h1><u><font color=red>
<% out.println("JSP Tutorial"); %>
</font></u></h1></center>
</body>
</html>
footer.jsp file for including jsp to another jsp it’s in jsp project.
<html>
<body>
<center><h2><font color=blue>
<% out.println("Naresh I technologies, Ameerpet, Hyderabad"); %>
</font></h2></center>
</body>
</html>
page1.jsp file for including jsp to another jsp it’s in jsp project.
<html>
<body bgcolor=yellow text=green>
<jsp:include page="header.jsp"/>
<h1><u>JSP:</u></h1>
<% out.println("JSP stands for Java Server Pages. JSP is a specification
for developing web applications with Java programming language."); %>
<jsp:include page="footer.jsp"/>
</body>
</html>
page2.jsp file for including jsp to another jsp it’s in jsp project.
<html>
<body bgcolor=yellow text=green>
<jsp:include page="header.jsp"/>
<h1><u>JSTL:</u></h1>
<% out.println("JSTL stands for Java server pages Standard Tag Library.
It is introduced in JSP 2.0 version to simplify the JSP."); %>
<jsp:include page="footer.jsp"/>
</body>
</html>
OUTPUT ::
It supports to include html in a jsp & jsp in a It supports to include servlet in a jsp, jsp in a
jsp. jsp & html in a jsp.
It is not equal to servlet including. It is equal to servlet including.
1) jspInit() method
2) _jspService() Method
3) jspDestroy() method
jspInit() method:
_jspService() Method:
https://jfs.pages.dev 84/101
4/21/23, 3:34 PM https://jfs.pages.dev
jspDestroy() method:
It is called by the web container whenever a converted servlet instance is removed from the web
container.
Converted servlet instances are removed whenever a web application is undeployed or server
shuts down.
This method belongs to jakarta.servlet.jsp.JspPage interface.
This method can be overridden by a programmer because this method is not overridden by web
container.
<!-- JSP Program to demonstrate converted servlet life cycle method -->
<html>
<body bgcolor=green text=yellow>
<%@ page import="java.sql.*"%>
<%!Connection con;
Package demo;
Import java.io*;
public class MessageBean implements Serializable{
private String message;
void setMessage(String message){
this.message=message;
}
public String getMessage(){
return message;
}
}
The following actions are used to access a Java Bean in a JSP
1) <jsp:useBean>
2) <jsp:setProperty>
3) <jsp:getProperty>
<jsp:useBean> :
https://jfs.pages.dev 86/101
4/21/23, 3:34 PM https://jfs.pages.dev
<jsp:setProperty> :
<jsp:getProperty> :
package jsp;
import java.io.Serializable;
public class MessageBean implements Serializable {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
https://jfs.pages.dev 87/101
4/21/23, 3:34 PM https://jfs.pages.dev
<jsp:plugin> :
<jso:fallback> :
<jsp:params> :
<jsp:param> :
JSP EL:
● JSP EL stands for Java Server Pages Expression Language.
● JSP EL was introduced with JSTL in the JSP 2.0 version to simplify the JSP.
● JSTL stands for JSP Standard Tag Library.
● Both JSP EL & JSTL are used to simplify the JSP.
● JSP EL can be used independently and it can also be used with JSTL.
● By using JSP EL & JSTL in a JSP, JSP becomes a 100% tag based application.
https://jfs.pages.dev 88/101
4/21/23, 3:34 PM https://jfs.pages.dev
● Expression can be replaced with JSP EL to make JSP as 100% tag based application.
● Scriptlets & Declarations can be replaced with JSTL to make JSP as a 100% tag based
application.
● The pattern that identifies JSP Expression Language is ${...}
● By default JSP EL is enabled.
● To disable JSP EL in a JSP, use the following.
< % @ page isELIgnored=”true” % >
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ or div Division
% or mod Modulo Division
< or lt Less than
> or gt Greater than
<= or le Less than or equal to
>= or ge Greater than or equal to
== or eq Equals to
!= or ne Not equals to
&& or and Logical AND
|| or or Logical OR
! or not Logical NOT
1. pageScope
2. requestScope
3. sessionScope
4. applicationScope
5. param
6. initParam
7. Cookie
https://jfs.pages.dev 89/101
4/21/23, 3:34 PM https://jfs.pages.dev
pageScope:
requestScope:
sessionScope:
applicationScope:
jakarta.servlet.jsp.PageContext:
Fields(Variables):
1) public static final int PAGE_SCOPE;
2) public static final int REQUEST_SCOPE;
3) public static final int SESSION_SCOPE;
4) public static final int APPLICATION_SCOPE;
<html>
<body bgcolor=red text=yellow>
<h1>
<%
pageContext.setAttribute("platform1", "JavaSE",
PageContext.PAGE_SCOPE);
pageContext.setAttribute("platform2", "JavaEE",
PageContext.REQUEST_SCOPE);
pageContext.setAttribute("platform3", "JavaME",
PageContext.SESSION_SCOPE);
pageContext.setAttribute("platform4", "JavaFX",
PageContext.APPLICATION_SCOPE);
%>
${ pageScope.platform1 }<br> ${ requestScope.platform2 }<br>
${ sessionScope.platform3 }<br> ${ applicationScope.platform4 }
</h1>
</body>
</html>
https://jfs.pages.dev 90/101
4/21/23, 3:34 PM https://jfs.pages.dev
In the above example, platform1 can be accessed in page1.jsp only because its scope is page
scope , platform2 can be accessed in page1.jsp & page2.jsp because its scope is request
scope, platform3 can be accessed in page1.jsp, page2.jsp, & page3.jsp because its scope is
session scope and platform can be accessed in all pages in a .war file.
param:
initParam:
cookie:
https://jfs.pages.dev 91/101
4/21/23, 3:34 PM https://jfs.pages.dev
JSTL:
Core Tags:
1. <c:out>
2. <c:set>
3. <c:remove>
4. <c:if>
5. <c:choose>
6. <c:when>
7. <c:otherwise>
8. <c:forEach>
9. <c:forTokens>
10. <c:redirect>
In order to use the above tag, we must include the following taglib directive in a JSP.
<c:out>:
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set>
<c:remove>
<html>
https://jfs.pages.dev 92/101
4/21/23, 3:34 PM https://jfs.pages.dev
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="a" value="10" />
<c:out value="${a}" />
<c:if>
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="a" value="10" />
<c:if test="${ a>0 }">
<c:out value="Positive Number" />
</c:if>
</h1>
</body>
</html>
<c:choose>
<c:when>
<c:otherwise>
● The above 3 tags are equivalent to if else if… else statement & switch statement.
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="a" value="10" />
<c:choose>
<c:when test="${a>0}">
<c:out value="Positive Number" />
</c:when>
<c:when test="${a<0}">
<c:out value="Negative Number" />
</c:when>
<c:otherwise>
<c:out value="Zero" />
https://jfs.pages.dev 93/101
4/21/23, 3:34 PM https://jfs.pages.dev
</c:otherwise>
</c:choose>
</h1>
</body>
</html>
<c:forEach> :
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forTokens> :
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forTokens var="s" items="Welcome to JSTL" delims=" ">
https://jfs.pages.dev 94/101
4/21/23, 3:34 PM https://jfs.pages.dev
<c:redirect>
SQL Tags:
1. <sql:setDataSource>
2. <sql:update>
3. <sql:query>
In order to use the above tags we must include the following taglib directive in a JSP.
<sql:setDataSource> :
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:setDataSource var="con" driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl" user="sam"
password="oracle" />
<c:out value="Connection Established Successfully" />
</h1>
</body>
</html>
<sql:update>
<html>
<body bgcolor=yellow text=blue>
<h1>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
https://jfs.pages.dev 95/101
4/21/23, 3:34 PM https://jfs.pages.dev
</h1>
</body>
</html>
<sql:query>
<html>
<body bgcolor=yellow text=blue>
<table border=10>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
</tr>
</c:forEach>
</table>
</body>
</html>
MVC
MVC stands for model view controller.
MVC architecture used to separate presentation logic, business logic, data access logic & data.
It is a convenient way to manage & update web application by using MVC architecture.
Here Model is a Java Bean, View is a JSP & Controller is a Servlet.
https://jfs.pages.dev 96/101
4/21/23, 3:34 PM https://jfs.pages.dev
MVC Architecture:
<html>
<body bgcolor=green text=yellow>
<form action=result>
<h1>
Enter Hall Ticket Number<br><input type=text name=hno><br><br>
<input type=submit><input type=reset>
</h1>
</form>
</body>
</html>
package mvc;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/result")
public class ResultServlet extends HttpServlet {
https://jfs.pages.dev 97/101
4/21/23, 3:34 PM https://jfs.pages.dev
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String s = request.getParameter("hno");
int h = Integer.parseInt(s);
ResultDAO rdao = new ResultDAO();
ResultBean rb = rdao.getResult(h);
request.setAttribute("result", rb);
RequestDispatcher rd =
request.getRequestDispatcher("/result.jsp");
rd.forward(request, response);
}
}
package mvc;
import java.sql.*;
public class ResultDAO {
ResultBean getResult(int hno) {
ResultBean rb=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sam","oracle");
PreparedStatement pstmt = con.prepareStatement("select * from results
where hno=?");
pstmt.setInt(1, hno);
ResultSet rs= pstmt.executeQuery();
rb= new ResultBean();
if(rs.next()) {
rb.setHno(rs.getInt("hno"));
rb.setName(rs.getString("name"));
rb.setC(rs.getInt("c"));
rb.setCpp(rs.getInt("cpp"));
rb.setJava(rs.getInt("java"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return rb;
}
}
package mvc;
<html>
<body bgcolor=green text=yellow><h1>
<% mvc.ResultBean rb=(mvc.ResultBean)request.getAttribute("result"); %>
Hall Ticket Number <%= rb.getHno() %><br>
Name : <%= rb.getName() %><br>
C : <%= rb.getC() %><br>
C++ : <%= rb.getCpp() %><br>
Java : <%= rb.getJava() %>
</h1></body>
</html>
Oracle table to show info for mvc project (table name is results)
In the above examples, result.html & result.jsp contains presentation logic, ResultServlet.java
contains controlling logic, ResultDAO.java contains data access logic & ResultBean.java
contains data whatever is retrieved from the database.
Advantages of MVC:
1) Easy to maintain
2) Easy to update
https://jfs.pages.dev 99/101
4/21/23, 3:34 PM https://jfs.pages.dev
3) Rapid application development
4) Parallel development
Reflection API
●It is used to analyze the structure of a class or interface.
●It is also used to get the variables (fields), methods & constructors of specified classes.
●It is also used to analyze methods, constructors & variables (fields).
●Reflection API used to develop Integrated Development Environments , debuggers &
javap tools.
Java.lang.reflect package:
Classes:
1) Field
2) Method
3) Constructor
java.lang.Class
Methods:
public static Class forName(String) throws ClassNotFoundException;
public Field[] getFields() throws SecurityException;
public Method[] getMethods() throws SecurityException;
public Constructor[] getConstructors() throws SecurityException
⇒ The above 3 methods are used to get the members of the current class & members of super
classes.
⇒ The above 3 methods are used to get the members of current class only.
https://jfs.pages.dev 100/101
4/21/23, 3:34 PM https://jfs.pages.dev
https://jfs.pages.dev 101/101