Advanced Java JDBC Programming 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.
[Link] 1/101
4/21/23, 3:34 PM [Link]
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
[Link] 2/101
4/21/23, 3:34 PM [Link]
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) [Link] package
2) [Link] package
3) [Link] package
[Link] package:
To get service I'd , use the following sql query at sql prompt:
[Link] 5/101
4/21/23, 3:34 PM [Link]
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 [Link].*;
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 ->
[Link] 6/101
4/21/23, 3:34 PM [Link]
4) It is platform dependent.
[Link] 7/101
4/21/23, 3:34 PM [Link]
⇒ 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 [Link] file from the following location:
[Link] 8/101
4/21/23, 3:34 PM [Link]
⇒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:
[Link] 9/101
4/21/23, 3:34 PM [Link]
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
[Link] 10/101
4/21/23, 3:34 PM [Link]
⇒ 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.
[Link] 11/101
4/21/23, 3:34 PM [Link]
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 .
[Link] 12/101
4/21/23, 3:34 PM [Link]
⇒ 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
[Link] 13/101
4/21/23, 3:34 PM [Link]
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.
[Link] 14/101
4/21/23, 3:34 PM [Link]
[Link] 15/101
4/21/23, 3:34 PM [Link]
ResultSet Enhancement:
ResultSet Enhancements divided into two categories:
1) ResultSet Types
2) Concurrency Types
[Link] 16/101
4/21/23, 3:34 PM [Link]
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.
[Link] 17/101
4/21/23, 3:34 PM [Link]
[Link] 18/101
4/21/23, 3:34 PM [Link]
[Link] 19/101
4/21/23, 3:34 PM [Link]
[Link] 20/101
4/21/23, 3:34 PM [Link]
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 [Link] 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 [Link] interface in Java language.
[Link] 21/101
4/21/23, 3:34 PM [Link]
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 [Link] 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
[Link] 22/101
4/21/23, 3:34 PM [Link]
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 [Link] 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 [Link] 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.
[Link] 23/101
4/21/23, 3:34 PM [Link]
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 :
[Link] 24/101
4/21/23, 3:34 PM [Link]
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.
[Link] 25/101
4/21/23, 3:34 PM [Link]
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.
[Link] 26/101
4/21/23, 3:34 PM [Link]
import [Link];
import [Link];
import [Link];
import [Link];
public class EnterDataToDBByScanner {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner([Link]);
[Link]("Enter Roll Number: ");
int rollno = [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Marks: ");
int marks = [Link]();
[Link]("[Link]");
Connection con =
[Link]("jdbc:oracle:thin:@localhost:1521:xe", "sam",
"tiger");
[Link](false);
PreparedStatement ps = [Link]("insert into student
values(?,?,?)");
[Link](1, rollno);
[Link](2, name);
[Link](3, marks);
[Link]();
[Link]("Enter Save/Cancel to Commit : ");
String option = [Link]();
if ([Link]("Save")) {
[Link]();
} else if ([Link]("Cancel")) {
[Link]();
} else {
[Link]("Invalid options !!! ");
}
[Link]("One record inserted successfully");
}
}
[Link] 27/101
4/21/23, 3:34 PM [Link]
[Link] 28/101
4/21/23, 3:34 PM [Link]
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:
[Link] 29/101
4/21/23, 3:34 PM [Link]
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.
[Link] 30/101
4/21/23, 3:34 PM [Link]
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:
[Link] 31/101
4/21/23, 3:34 PM [Link]
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
[Link] class. [Link] interface
Every applet must extends [Link] Every servlets must implements
class to derive life cycle methods. [Link] 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
[Link]
public abstract void init(ServletConfig) throws ServletException;
public abstract ServletConfig getServletConfig();
public abstract void service(ServletRequest, ServletResponse) throws
ServletException, IOException;
public abstract [Link] getServletInfo();
public abstract void destroy();
[Link] 33/101
4/21/23, 3:34 PM [Link]
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 [Link] icon
To open Tomcat Homepage:
1) Open the browser
2) Type the following in address bar
[Link]
[Link] 34/101
4/21/23, 3:34 PM [Link]
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 [Link] 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" ……/>
[Link]:
It is called as configuration file and it is used to configure servlets, listeners, filters, JSPs,
welcome files, initialization parameters , context parameter, ….etc.
[Link] 35/101
4/21/23, 3:34 PM [Link]
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 [Link].*;
import [Link];
[Link] 37/101
4/21/23, 3:34 PM [Link]
import [Link].*;
public class TimeServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
LocalTime lt = [Link]();
int h = [Link]();
int m = [Link]();
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=red text=yellow><h1>");
[Link]("Present Time: " + h + ":" + m);
[Link]("</h1></body></html>");
}
}
package basics;
import [Link].*;
import [Link].*;
public class CounterServlet extends GenericServlet {
int count;
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
count++;
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=blue><h1>");
[Link]("This page has been accessed "+count+" times");
[Link]("</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/[Link]-excel"
6) "image/jpg"
7) "image/bmp" ….etc.
⇒ Default MIME type is "text/html"
⇒ to change the MIME type use setContentType() method of [Link]
interface.
[Link] 38/101
4/21/23, 3:34 PM [Link]
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 [Link] 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.
[Link] 40/101
4/21/23, 3:34 PM [Link]
</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
[Link] 41/101
4/21/23, 3:34 PM [Link]
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));
[Link]
package login;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link] 42/101
4/21/23, 3:34 PM [Link]
[Link]();
}
}
[Link]
package login;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link] 43/101
4/21/23, 3:34 PM [Link]
try {
String s1 = [Link]("uname");
String s2 = [Link]("pword");
PreparedStatement pstmt = [Link]("select *
from uinfo where uname=? and pword=?");
[Link](1, s1);
[Link](2, s2);
ResultSet rs = [Link]();
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=cyan text=blue><h1>");
if ([Link]()) {
[Link]("welcome : " + s1);
} else {
[Link]("invalid username or password");
}
[Link]("</h1></body></html>");
} catch (SQLException e) {
[Link]();
}
}
}
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 [Link]
[Link] 44/101
4/21/23, 3:34 PM [Link]
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 [Link]
Example :
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>[Link]</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 [Link] , we use the following method of
ServletConfig interface.
Example :
public void init(ServletConfig config) throws ServletException {
try {
String s1 = [Link]("driver");
String s2 = [Link]("url");
String s3 = [Link]("username");
String s4 = [Link]("password");
[Link](s1);
[Link] = [Link](s2, s3, s4);
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
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 [Link]
</welcome-file-list>
[Link] 45/101
4/21/23, 3:34 PM [Link]
<context-param>
<param-name>driver</param-name>
<param-value>[Link]</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 [Link] by using getInitParameter()
method of [Link] interface.
Example :
public void init(ServletConfig config) throws ServletException {
try {
ServletContext sc = [Link]();
String s1 = [Link]("driver");
String s2 = [Link]("url");
String s3 = [Link]("username");
String s4 = [Link]("password");
[Link](s1);
con = [Link](s2, s3, s4);
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
ServletConfig ServletContext
[Link] 46/101
4/21/23, 3:34 PM [Link]
ServletConfig ServletContext
It is an interface in [Link] package. It is also an interface in [Link]
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 [Link] [Link]
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…
[Link] 47/101
4/21/23, 3:34 PM [Link]
[Link]("<font color=yellow> Invalid
Username/Password </font>");
RequestDispatcher rd =
[Link]("/[Link]");
[Link](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.
[Link] 48/101
4/21/23, 3:34 PM [Link]
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.
[Link] 49/101
4/21/23, 3:34 PM [Link]
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.
[Link]
import [Link].*;
import [Link];
import [Link].*;
public class SetCookie extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
[Link] 50/101
4/21/23, 3:34 PM [Link]
String s1= [Link]("book1");
String s2= [Link]("book2");
String s3= [Link]("book3");
if(s1!=null) {
Cookie c1= new Cookie("book1",s1);
[Link](c1);
}
if(s2!=null) {
Cookie c2= new Cookie("book2",s2);
[Link](c2);
}
if(s3!=null) {
Cookie c3= new Cookie("book3",s3);
[Link](c3);
}
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=blue><center>");
[Link]("<h1>Your Books are Added to Cart</h1>");
[Link]("<a href=get>Next</a>");
[Link]("</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.
[Link] 51/101
4/21/23, 3:34 PM [Link]
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.
[Link] 52/101
4/21/23, 3:34 PM [Link]
</form>
</body>
</html>
import [Link].*;
import [Link];
import [Link].*;
public class SetUrl extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= [Link]("book1");
String s2= [Link]("book2");
String s3= [Link]("book3");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=blue><center>");
[Link]("<h1>Your Books are Added to Cart</h1>");
[Link]("<a href=get?
book1="+s1+"&book2="+s2+"&book3="+s3+">Next</a>");
[Link]("</center></body></html>");
}
}
import [Link].*;
import [Link];
import [Link].*;
public class GetUrl extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= [Link]("book1");
String s2= [Link]("book2");
String s3= [Link]("book3");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=green text=yellow><center>");
[Link]("<h1><u>Your Selected Books: </u></h1>");
if()
[Link](s1+"<br>");
if()
[Link](s2+"<br>");
if()
[Link](s3+"<br>");
[Link]("</center></body></html>");
}
}
[Link] 53/101
4/21/23, 3:34 PM [Link]
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.
[Link]
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 [Link].*;
import [Link];
[Link] 54/101
4/21/23, 3:34 PM [Link]
import [Link];
import [Link].*;
public class DemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw = [Link]();
HttpSession hs = [Link]();
[Link]("<html><body bgcolor=green text=white><h1>");
[Link]("Session Id : "+[Link]()+"<br>");
[Link]("Creation Time: "+new Date([Link]())+"
<br>");
[Link]("Last Access time:
"+new Date([Link]())+"<br>");
[Link]("Time Interval: "+[Link]()+"
Seconds <br>");
[Link]("</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 [Link].*;
import [Link];
import [Link].*;
public class SetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1 = [Link]("book1");
String s2 = [Link]("book2");
String s3 = [Link]("book3");
HttpSession hs = [Link]();
[Link]("book1", s1);
[Link]("book2", s2);
[Link]("book3", s3);
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=cyan text=blue><center>");
[Link]("<h1>Your books are added to Cart: </h1>");
[Link]("<a href=get>Next</a>");
[Link]("</center></body></html>");
}
}
[Link] 55/101
4/21/23, 3:34 PM [Link]
package session2;
import [Link].*;
import [Link];
import [Link].*;
public class GetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = [Link]();
String s1= (String)[Link]("book1");
String s2= (String)[Link]("book2");
String s3= (String)[Link]("book3");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=red text=yellow>");
[Link]("<h1>Selected books: </h1>");
if(s1!=null)
[Link](s1+"<br>");
if(s2!=null)
[Link](s2+"<br>");
if(s3!=null)
[Link](s3+"<br>");
[Link]("</body></html>");
}
}
⇒ In the above example, session id created by web container, passed to client system
and stored in cookie variable at client side.
[Link]
Method:
public abstract String encodeURL(String);
⇒ it is used to append a session id to url.
package session2;
import [Link].*;
import [Link];
import [Link].*;
public class SetSession extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1 = [Link]("book1");
String s2 = [Link]("book2");
String s3 = [Link]("book3");
HttpSession hs = [Link]();
[Link]("book1", s1);
[Link]("book2", s2);
[Link]("book3", s3);
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=cyan text=blue><center>");
[Link]("<h1>Your books are added to Cart: </h1>");
String s =[Link]("get");
[Link]("<a href="+s+">Next</a>");
[Link]("</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 [Link].*;
import [Link];
[Link] 57/101
4/21/23, 3:34 PM [Link]
import [Link].*;
public class SetFields extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= [Link]("book1");
String s2= [Link]("book2");
String s3= [Link]("book3");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=blue><center>");
[Link]("<form action=get>");
[Link]("<input type=hidden name=book1 value="+s1+">");
[Link]("<input type=hidden name=book2 value="+s2+">");
[Link]("<input type=hidden name=book3 value="+s3+">");
[Link]("<h1>Your books are added to cart: </h1>");
[Link]("<input type=submit value=next>");
[Link]("</form></center></body></html>");
}
}
import [Link];
import [Link];
import [Link].*;
import [Link].*;
public class GetFields extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String s1= [Link]("book1");
String s2= [Link]("book2");
String s3= [Link]("book3");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=red text=white><center>");
[Link]("<h1><u>Your Selected Books: </u></h1>");
if()
[Link](s1+"<br>");
if()
[Link](s2+"<br>");
if()
[Link](s3+"<br>");
[Link]("</center></body></html>");
}
}
[Link]
Methods:
public abstract HttpSession getSession(boolean);
public abstract HttpSession getSession();
[Link] 58/101
4/21/23, 3:34 PM [Link]
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:
[Link] 59/101
4/21/23, 3:34 PM [Link]
================
</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) [Link]
2) [Link]
3) [Link]
4) [Link] ,,,,etc.
[Link] 60/101
4/21/23, 3:34 PM [Link]
[Link]
Methods:
public default void contextInitialized(ServletContextEvent);
public default void contextDestroyed(ServletContextEvent);
The above event handlers (method) handle ServletContextEvent.
[Link] in scl package (servlet context listener) for servlet listener 1st program
package scl;
import [Link].*;
import [Link].*;
public class MyListener implements ServletContextListener {
Connection con;
public void contextInitialized(ServletContextEvent sce) {
try {
[Link]("[Link]");
con =
[Link]("jdbc:oracle:thin:@localhost:1521:orcl",
"sam", "oracle");
ServletContext sc = [Link]();
[Link]("oracle", con);
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
public void contextDestroyed(ServletContextEvent sce) {
try {
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
M S l tj i l k ( l t t t li t )f l t li t 1 t
[Link] 61/101
4/21/23, 3:34 PM [Link]
[Link] in scl package (servlet context listener) for servlet listener 1st program
package scl;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = [Link]();
Connection con =(Connection)[Link]("oracle");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=cyan text=red><center> <h1>");
[Link]("Connection Object Obtained Successfully");
[Link]("</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:
[Link] 62/101
4/21/23, 3:34 PM [Link]
HttpSessionEvent:
HttpSessionAttributeListener:
[Link]
Methods:
public default void attributeAdded(HttpSessionBindingEvent);
public default void attributeRemoved(HttpSessionBindingEvent);
public default void attributeReplaced(HttpSessionBindingEvent);
HttpSessionBindingEvent:
package hsl;
import [Link].*;
public class MyListener implements HttpSessionListener {
int count = 0;
public void sessionCreated(HttpSessionEvent hse) {
count++;
HttpSession hs = [Link]();
[Link]("users", count);
}
public void sessionDestroyed(HttpSessionEvent hse) {
count--;
HttpSession hs = [Link]();
[Link]("users", count);
}
}
package hsl;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
[Link] 63/101
4/21/23, 3:34 PM [Link]
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession hs = [Link]();
[Link](30); //30sec
int count =(Integer)[Link]("users");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=cyan text=red><center> <h1>");
[Link]("At present "+count+" users are accessing server");
[Link]("</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.
[Link] 64/101
4/21/23, 3:34 PM [Link]
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 [Link] interface.
[Link]
Methods:
public default void init(FilterConfig) throws ServletException;
public abstract void doFilter(ServletRequest, ServletResponse,
FilterChain) throws IOException ,ServletException;
public default void destroy();
[Link] 65/101
4/21/23, 3:34 PM [Link]
[Link]
Methods:
public void doFilter(ServletRequest, ServletResponse, FilterChain)
throws IOException ,ServletException;
protected void doFilter(HttpServletRequest, HttpServletResponse,
FilterChain) throws IOException ,ServletException;
Every filter must implement [Link] 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 [Link].*;
import [Link];
import [Link].*;
public class WelcomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=red><center>");
[Link]("<h1>welcome...</h1>");
[Link]("</center><body><html>");
}
}
package filter;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
public class LoginFilter extends HttpFilter implements Filter {
Connection con;
[Link] 66/101
4/21/23, 3:34 PM [Link]
public void destroy() {
try {
[Link]();
} catch (Exception e) {
[Link]();
}
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain) {
try {
String s1 = [Link]("uname");
String s2 = [Link]("pword");
PreparedStatement pstmt = [Link]("select *
from uinfo where uname=? and pword=?");
[Link](1, s1);
[Link](2, s2);
ResultSet rs = [Link]();
if ([Link]()) {
[Link](request, response);
} else {
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=red text=yellow><h1>");
[Link]("invalid username/password");
[Link]("</h1><body><html>");
}
} catch (SQLException | IOException | ServletException e) {
[Link]();
}
}
public void init(FilterConfig fConfig) throws ServletException {
try {
[Link]("[Link]");
con =
[Link]("jdbc:oracle:thin:@localhost:1521:orcl",
"sam", "oracle");
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
}
[Link] 67/101
4/21/23, 3:34 PM [Link]
</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 [Link];
import [Link].*;
import [Link].*;
public class CounterFilter extends HttpFilter implements Filter {
int count=0;
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws IOException,
ServletException {
count++;
[Link] 68/101
4/21/23, 3:34 PM [Link]
ServletContext sc = [Link]();
[Link]("views", count);
[Link](request, response);
}
}
package count;
import [Link].*;
import [Link].*;
import [Link].*;
public class CounterServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
ServletContext sc = [Link]();
int count =(Integer)[Link]("views");
PrintWriter pw = [Link]();
[Link]("<html><body bgcolor=yellow text=red><h1>");
[Link]("The homepage has been accessed " + count + "
times.");
[Link]("</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.
[Link] 69/101
4/21/23, 3:34 PM [Link]
JSP Architecture:
1) Conversion
2) Compilation
3) Execution
JSP Elements:
1. Scripting Elements.
2. Directives
3. Actions
[Link] 70/101
4/21/23, 3:34 PM [Link]
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:
[Link] file
[Link] file
<html>
<body bgcolor=yellow text=blue>
<h1>
<% [Link]("Welcome to Naresh iTechnologies Ameerpet, Hyderabad");
%>
</h1>
</body>
</html>
<html>
<body bgcolor=green text=white>
<h1>
<jsp:scriptlet>
[Link]("Welcome to Naresh I technologies");
</jsp:scriptlet>
</h1>
</body>
</html>
[Link] 72/101
4/21/23, 3:34 PM [Link]
JSP to Servlet:
Declarations:
Scriptlets:
Expressions:
[Link] 73/101
4/21/23, 3:34 PM [Link]
<html>
<body bgcolor=red text=yellow>
<% [Link] lt = [Link](); %>
<%= 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
[Link] 74/101
4/21/23, 3:34 PM [Link]
[Link] 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="[Link]">
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=[Link]("uname");
String s2=[Link]("pword");
if([Link]("abc")&& [Link]("xyz")){
[Link]("Welcome");
}else{
[Link]("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><% [Link]("include directive example"); %></u></h1>
<%@ include file="[Link]" %>
[Link] 75/101
4/21/23, 3:34 PM [Link]
<%@ include file="[Link]" %>
<%@ include file="[Link]" %>
</body>
</html>
Page Directive:
1. language
2. import
3. buffer
[Link] 76/101
4/21/23, 3:34 PM [Link]
4. autoFlush
@The above buffer & autoFlush attributes are used to manage buffer memory efficiently.
5. errorPage
6. isErrorPage
In the above example [Link] program executed whenever exception occurs in a [Link].
<!DOCTYPE html>
<html>
<body bgcolor=green text=yellow>
<h1><u>Arithmetic Application</u></h1>
<form action=[Link]>
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="[Link]"%>
<%
String s1 = [Link]("first");
String s2 = [Link]("second");
int x= [Link](s1);
int y= [Link](s2);
int z=x/y;
[Link]("output : "+ z);
%>
</body>
</html>
<html>
<body bgcolor=red text=yellow>
<%@ page isErrorPage="true" %>
<% [Link]("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>
[Link] 78/101
4/21/23, 3:34 PM [Link]
<%= "Session Creation Time: "+new Date([Link]()) %>
<br>
<%= "Session Last Accessed Time: "+new Date(session.
getLastAccessedTime ()) %><br>
<%= "Default Time Interval: " +[Link]()+"
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=[Link]>
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 = [Link]("operation");
if ([Link]("addition")) {
%><jsp:forward page="[Link]"/><%
} else if ([Link]("subtraction")) {
%><jsp:forward page="[Link]"/><%
} else if ([Link]("multiplication")) {
%><jsp:forward page="[Link]"/><%
} else
[Link] 80/101
4/21/23, 3:34 PM [Link]
%><jsp:forward page="[Link]"/><%
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Addition Result</h1>
<%
String s1 = [Link]("first");
String s2 = [Link]("second");
int x = [Link](s1);
int y = [Link](s2);
[Link]("Output: "+(x+y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Subtraction Result</h1>
<%
String s1 = [Link]("first");
String s2 = [Link]("second");
int x = [Link](s1);
int y = [Link](s2);
[Link]("Output: "+(x-y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Multiplication Result</h1>
<%
String s1 = [Link]("first");
String s2 = [Link]("second");
int x = [Link](s1);
int y = [Link](s2);
[Link]("Output: "+(x*y));
%>
</body>
</html>
<html>
<body bgcolor=red text=white>
<h1>Division Result</h1>
<%
String s1 = [Link]("first");
String s2 = [Link]("second");
int x = [Link](s1);
int y = [Link](s2);
[Link]("Output: "+(x/y));
%>
</body>
</html>
[Link] 81/101
4/21/23, 3:34 PM [Link]
2. <jsp:include>
It is used to include the request & response of one jsp into another jsp
[Link] file for including jsp to another jsp it’s in jsp project.
<html>
<body>
[Link] 82/101
4/21/23, 3:34 PM [Link]
<center><h1><u><font color=red>
<% [Link]("JSP Tutorial"); %>
</font></u></h1></center>
</body>
</html>
[Link] file for including jsp to another jsp it’s in jsp project.
<html>
<body>
<center><h2><font color=blue>
<% [Link]("Naresh I technologies, Ameerpet, Hyderabad"); %>
</font></h2></center>
</body>
</html>
[Link] file for including jsp to another jsp it’s in jsp project.
<html>
<body bgcolor=yellow text=green>
<jsp:include page="[Link]"/>
<h1><u>JSP:</u></h1>
<% [Link]("JSP stands for Java Server Pages. JSP is a specification
for developing web applications with Java programming language."); %>
<jsp:include page="[Link]"/>
</body>
</html>
[Link] file for including jsp to another jsp it’s in jsp project.
<html>
<body bgcolor=yellow text=green>
<jsp:include page="[Link]"/>
<h1><u>JSTL:</u></h1>
<% [Link]("JSTL stands for Java server pages Standard Tag Library.
It is introduced in JSP 2.0 version to simplify the JSP."); %>
<jsp:include page="[Link]"/>
</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:
[Link] 84/101
4/21/23, 3:34 PM [Link]
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 [Link] 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="[Link].*"%>
<%!Connection con;
Package demo;
Import [Link]*;
public class MessageBean implements Serializable{
private String message;
void setMessage(String message){
[Link]=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> :
[Link] 86/101
4/21/23, 3:34 PM [Link]
<jsp:setProperty> :
<jsp:getProperty> :
package jsp;
import [Link];
public class MessageBean implements Serializable {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
[Link] = message;
}
}
[Link] 87/101
4/21/23, 3:34 PM [Link]
<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.
[Link] 88/101
4/21/23, 3:34 PM [Link]
● 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
[Link] 89/101
4/21/23, 3:34 PM [Link]
pageScope:
requestScope:
sessionScope:
applicationScope:
[Link]:
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>
<%
[Link]("platform1", "JavaSE",
PageContext.PAGE_SCOPE);
[Link]("platform2", "JavaEE",
PageContext.REQUEST_SCOPE);
[Link]("platform3", "JavaME",
PageContext.SESSION_SCOPE);
[Link]("platform4", "JavaFX",
PageContext.APPLICATION_SCOPE);
%>
${ pageScope.platform1 }<br> ${ requestScope.platform2 }<br>
${ sessionScope.platform3 }<br> ${ applicationScope.platform4 }
</h1>
</body>
</html>
[Link] 90/101
4/21/23, 3:34 PM [Link]
In the above example, platform1 can be accessed in [Link] only because its scope is page
scope , platform2 can be accessed in [Link] & [Link] because its scope is request
scope, platform3 can be accessed in [Link], [Link], & [Link] because its scope is
session scope and platform can be accessed in all pages in a .war file.
param:
initParam:
cookie:
[Link] 91/101
4/21/23, 3:34 PM [Link]
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="[Link] prefix="c"%>
<c:set>
<c:remove>
<html>
[Link] 92/101
4/21/23, 3:34 PM [Link]
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="[Link] prefix="c"%>
<c:set var="a" value="10" />
<c:out value="${a}" />
<c:if>
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="[Link] 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="[Link] 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" />
[Link] 93/101
4/21/23, 3:34 PM [Link]
</c:otherwise>
</c:choose>
</h1>
</body>
</html>
<c:forEach> :
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="[Link] prefix="c"%>
<c:forTokens> :
<html>
<body bgcolor=green text=yellow>
<h1>
<%@ taglib uri="[Link] prefix="c"%>
<c:forTokens var="s" items="Welcome to JSTL" delims=" ">
[Link] 94/101
4/21/23, 3:34 PM [Link]
<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="[Link] prefix="c"%>
<%@ taglib uri="[Link] prefix="sql"%>
<sql:setDataSource var="con" driver="[Link]"
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="[Link] prefix="c"%>
<%@ taglib uri="[Link] prefix="sql"%>
[Link] 95/101
4/21/23, 3:34 PM [Link]
</h1>
</body>
</html>
<sql:query>
<html>
<body bgcolor=yellow text=blue>
<table border=10>
<%@ taglib uri="[Link] prefix="c"%>
<%@ taglib uri="[Link] 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.
[Link] 96/101
4/21/23, 3:34 PM [Link]
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 [Link];
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/result")
public class ResultServlet extends HttpServlet {
[Link] 97/101
4/21/23, 3:34 PM [Link]
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String s = [Link]("hno");
int h = [Link](s);
ResultDAO rdao = new ResultDAO();
ResultBean rb = [Link](h);
[Link]("result", rb);
RequestDispatcher rd =
[Link]("/[Link]");
[Link](request, response);
}
}
package mvc;
import [Link].*;
public class ResultDAO {
ResultBean getResult(int hno) {
ResultBean rb=null;
try {
[Link]("[Link]");
Connection con=
[Link]("jdbc:oracle:thin:@localhost:1521:orcl","sam","oracle");
PreparedStatement pstmt = [Link]("select * from results
where hno=?");
[Link](1, hno);
ResultSet rs= [Link]();
rb= new ResultBean();
if([Link]()) {
[Link]([Link]("hno"));
[Link]([Link]("name"));
[Link]([Link]("c"));
[Link]([Link]("cpp"));
[Link]([Link]("java"));
}
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
return rb;
}
}
package mvc;
<html>
<body bgcolor=green text=yellow><h1>
<% [Link] rb=([Link])[Link]("result"); %>
Hall Ticket Number <%= [Link]() %><br>
Name : <%= [Link]() %><br>
C : <%= [Link]() %><br>
C++ : <%= [Link]() %><br>
Java : <%= [Link]() %>
</h1></body>
</html>
Oracle table to show info for mvc project (table name is results)
In the above examples, [Link] & [Link] contains presentation logic, [Link]
contains controlling logic, [Link] contains data access logic & [Link]
contains data whatever is retrieved from the database.
Advantages of MVC:
1) Easy to maintain
2) Easy to update
[Link] 99/101
4/21/23, 3:34 PM [Link]
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.
[Link] package:
Classes:
1) Field
2) Method
3) Constructor
[Link]
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.
[Link] 100/101
4/21/23, 3:34 PM [Link]
[Link] 101/101
Session tracking methods used to maintain client state information include Cookies, URL Rewriting, HttpSession, and Hidden Form Fields. Cookies store client state information in the client's browser, allowing limited String type data and losing information if cookies are disabled. URL Rewriting appends data to the URL, making it visible in the address bar and also limited to String data. HttpSession stores state information server-side, creating a session ID maintained either through cookies or URL rewriting. This method can maintain information across multiple requests and session IDs are managed by the web container. Hidden Form Fields involve embedding data within HTML forms but are only viable when interacting with form submissions, thereby limiting their versatility to user-triggered actions .
Servlet forwarding and redirecting differ primarily in how they handle requests and responses. In servlet forwarding, the server implicitly passes the request and response from one servlet to another within the same server. This process does not change the <url-pattern>, and only one pair of request and response is maintained by the web container. Conversely, in servlet redirecting, the server instructs the browser to execute a new URL. This causes a change in the <url-pattern> and creates a separate pair of request and response for each redirected servlet. Additionally, forwarding supports servlet-to-servlet, HTML, and JSP transitions while redirecting can work within the server and between different servers, supporting a wider range of transitions, including ASP, ASP.NET, and PHP .
HTTP sessions with cookies and URL rewriting differ fundamentally in where and how the session ID is stored and maintained. In HTTP sessions with cookies, the session ID is stored on the client side within a cookie variable, assuming the browser's setting supports cookie storage. This method provides persistence across browser sessions as long as the cookies are valid. URL Rewriting, however, appends the session ID directly to URLs during the client's navigation, displaying the session ID visibly in the browser's address bar. While URL Rewriting works even when cookies are disabled, it requires changes to all URLs to preserve session state and does not persist beyond the current browser session. Additionally, URL Rewriting may expose session details more readily than cookies, imposing potential security concerns .
To configure a Tomcat Web Server in Eclipse, open the JavaEE perspective, navigate to the 'Servers' view, right-click to select 'New' and choose 'Server'. Choose 'Apache > Tomcat v10.0 Server', click 'Next', browse to select the Tomcat installation directory, and finish the setup by clicking 'Next' and 'Finish'. To change Tomcat's default port number, locate the 'server.xml' file (found in 'C:/Program Files/Apache Software Foundation/Tomcat 10.0/conf'), and modify the port number by adjusting the <Connector port> attribute from '8080' to a new port such as '8082'. Save the changes to apply the new configuration .
To configure servlets within a Tomcat Server through Eclipse, begin by ensuring your current perspective is set to JavaEE. In the 'Servers' view, add a new server by right-clicking and choosing 'New', selecting 'Server', and then 'Apache Tomcat v10.0'. Follow the prompts to set the installation directory and finish the setup. For each servlet, configure it in the 'web.xml' of your web application by adding servlet and servlet-mapping elements to define the servlet’s name and URL patterns it handles. This configuration is essential as it enables the Tomcat server to manage requests properly and direct them to the appropriate servlets based on the URL patterns specified. It sets the groundwork for robust Java web applications by allowing servlets to be mapped, managed, and invoked effectively within the Tomcat environment .
The PreparedStatement interface offers significant improvements over standard Statement objects by allowing the execution of parameterized queries, which enhances performance and security. PreparedStatement compiles the SQL query once and executes it numerous times with different parameters, reducing parsing time and resource utilization during repeated executions. This approach minimizes SQL injection risks by enabling the SQL engine to distinguish between code and data, ensuring that data inputs cannot alter query semantics. Moreover, using PreparedStatement results in less server-side recompilation and can optimize query execution plans due to the predictability of parameterized inputs .
To add an external JAR file to a project in Eclipse, right-click on the project in the Package Explorer, select 'Build Path', and then 'Configure Build Path'. Navigate to the 'Libraries' tab and click 'Add External JARs'. Browse to the location of the JAR file, for instance, 'ojdbc6_g.jar', select it, and click 'Open'. Apply and close the configurations. Including external JAR files is crucial for JDBC programming as they often contain necessary classes and interfaces needed to establish database connections and execute SQL statements. Without these JAR files, the Java application would lack the required dependencies to interact with a database .
Creating and managing a session with the HttpSession interface in Java servlets involves the following steps: In the servlet, retrieve or create a session object using 'HttpSession session = request.getSession();'. Use 'session.setAttribute(String, Object)' to store user-specific data, allowing state tracking across requests. Configure session expiration using 'session.setMaxInactiveInterval(int)' to define how long a session should stay active. During user interactions, retrieve session attributes using 'session.getAttribute(String)', and if needed, remove them with 'session.removeAttribute(String)'. To end the session, use 'session.invalidate()', which removes the session and its attributes. This mechanism is critical for applications requiring user identity persistence, such as shopping carts or login sessions, and it helps ensure that user data is consistently accessible throughout their session .
The web.xml configuration file fundamentally influences a servlet's behavior by defining its deployment descriptor, which includes servlet mapping, initialization parameters, context parameters, and more. It plays a pivotal role in specifying servlet names, the URL patterns they respond to, and the sequence of filters applied. For example, it configures which servlets handle certain requests through <servlet-mapping> tags and can dictate initialization parameters necessary for the servlet's operational logic. Additionally, web.xml allows the configuration of error pages, security constraints, and session timeout settings, contributing significantly to a web application's structural and behavioral attributes .
To write and run a JDBC program in Eclipse using the Java perspective, follow these steps: Open the Java perspective by selecting 'Window', then 'Perspective', and 'Open Perspective'. Create a new Java project by navigating to 'File', 'New', 'Java Project', and entering a project name, such as 'jdbc'. Finish the setup by clicking 'Next', then 'Finish', and choosing 'Don't Create'. In the package explorer, right-click on the project 'jdbc', select 'New', 'Class', and input a class name, for example, 'ConnectionDemo'. Include the main() method and click 'Finish' to proceed. Write your JDBC program in the editor. To add necessary JAR files, right-click on the project, choose 'Build Path', then 'Configure Build Path', go to the 'Libraries' tab, click 'Add External JARs', select the needed JAR files like 'ojdbc6_g.jar', and click 'Open', followed by 'Apply & Close'. Finally, to run the application, right-click on 'ConnectionDemo.java', select 'Run As', and choose 'Java Application' .









