Professional Documents
Culture Documents
JDBC & JSP Notes for Recording
JDBC & JSP Notes for Recording
JDBC & JSP Notes for Recording
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
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.
o Create connection
o Create statement
o Execute queries
o Close connection
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(
2));
}
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?
Method Description
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();
}}
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)
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.
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.
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.*;
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...");
con.close();
}
web.xml file
<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">
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;
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"admin");
Statement st=con.createStatement();
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>
login.html
validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.*;
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;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
out.close();
}
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>
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>
scriptlet tag
expression tag
declaration tag
JSP scriptlet tag
<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>
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 jspscriptlet tag can only The jsp declaration tag can
declare variables not declare both variables as well
methods. as methods.
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
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
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);
%>
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);
%>
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>
page
request
session
application
In JSP, page scope is the default scope.
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
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.
extends
buffer
language
index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
isErrorPage
myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body> </html>
Code Reusability
Syntax of include directive
</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
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.
</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
Java Bean
A Java Bean is a java class that should follow following
conventions:
//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());
}
}
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
<%
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();
%>
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
<%
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();
%>