JDBC & JSP Notes For Recording
JDBC & JSP Notes For Recording
Connection interface
Commonly used methods of Connection interface:
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
1) Register the driver class
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","or
acle");
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","or
acle");
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.getCo
lumnCount());
System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st col
umn: "+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 dr
method calls into the ODBC function calls. This is now discouraged because of thin 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 c
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 is
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
webapp
register.html
WEB-INF
classes
registeruser.class
lib
web.xml
In this example, we have created the three pages.
o register.html
o registeruser.java
o web.xml
Tis page, allows 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.
register.html
<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>
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.
registeruser.java
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>registeruser</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
Import java.io.*;
Import java.sql.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:XE","system","admin");
Statement st=con.createStatement();
ResultSet rs=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> ServletDatabaseConnect</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDBConnect</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
</web-app>
create table userreg(name varchar2(40),pass var
char2(40));
<html>
<body><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> </body></html>
Web.xml
<web-app>
<servlet>
<servlet-name>Servletauthentication</servlet-name>
<servlet-class>validate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Servletauthentication </servlet-name>
<url-pattern>/authenticate</url-pattern>
</servlet-mapping></web-app>
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","or
acle");
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”);
}
}
}
(0R)
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,n);
ps.setString(2,p);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
} }
Write a servlet which welcome the user by
their name.
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
HttpServlet {
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 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>
<html>
<body>
<%= "welcome to jsp" %>
</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>
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
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
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
info
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
</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:
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.
//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());
}
}
opertyName" />
Simple example of jsp:getProperty action tag
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">
<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();
%>