Java JDBC
JDBC stands for Java Database Connectivity.
JDBC is a Java API to connect and execute the
query with the database.
The java.sql package contains classes and
interfaces for JDBC API.
A list of popular interfaces of JDBC API are given
below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
A list of popular classes of JDBC API are given
below:
o DriverManager class
o Blob class
o Clob class
Useful methods of DriverManager class
Method Description
1) public static void is used to register the
registerDriver (Driver given driver with
driver): DriverManager.
2) public static void is used to deregister
deregisterDriver (Driver the given driver (drop
driver): the driver from the
list) with
DriverManager.
3) public static is used to establish
Connection the connection with
getConnection (String the specified url.
url):
4) public static is used to establish
Connection the connection with
getConnection (String the specified url,
url,StringuserName,Strin username and
g password): password.
Connection interface
Commonly used methods of Connection interface:
public Statement createStatement(): creates a
statement object that can be used to execute SQL
queries.
public void close(): closes the connection and
Releases a JDBC resources immediately.
Statement interface
Commonly used methods of Statement interface:
1) public ResultSet executeQuery(String
sql): is used to execute SELECT query.
It returns the object of ResultSet.
2) public int executeUpdate(String sql): is
used to execute specified query,
it may be create, drop, insert, update, delete etc.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a
row of a table. Initially, cursor points to before the first
row.
Commonly used methods of ResultSet interface
1) public is used to move the cursor to
boolean next(): the one row next from the
current position.
2) public is used to move the cursor to
boolean the one row previous from the
previous(): current position.
3) public is used to move the cursor to
boolean first(): the first row in result set
object.
4) public is used to move the cursor to
boolean last(): the last row in result set
object.
Java Database Connectivity Steps
There are 5 steps to connect any java application
with the database using JDBC. These steps are
as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to
register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)
throws ClassNotFoundException
Example to register the Oracle Driver class
Here, Java program is loading oracle driver to
establish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class
is used to establish connection with the database.
Syntax of getConnection() method
1) public static Connection
getConnection(String url)
throws SQLException
2) public static Connection
getConnection(String url, String name,
String password) throws SQLException
Example to establish connection with the Oracle
database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",
"password");
3) Create the Statement object
The createStatement() method of Connection
interface is used to create statement. The object of
statement is responsible to execute queries with
the database.
Syntax of createStatement() method:
public Statement createStatement()
throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
int executeUpdate() method of Statement
interface is used to execute non select
queries to the database.
The executeQuery() method of Statement interface
is used to execute select queries to the database.
This method returns the object of ResultSet that can
be used to get all the records of a table.
Syntax of executeQuery() method
Public ResultSet executeQuery(String sql)
throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from e
mp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(
2));
}
5) Close the connection object
By closing connection object statement and
ResultSet will be closed automatically. The close()
method of Connection interface is used to close the
connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
Example program to Connect Java Application with Oracle
database
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from e
mp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString
(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}
catch(Exception e)
{ System.out.println(e); }
}
}
To connect java application with the Oracle database
ojdbc14.jar or classes12.jar file is required to be
loaded.
Download the jar file ojdbc14.jar or classes12.jar
Two ways to load the jar file:
1. paste the ojdbc14.jar file in XXX folder
2. set classpath
setclasspath:
Go to environment variable set classpath to ojdbc14.jar
Example program of Statement to insert records into database.
import java.sql.*;
import java.io.*;
class RS{
public static void main (String args[])
throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("j
dbc:oracle:thin:@localhost:1521:xe","system","o
racle");
Statement s=con.createStatement();
int i=s.executeUpdate("insert into emp130 value
s(1,’ramu’,10000");
System.out.println(i+" records affected");
int i=s.executeUpdate("insert into emp130 value
s(2,’ravi’,20000");
System.out.println(i+" records affected");
con.close();
}}
PreparedStatement interface
The PreparedStatement interface is a sub
interface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for
the values. Its value will be set by calling the
setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of
the application will be faster if you use
PreparedStatement interface because query is
compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection
interface is used to return the object of
PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(Str
ing query) throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement
interface are given below:
Method Description
public void setInt sets the integer value to
(intparamIndex, int the given parameter
value) index.
public void setString sets the String value to
(intparamIndex, String the given parameter
value) index.
public void setFloat sets the float value to
(intparamIndex, float the given parameter
value) index.
public void setDouble sets the double value to
(intparamIndex, double the given parameter
value) index.
public int executes the query. It is
executeUpdate() used for create, drop,
insert, update, delete
etc.
public ResultSet executes the select
executeQuery() query. It returns an
instance of ResultSet.
Example program of PreparedStatement to insert records into
database until user press n.
import java.sql.*;
import java.io.*;
class RS{
public static void main (String args[])
throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("j
dbc:oracle:thin:@localhost:1521:xe","system","o
racle");
PreparedStatement ps=con.prepareStatement("i
nsert into emp130 values(?,?,?)");
BufferedReader br=new BufferedReader(new In
putStreamReader(System.in));
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
System.out.println("Do you want to continue: y/
n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
con.close();
}}
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can
get further information from the data.
If you have to get metadata of a table like total
number of column, column name, column type
etc. .
ResultSetMetaData interface is useful because it
provides methods to get metadata from the
ResultSet object.
Commonly used methods of ResultSetMetaData
interface
Method Description
public int getColumnCount() it returns the total
throws SQLException number of columns
in the ResultSet
object.
public String it returns the
getColumnName(int index) column name of
throws SQLException the specified
column index.
public String it returns the
getColumnTypeName (int column type name
index) throws SQLException for the specified
index.
public String it returns the table
getTableName(int index) name for the
throws SQLException specified column
index.
Example program of ResultSetMetaData interface :
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
PreparedStatement ps=con.prepareStatement("s
elect * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getC
olumnCount());
System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st co
lumn: "+rsmd.getColumnTypeName(1));
con.close();
}
catch(Exception e){ System.out.println(e);}
}
}
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
method calls into the ODBC function calls. This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.
Advantage:
o No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
Example web application to insert Registration form data into
database
You need to create a table first as given below:
CREATE TABLE "REGISTERUSER" ( NAME VARCHAR2(4000),
PASS VARCHAR2(4000), EMAIL VARCHAR2(4000),
COUNTRY VARCHAR2(4000) )
webapp
WEB-INF
classes
lib
web.xml
In this example, we have created the three pages.
o register.html
o Register.java
o web.xml
register.html
In this page, we have getting input from the user using text fields and combobox. The
information entered by the user is forwarded to Register servlet, which is responsible to
store the data into the database.
<html>
<body>
<form action="store" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><
br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Register.java
This servlet class receives all the data entered by user and stores it into the database.
Here, we are performing the database logic. But you may separate it, which will be
better for the web application.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void service(HttpServletRequest request, HttpServletRe
sponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}catch (Exception e2) {System.out.println(e2);}
con.close();
}
web.xml file
The is the configuration file, providing information about the servlet.
<web-app>
<servlet>
<servlet-name>Registerservlet</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registerservlet</servlet-name>
<url-pattern>/store</url-pattern>
</servlet-mapping>
</web-app>
Example web application to display data from
database.
index.html
<html>
<body><form action="show" method="post">
Enter Table Name :<input type="text" name="table">
<input type="submit" value="Display">
</form>
</body>
</html>
ServletDatabaseConnect.java
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.Statement;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class ServletDatabaseConnect extends HttpServlet
{
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriterpw=res.getWriter();
res.setContentType("text/html");
Stringtb=req.getParameter("table");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"admin");
Statement st=con.createStatement();
System.out.println("connection established successfully...!!");
ResultSetrs=st.executeQuery("Select * from "+tb);
pw.println("<table border=1>");
while(rs.next())
{
pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+
"<td>"+rs.getString(3)+"</td></tr>");
}
pw.println("</table>");
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>ServletDBConnect</servlet-name>
<servlet-class>java4s.ServletDatabaseConnect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDBConnect</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
</web-app>
Example web application for user authentication
create table userreg(name varchar2(40),pass var
char2(40));
login.html
<form action="authenticate" method="post">
Name:<input type="text" name="username"/><br/><br/>
Password:<input type="password" name="userpass"/><br/><
br/>
<input type="submit" value="login"/>
</form>
validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class validate extends HttpServlet {
public void service(HttpServletRequest request, HttpServletRe
sponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement s=con.CreateStatement( );
ResultSet rs =s.executeQuery("select username, pass
from registeruser “);
Boolean flag=false;
While(rs.next())
{
if(n.equals(rs.getString(1)) && p.quals(rs.getString(2))
{
out.println(“you are authorized user”);
flag=true
break;
}
}
If(!flag)
{
Out.println(“you are un authorized user”);
}
}
}
import java.sql.*;
public class LoginDao {
public static boolean validate(String name,Stri
ng pass){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
PreparedStatement ps=con.prepareStatement(
"select * from userreg where name=? and pass=
?");
ps.setString(1,name);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServl
et {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
out.close();
}
JSP (java server pages)
JSP technology is used to create web application just
like Servlet technology.
It is an extension to Servlet because it provides more
functionality than servlet such as expression language,
JSTL, etc.
The JSP pages are easier to maintain than Servlet
because we can separate designing and development.
A JSP page consists of HTML tags and JSP tags.
Extension to jsp page is .jsp
Advantages of JSP over Servlet
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can
use all the features of the Servlet in JSP. In addition to, we
can use implicit objects, predefined tags, expression language
and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. In Servlet technology,
we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and
redeploy
If JSP page is modified, we don't need to recompile and
redeploy the project. The Servlet code needs to be updated
and recompiled if we have to change the look and feel of the
application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL,
custom tags, etc. that reduces the code. Moreover, we can use
EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
Translation of JSP Page
Compilation of JSP Page
Classloading (the classloader loads class file)
Instantiation (Object of the Generated Servlet is
created).
Initialization (the container invokes jspInit() method).
Request processing (the container invokes _jspService()
method).
Destroy (the container invokes jspDestroy() method).
Creating a simple JSP Page
To create the first JSP page, write some HTML code as given
below, and save it by .jsp extension.
index.jsp
<html>
<body>
<h1>Welcome</h1>
</body>
</html>
The Directory structure of JSP
Jsp elements
1. Template text
2. Scripting elements
3. Jsp custom tags
4. Jsp action tags
5. Jsp tag directives
Template text
Which is directly sent to browser
index.jsp
<h1>Welcome</h1>
JSP Scripting elements
The scripting elements provides the ability to insert java code
inside the jsp. There are three types of scripting elements:
scriptlet tag
expression tag
declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form> </body> </html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
JSP expression tag
The code placed within JSP expression tag is written to the
output stream of the response. So you need not write
out.print() to write data. It is mainly used to print the values of
variable or method.
Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply
displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Example of JSP expression tag that prints current time
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime()
%>
</body>
</html>
Example of JSP expression tag that welcome the user
by their name
index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
JSP Declaration Tag
The JSP declaration tag is used to declare fields and
methods.
The code written inside the jsp declaration tag is placed
outside the service() method of auto generated servlet.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration
tag
JspScriptlet Tag Jsp Declaration Tag
The jspscriptlet tag can only The jsp declaration tag can
declare variables not declare both variables as well
methods. as methods.
The declarations of jsp
The declarations of scriptlet
declaration tag is placed
tag is placed inside the
outside the _jspService()
_jspService() method.
method.
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the
field and printing the value of the declared field using the jsp
expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %> or <% int res=cube(3);
out.print(res); %>
</body>
</html>
JSP Implicit Objects
There are 9 jsp implicit objects. These objects are created by
the web container that are available to all the jsp pages.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1) JSP out implicit object
Example of out implicit object
In this example we are simply displaying date and time.
index.jsp
<html>
<body>
<% out.print("welcome”); %>
</body>
</html>
2) JSP request implicit object
The JSP request is an implicit object of type
HttpServletRequest
It can be used to get request information.
Simple example for printing the name of the user with
welcome message using request implicit object.
Example of JSP request implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
JSP response implicit object
In JSP, response is an implicit object of type
HttpServletResponse.
The instance of HttpServletResponse is created by the web
container for each jsp request.
It can be used to add or manipulate response such as redirect
response to another resource, sending error etc.
Example for redirecting the response to the Google using
response implicit object.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
JSP config implicit object
In JSP, config is an implicit object of type ServletConfig.
This object can be used to get initialization parameter for a
particular JSP page.
The config object is created by the web container for each jsp
page.
Generally, it is used to get initialization parameter from the
web.xml file.
Example of config implicit object:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>name</param-name>
<param-value>ramu</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String usr=config.getInitParameter("name");
out.print("user name is="+usr);
%>
JSP application implicit object
In JSP, application is an implicit object of type
ServletContext.
The instance of ServletContext is created only once by the
web container when application or project is deployed on the
server.
This object can be used to get initialization parameter from
configuaration file (web.xml). It can also be used to get, set or
remove attribute from the application scope.
This initialization parameter can be used by all jsp pages.
Example of application implicit object:
index.html
<form action="welcome">
input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>ramu</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String usr=application.getInitParameter("name");
out.print("user name is="+usr);
%>
session implicit object
In JSP, session is an implicit object of type HttpSession.
The Java developer can use this object to set,get or remove
attribute or to get session information.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user", name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
pageContext implicit object
In JSP, pageContext is an implicit object of type PageContext
class.
The page Context object can be used to set, get or remove
attribute from one of the following scopes:
page
request
session
application
In JSP, page scope is the default scope.
Example of pageContext implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION
_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageCo
ntext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
exception implicit object
In JSP, exception is an implicit object of type
java.lang.Throwable class.
This object can be used to print the exception. But it can only
be used in error pages.
Example of exception implicit object:
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
JSP directives
The jsp directives are messages that tells the web container
how to translate a JSP page into the corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
JSP page directive
The page directive defines attributes that apply to an entire
JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
session
errorPage
isErrorPage
import
The import attribute is used to import class, interface or all
the members of a package. It is similar to import keyword in
java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
contentType
The contentType attribute defines the MIME(Multipurpose
Internet Mail Extension) type of the HTTP response.
The default value is "text/html;
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
extends
The extends attribute defines the parent class that will be
inherited by the generated servlet.
info
This attribute simply sets the information of the JSP page
which is retrieved later by using getServletInfo() method of
Servlet interface.
Example of info attribute
<html>
<body>
<%@ page info="my servlet" %>
Information About servlet is: <%= getServletInfo () %>
</body>
</html>
The web container will create a method getServletInfo() in the
resulting servlet. For example:
public String getServletInfo() {
return "my servletl";
}
buffer
The buffer attribute sets the buffer size in kilobytes to handle
output generated by the JSP page. The default size of the
buffer is 8Kb.
Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
language
The language attribute specifies the scripting language used in
the JSP page. The default value is "java".
isELIgnored
We can ignore the Expression Language (EL) in jsp by the
isELIgnored attribute. By default its value is false i.e.
Expression Language is enabled by default. We see
Expression Language later.
<%@ page isELIgnored="true" %> //Now EL will be ignored
isThreadSafe
Servlet and JSP both are multithreaded. If you want to
control this behaviour of JSP page, you can use isThreadSafe
attribute of page directive. The value of isThreadSafe value is
true. If you make it false, the web container will serialize the
multiple requests, i.e. it will wait until the JSP finishes
responding to a request before passing another request to it.
If you make the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
errorPage
The errorPage attribute is used to define the error page, if
exception occurs in the current page, it will be redirected to
the error page.
Example of errorPage attribute
index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the current
page is the error page.
The exception object can only be used in the error page.
Example of isErrorPage attribute
myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body> </html>
Jsp Include Directive
The include directive is used to include the contents of any
resource it may be jsp file, html file or text file.
The include directive includes the original content of the
included resource at page translation time (the jsp page is
translated only once so it will be better to include static
resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the
header.html file. To run this example you must create an
header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Taglib directive
The JSP taglib directive is used to define a tag library that
defines many tags.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary
" %>
Exception Handling in JSP
The exception is normally an object that is thrown at runtime.
Exception Handling is the process to handle the runtime
errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web
developer. In JSP, there are two ways to perform exception
handling:
1. By errorPage and isErrorPage attributes of page
directive
2. By <error-page> element in web.xml file
Example of exception handling in jsp by the
elements of page directive
In this case, you must define and create a page to handle
the exceptions, as in the error.jsp page. The pages
where may occur exception, define the errorPage
attribute of page directive, as in the process.jsp page.
There are 3 files:
index.jsp for input values
process.jsp for dividing the two numbers and
displaying the result
error.jsp for handling the exception
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
Example of exception handling in jsp by
specifying the error-page element in web.xml file
This approach is better because you don't need to
specify the errorPage attribute in each jsp page.
Specifying the single entry in the web.xml file will
handle the exception. In this case, either specify
exception-type or error-code with the location element.
If you want to handle all the exception, you will have to
specify the java.lang.Exception in the exception-type
element. Let's see the simple example:
There are 4 files:
web.xml file for specifying the error-page element
index.jsp for input values
process.jsp for dividing the two numbers and
displaying the result
error.jsp for displaying the exception
1) web.xml file if you want to handle any
exception
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-
type>
<location>/error.jsp</location>
</error-page>
</web-app>
This approach is better if you want to handle any
exception. If you know any specific error code and you
want to handle that exception, specify the error-code
element instead of exception-type as given below:
1) web.xml file if you want to handle the exception
for a specific error code
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
2) index.jsp file is same as in the above example
3) process.jsp
Now, you don't need to specify the errorPage attribute
of page directive in the jsp page.
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
JSP Action Tags
Each JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages
and to use Java Bean. The Jsp action tags are given below.
JSP Action
Description
Tags
forwards the request and response to another
jsp:forward
resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
sets the parameter value. It is used in forward
jsp:param
and include mostly.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are
used for bean development. So we will see these tags in bean
developement.
jsp:forward action tag
The jsp:forward action tag is used to forward the request to
another resource it may be jsp, html or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL " />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL">
<jsp:param name="parametername" value="parametervalue
" />
</jsp:forward>
Example of jsp:forward action tag without parameter
In this example, we are simply forwarding the request to the
printdate.jsp file.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getT
ime()); %>
</body> </html>
Example of jsp:forward action tag with parameter
In this example, we are forwarding the request to the
printdate.jsp file with parameter and printdate.jsp file prints
the parameter value with date and time.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="java" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getT
ime()); %>
<%= request.getParameter("name") %>
</body>
</html>
jsp:include action tag
The jsp:include action tag is used to include the content of
another resource it may be jsp, html or servlet.
The jsp include action tag includes the resource at request
time so it is better for dynamic pages because there might be
changes in future.
The jsp:include tag can be used to include static as well as
dynamic pages.
Advantage of jsp:include action tag
Code reusability: We can use a page many times such as
including header and footer pages in all pages. So it saves a
lot of time.
Difference between jsp include directive and include
action
JSP include directive JSP include action
includes resource at translation includes resource at
time. request time.
better for dynamic
better for static pages.
pages.
includes the original content in the calls the include
generated servlet. method.
Syntax of jsp:include action tag without parameter
<jsp:include page="relativeURL" />
Syntax of jsp:include action tag with parameter
<jsp:include page="relativeURL">
<jsp:param name="parametername" value="parametervalue
” />
</jsp:include>
Example of jsp:include action tag without parameter
In this example, index.jsp file includes the content of the
printdate.jsp file.
index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getT
ime()); %>
Java Bean
A Java Bean is a java class that should follow following
conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of
the properties, known as getter and setter methods.
Why use Java Bean?
It is a reusable software component. It provides easy
maintenance.
Simple example of java bean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee()
{ }
public void setId(int id)
{ this.id=id; }
public int getId()
{ return id; }
public void setName(String name)
{ this.name=name; }
public String getName()
{ return name; }
}
How to access the java bean class?
To access the java bean class, we should use getter and
setter methods.
package mypack;
public class Test{
public static void main(String args[])
{
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}
}
jsp:useBean action tag
The jsp:useBean action tag is used instantiate a bean class. If
bean object of the Bean class is already created, it doesn't
create the bean depending on the scope.
But if object of bean is not created, it instantiates the bean.
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | s
ession | application" class= "packageName.className"
>
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be
page, request, session or application. The default scope
is page.
o page: specifies that you can use this bean within
the JSP page. The default scope is page.
o request: specifies that you can use this bean from
any JSP page that processes the same request. It
has wider scope than page.
o session: specifies that you can use this bean from
any JSP page in the same session whether
processes the same request or not. It has wider
scope than request.
o application: specifies that you can use this bean
from any JSP page in the same application. It has
wider scope than session.
3. class: instantiates the specified bean class (i.e. creates
an object of the bean class) but it must have
no-argument constructor and must not be abstract.
jsp:setProperty and jsp:getProperty action
tags
The jsp:setProperty action tag sets a property value or values
in a bean using the setter method.
Syntax of jsp:setProperty action tag
<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" value="{ string | <%= expression
%>}" />
Example of jsp:setProperty action tag if you have to set
all the values of incoming request in the bean
<jsp:setProperty name="bean" property="*" />
Example of jsp:setProperty action tag if you have to set
a specific value in the property
<jsp:setProperty name="bean" property="username" value="
Kumar" />
jsp:getProperty action tag
The jsp:getProperty action tag returns the value of the
property.
Syntax of jsp:getProperty action tag
<jsp:getProperty name="instanceOfBean" property="pr
opertyName" />
Simple example of jsp:getProperty action tag
<jsp:getProperty name="obj" property="name" />
Example for using java bean in JSP
In this example there are 3 pages:
index.html for input of values
welocme.jsp file that sets the incoming
values to the bean object and prints the one
value
User.java bean class that have setter and
getter methods
index.html
<html><body>
<form action="welcome.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="pass
word"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form> </body></html>
welcome.jsp
<jsp:useBean id="u" class="org.sssit.User"></js
p:useBean>
<jsp:setProperty property="*" name="u"/>
<jsp:getProperty property="name" name="u"/>
<br>
<jsp:getProperty property="password" name="u
"/><br>
<jsp:getProperty property="email" name="u" />
<br>
<%
U.storedata();
%>
User.java
package org.sssit;
public class User {
private String name, password, email;
//setters and getters
User()
{
}
Void setName(string name)
{
this.name=name;
}
String getName()
{
return name;
}
----
-----
Void storedata()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orclit","scott","tiger");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?)");
ps.setString(1,name);
ps.setString(2,password);
ps.setString(3,email);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}
catch (Exception e2) {System.out.println(e2);}
con.close();
}
}
Alternative way:
<jsp:useBean id="u"
scope=”page” class="User"></jsp:useBean>
<jsp:setProperty property="name"
name="u"
value=<%=request.getparameter(‘name’)/>
<jsp:setProperty property="password"
name="u"
value=<%=request.getparameter(‘password’)/>
<jsp:setProperty property="email"
name="u"
value=<%=request.getparameter(‘email’)/>
<%
U.storedata();
%>
Storing bean in request scope:
<jsp:useBean id="u"
scope=”request” class="User"></jsp:useBean>
<jsp:setProperty property="name" name="u"
value=<%=request.getparameter(‘name’)/>
<jsp:setProperty property="password"
name="u"
value=<%=request.getparameter(‘password’)/>
<jsp:setProperty property="email" name="u"
value=<%=request.getparameter(‘email’)/>
<jsp:include page=”two.jsp” />
two.jsp
<%
U.storedata();
%>
Storing bean in session scope:
one.jsp
<jsp:useBean id="u"
scope=”session” class="User"></jsp:useBean>
<jsp:setProperty property="name" name="u"
value=<%=request.getparameter(‘name’)/>
<jsp:setProperty property="password"
name="u"
value=<%=request.getparameter(‘password’)/>
<jsp:setProperty property="email" name="u"
value=<%=request.getparameter(‘email’)/>
<html>
<body>
<form method=”get” action=”two.jsp”>
<input type=”submit” value=”submit”>
</body>
</html>
two.jsp
<%
U.storedata();
%>
Example web application to insert Registration form
data into database
webapp
WEB-INF
classes
lib
web.xml
In this example, we have created the three pages.
o register.html
o Register.jsp
o web.xml
register.html
This page, get input from the user using text fields and
combobox. The information entered by the user is forwarded to
Register servlet, which is responsible to store the data into the
database.
<html>
<body>
<form action="register.jsp" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><
br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Register.jsp
<%@ page import=”java.sql.*”; %>
<%
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orclit","scott","tiger");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}
catch (Exception e2) {System.out.println(e2);}
con.close();
%>