UNIT III
SERVER SIDE PROGRAMMING
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST
actions- Session Handling- Understanding Cookies- DATABASE
CONNECTIVITY: JDBC
Servlets
Servlets are simple java programs that run on the servers
Servlet technology is robust and scalable because of java language.
Servlets are most commonly used with HTTP hence sometimes servlets are also
called “HTTP Servlets”
Servlets makes use of java standard extension packages [Link] and
[Link]
Working of Servlets or Architecture of Servlets
Before learning the actual servlet programming it is very important to understand
how servlet works.
Execution of Servlets basically involves six basic steps:
1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the webserver.
1 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
6. The web server sends the response back to the client and the client browser displays it
on the screen.
When we write a servlet program, it is necessary to –
i) either implement Servlet interface or
ii) extend a class that implements Servlet interface.
While implementing Servlet interface we must include [Link] package. Hence
the first line in out servlet program must be import [Link].*;
GenericServlet class is a predefined implementation of Servlet interface. Hence we
can extend GenericServlet class in our servlet program. Similarly, the
HttpServlet class is a child class of GenericServlet class, hence we can extend
this class as well while writing the servlet program.
The servlet gets the request from the client for some service. The servlet then processes the
request and sends the response back to the client. In order to handle these issues
HttpServletRequest and HttpServletResponse are used in servlet program.
These requests are handled with the help of some methods that are popularly known as
methods of HttpServlet. These methods are as follows
The doGet and doPost methods
The doGet method requests the data from the source.
The doPost method submits the processed data to the source.
The protocol of doGet method is as follows
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
2 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
The ServletException and IOException are thrown to handle the Servlet problems gracefully.
The HttpServletRequest request: contain the client request made by client.
The HttpServletResponse response : contains the response made by servlet back to the client.
The protocol of doPost method is same as doGet method. It is as follows –
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
The GET request is more efficient than the POST request.
The GET request is less secure than the POST request.
CGI
• Before Servlet, CGI (Common Gateway Interface) scripting language was common as a
server-side programming language.
• CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
3 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
Servlet Life Cycle
In the life cycle of servlet there are three important methods. These methods are
i) init()
ii) service()
iii) destroy()
4 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
init()
The life cycle of servlet begins here
This method is called only once
It is not called again for each user request
The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
Syntax:
public void init() throws ServletException {
// Initialization code...
}
service()
Handles all the request sent by the client
It is called only after the servlet is initialized
It is the main method to perform the actual task
This service() method then involves doGet(), doPost() etc. methods.
Syntax:
public void service (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
doGet()
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
doPost()
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
5 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
destroy()
The end of the servlet life is indicated by this method
It is called only once
All the resources initialized for servicing the request are cleaned up
Syntax:
public void destroy {
// Servlet code
}
Example program for Servlet Life Cycle
// Import required java libraries
import [Link].*;
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
[Link]("text/html");
// Actual logic goes here.
PrintWriter out = [Link]();
[Link]("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
Creation of Servlets
The servlet can be created by three ways:
1. By implementing Servlet interface
2. By inheriting GenericServlet class
3. By inheriting HttpServlet class
6 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
By implementing Servlet interface
Servlet interface provides common behaviour to all the servlets. Servlet interface needs to be
implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods (init, service and destroy) that are used to initialize the
servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void service(ServletRequest provides response for the incoming request. It
request,ServletResponse response) is invoked at each request by the web
container.
public void destroy() is invoked only once and indicates that servlet
is being destroyed.
public ServletConfig returns the object of ServletConfig.
getServletConfig()
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
GenericServlet class
It provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol independent.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when
user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates
that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
7 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is
no need to call [Link](config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the
given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined
in the [Link] file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the
servlet log file and a stack trace.
HttpServlet Class
HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the
request to the protected service method by converting the request and response object
into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles
the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
8 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
6. protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles
the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse
res) handles the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
Form GET and POST actions
In HTTP-GET request the doGet method is used.
In HTTP-POST request the doPost method is used.
When the user submit the request using doGet method then the URL string
displays the request submitted by the user.
The GET method sends user information along with ? symbol called query
string. For instance
[Link] = aaaa&age = 20
When doPost method is used, then the URL string does not show the
submitted contents.
Post method is the most reliable method of sending user information to the
server from HTML form. Servlet handles this request using doPost method.
Difference between GET and POST
GET POST
Using GET request limited amount Using POST large amount of
of information can be sent.
information can be sent
GET request is not secured as This is a secured request
information is visible in URL
This request is can be bookmarked. This request cannot be bookmarked.
This request is more efficient. This request is less efficient
How does servlet read form data?
Servlet makes use of following three methods to read the data entered by the user on the
HTML form
9 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
1. getParameter() − You call [Link]() method to get the value of a form
parameter.
2. getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
3. getParameterNames() − Call this method if you want a complete list of all parameters
in the current request.
Example for getParameter()
HTML Servlet code
<!DOCTYPE html> import [Link];
<html> import [Link];
<head> import [Link];
<meta http-equiv="Content-Type" import [Link];
content="text/html; charset=ISO-8859-1"> import [Link];
<title>Input Form</title> import [Link];
</head>
<body> public class ServletGetParameter extends HttpServlet{
<form action="parameter" method="get"> public void doGet(HttpServletRequest request,
<table> HttpServletResponse response) throws IOException, ServletException
<tr> {
<td>Enter Your Name : </td> [Link]("text/html");
<td><input type="text" name="nm"/></td> PrintWriter out = [Link]();
</tr> String name = [Link]("nm");
<tr> [Link]("Welcome, "+name);
<td>Ente your password :</td> }
<td><input type="password"
name="psw"/></td> }
</tr>
<tr>
<td></td>
<td><input type="submit"
value="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
OUTPUT
Example for getParameterValues()
HTML Servlet code
<!DOCTYPE html> import [Link];
10 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
<html> import [Link];
<head>
<title>Get parameter value</title>
</head> import [Link];
<body> import [Link];
<h2 align="center"><font import [Link];
color="green">HOBBIES</font></h2> import [Link];
<form action="Onget" method="post">
<table align="center"> public class GetParameterValuesExample extends
<tr> HttpServlet
<td><font>Playing Cricket</font></td> {
<td><input type="checkbox" name="hobbies" protected void doPost(HttpServletRequest
value="Playing Cricket"></td> request,HttpServletResponse response)throws
</tr> ServletException,IOException
<tr> {
<td><font>Watching Movies</font></td> PrintWriter printWriter=[Link]();
<td><input type="checkbox" name="hobbies" [Link]("text/html");
value="Watching Movies"></td>
</tr> String[] values=[Link]("hobbies");
[Link]("Selected Values:-");
<tr> for(int i=0; i<[Link]; i++)
<td><font>Listening Songs</font></td> {
<td><input type="checkbox" name="hobbies" [Link]("<li>"+values[i]+"</li>");
value="Listening Songs"></td> }
</tr> [Link]();
}
<tr> }
<td><font>Playing Basketball</font></td>
<td><input type="checkbox" name="hobbies"
value="Playing Basketball"></td>
</tr>
<tr>
<td></td>
<td> <input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Output
Session Tracking Techniques
11 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Session tracking techniques is a conversation between the server and a client.
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of a user. It is also known
as session management in servlet.
Session tacking is a mechanism by which we can keep track of previous sessions
between server and the browser.
There are two types of protocols which are given below:
o Stateful
Part of data exchanged between client and server and these protocols
always keep track of communication sessions.
o Stateless
Neither client nor server keeps track of the state of communication
session. Http is a stateless session protocol in which each request is
independent of the previous request.
The session tracking techniques can be classified in the following 4 types
o Cookies
o Hidden form fields
o URL rewriting
o Http Session
Cookies
o A cookie is a small piece of information that is persisted between the
multiple client requests.
o A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version number.
o Types of Cookie:
Persistent cookie
It is valid for multiple session. It is removed only if user
logout or signed out.
Non-Persistent cookie
It is valid for single session only. It is removed each time when
user closes the browser.
o Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
o Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Cookie class
o [Link] class provides the functionality of using cookies.
o Constructor of Cookie class
12 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
o Useful Methods of Cookie class
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
o How to create Cookie?
Cookie ck=new Cookie("user","xx");//creating cookie object
[Link](ck);//adding cookie in the response
o Delete cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
[Link](0);//changing the maximum age to 0 seconds
[Link](ck);//adding cookie in the response
o How to get Cookies?
1. Cookie ck[]=[Link]();
2. for(int i=0;i<[Link];i++){
3. [Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name a
nd value of cookie
4. }
Simple example of Servlet Cookies
[Link]
<form action="servlet1" method="post">
13 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
[Link](ck);//adding cookie in the response
//creating submit button
[Link]("<form action='servlet2'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");
[Link]();
}catch(Exception e){[Link](e);}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
14 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
try{
[Link]("text/html");
PrintWriter out = [Link]();
Cookie ck[]=[Link]();
[Link]("Hello "+ck[0].getValue());
[Link]();
}catch(Exception e){[Link](e);}
}
}
Output
15 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
16 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
2) Hidden Form Field
o In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state
of an user.
o In such case, we store the information in the hidden field and get it from another servlet.
Advantage of Hidden Form Field
1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Only textual information can be used.
17 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Example:
<input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
Coding
[Link]
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
[Link]("text/html");
PrintWriter out = [Link]();
18 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
String n=[Link]("userName");
[Link]("Welcome "+n);
//creating form that have invisible textfield
[Link]("<form action='servlet2'>");
[Link]("<input type='hidden' name='uname' value='"+n+"'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");
[Link]();
}catch(Exception e){[Link](e);}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
[Link]("text/html");
PrintWriter out = [Link]();
//Getting the value from the hidden field
String n=[Link]("uname");
[Link]("Hello "+n);
[Link]();
}catch(Exception e){[Link](e);}
}
}
19 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
3) URL Rewriting
o We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&..
o A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand (&).
Example coding
[Link]
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
20 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
//appending the username in the query string
[Link]("<a href='servlet2?uname="+n+"'>visit</a>");
[Link]();
}catch(Exception e){[Link](e);}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
[Link]("text/html");
PrintWriter out = [Link]();
//getting value from the query string
String n=[Link]("uname");
[Link]("Hello "+n);
[Link]();
}catch(Exception e){[Link](e);}
}
}
21 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
4. HttpSession interface
o In such case, container creates a session id for each user.
o The container uses this id to identify the particular [Link] object of HttpSession can
be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
22 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to
it.
Example Program
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
[Link]("text/html");
HttpSession session = [Link]();
String heading;
Integer accessCount =(Integer)[Link]("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
}
else {
heading = "Welcome Back";
accessCount = new Integer([Link]() + 1);
}
[Link]("accessCount", accessCount);
PrintWriter out = [Link]();
String title = "Session Tracking Example";
[Link]( "<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + [Link]() + "\n" +
23 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" +
new Date([Link]()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" +
new Date([Link]()) + "\n" +
"<TR>\n" +
" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +
"</TABLE>\n" +
"</CENTER></BODY></HTML>");
}
}
Output:
24 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
JDBC Connectivity
JDBC stands for Java Database Connectivity. JDBC is a SQL level API that allows to execute
SQL statements and retrieve result if any.
JDBC Driver
o JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
JDBC-ODBC bridge driver
o The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.
25 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
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 calls into native calls of the database API. It is not written entirely in java.
26 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
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.
27 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
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 is known as thin driver. It is fully written in Java language.
28 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
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.
JDBC basics
All the interfaces and classes necessary to implement JDBC remains in a package
called [Link].*;
This API has a single class called DriverManager and set of interfaces like
o Statement
o Connection
o ResultSet
o PreparedStatement
29 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
Steps to Perform JDBC Connection
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
o public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
o [Link]("[Link]");
RDBMS JDBC driver name URL format
jdbc:mysql://hostname/ databaseName
MySQL [Link]
jdbc:oracle:thin:@hostname:port
ORACLE [Link]
Number:databaseName
30 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
jdbc:db2:hostname:port
DB2 [Link].DB2Driver
Number/databaseName
jdbc:sybase:Tds:hostname: port
Sybase [Link]
Number/databaseName
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=[Link](
"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=[Link]();
4) Execute the query
The executeQuery() method of Statement interface is used to execute 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=[Link]("select * from emp");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
31 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
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
[Link]();
JDBC - Statements, PreparedStatement and CallableStatement
Once a connection is obtained we can interact with the database. The JDBC
Statement, CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable to send SQL or PL/SQL commands and receive data from the
database. They also define methods that help bridge data type differences between
Java and SQL data types used in a database
Interfaces Recommended Use
Use for general-purpose access to the database. Useful when
Statement using static SQL statements at runtime. The Statement interface
cannot accept parameters.
Used when the SQL statements are to be executed many times.
PreparedStatement The PreparedStatement interface accepts input parameters at
runtime.
Use when database stored procedures are to be executed. The
CallableStatement CallableStatement interface can also accept runtime input
parameters.
Create a Statement Object
A Statement object is used to send queries and commands to the database. It is
created from the Connection using createStatement.
Statement statement = [Link]();
Most, but not all, database drivers permit multiple concurrent Statement objects
to be open on the same connection.
Execute a Query or Update
The Statement object can be uses to send SQL queries by using the executeQuery
32 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
method, which returns an object of type ResultSet.
Example: String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = [Link](query);
The methods in the Statement class are
Methods Description
executeQuery Executes an SQL query and returns the data in a
ResultSet. The ResultSet may be empty, but never null.
executeUpdate Used for UPDATE, INSERT, or DELETE commands.
Returns the number of rows affected, which could be
zero. Also provides support for Data Definition Language
(DDL) commands, for example, CREATE TABLE,
DROP TABLE, and ALTERTABLE.
executeBatch Executes a group of commands as a unit, returning an
array with the update counts for each command. Use
addBatch to add a command to the batch group.
setQueryTimeout Specifies the amount of time a driver waits for the result
before throwing a SQLException.
getMaxRows/setMaxRows Determines the number of rows a ResultSet may contain.
Excess rows are silently dropped. The default is zero for
no limit.
Process the Results
ResultSet Interface
ResultSet is the representation of the Query result returning one row at a time. Its is a
replicate of database
It holds a number of methods to retrieve the records detail as well as the field details.
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
Methods Description
next() Used to move from row to row
first() Used to move to the 1st record of the database
33 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
last() Used to move to the last record in the database
previous() Used to move to the first record in the database
findColumn Returns the index in the ResultSet corresponding to the specified
column name.
getRow Returns the current row number, with the first row starting at 1
(JDBC 2.0).
relative/absolute The relative method moves the cursor a relative number of rows,
either positive (up) or negative (down). The absolute method
moves the cursor to the given row number. If the absolute value
is negative, the cursor is positioned relative to the end of the
ResultSet (JDBC 2.0).
The PreparedStatement Objects
The PreparedStatement interface extends the Statement interface in which the
SQL statements are precompiled by the database for faster execution
? character is used as a placeholder for values to be submitted later
Example:
PreparedStatement pstmt = [Link](insert into table1 values(?,?,?)”);
[Link](1,20);
‘The CallableStatement Objects
A Connection object creates the CallableStatement object which would be used
to execute a call to a database stored procedure.
Simple JDBC connection in a servlet
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
34 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
import [Link];
import [Link];
public class JDBCServlet extends HttpServlet
{
public void doGet(HttpServletRequest inRequest,HttpServletResponse outResponse)
throws ServletException,IOException
{
PrintWriter out = null;
Connection connection = null;
Statement statement;
ResultSet rs;
try {
[Link]("[Link]");
connection =[Link]("jdbc:mysql://localhost/products");
statement = [Link]();
[Link]("test/html");
out = [Link]();
rs = [Link]("SELECT ID, title, price FROM product");
[Link]("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
[Link]("<BODY>");
[Link]("<UL>");
while ([Link]()) {
[Link]("<LI>" + [Link]("ID") + " " + [Link]("title")+ " "
+[Link]("price"));
}
[Link]("</UL>");
[Link]("</BODY></HTML>");
35 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
}
catch (ClassNotFoundException e)
{
[Link]("Driver Error");
} catch (SQLException e)
{
[Link]("SQLException: " + [Link]());
}
}
public void doPost(HttpServletRequest inRequest,HttpServletResponse outResponse) throws
ServletException, IOException
{
doGet(inRequest, outResponse);
}
}
OUTPUT
ID Title Price
56 Soap 40
98 Shampoo 15
Code to insert a data into the database
Create a "Registration" table
SQL> create table registration (Name varchar2(20), password varchar2(10), email
varchar2(20), mobile number, dob varchar2(20), gender varchar2(6), country varchar2 (10));
36 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
[Link]
<!doctype html>
<body>
<form action="servlet/Register" method="post">
<fieldset style="width:20%; background-color:#ccffeb">
<h2 align="center">Registration form</h2><hr>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="userName" required /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userPass" required /></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" name="userEmail" required /></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="userMobile" required/></td>
</tr>
<tr>
<td>Date of Birth</td>
<td><input type="date" name="userDOB" required/></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value="male" checked> Male
<input type="radio" name="gender" value="female"> Female </td></tr>
<tr>
<td>Country</td>
<td><select name="userCountry" style="width:130px">
<option>Select a country</option>
<option>India</option>
<option>America</option>
<option>England</option>
<option>other</option></select>
</td>
</tr>
<tr>
37 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
<td><input type="reset" value="Reset"/></td>
<td><input type="submit" value="Register"/></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
[Link]
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
public class Register extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String name = [Link]("userName");
String pwd = [Link]("userPass");
String email = [Link]("userEmail");
int mobile = [Link]([Link]("userMobile"));
String dob = [Link]("userDOB");
String gender = [Link]("gender");
String country =[Link]("userCountry");
try
{
//load the driver
38 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
[Link]("[Link]");
//create connection object
Connection
con=[Link]( "jdbc:oracle:thin:@localhost:1521:xe","local","test");
// create the prepared statement object
PreparedStatement ps=[Link]("insert into registration
values(?,?,?,?,?,?,?)");
[Link](1,name);
[Link](2,pwd);
[Link](3,email);
[Link](4, mobile);
[Link](5,dob);
[Link](6,gender);
[Link](7,country);
int i = [Link]();
if(i>0)
[Link]("You are successfully registered...");
}
catch (Exception ex)
{
[Link]();
}
[Link]();
}
}
JDBC INSERT RECORD EXAMPLE
Create table:
CREATE TABLE customer (
39 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
'First Name' varchar(30) ,
'Last Name' varchar(30) ,
'E-Mail' varchar(45) ,
'City' varchar(30) ,
'password' varchar(30) NOT NULL,
PRIMARY KEY ('password')
)
INSERT RECORD INTO THE DB
insert into customer () values ('Jonty','Magic','jonty@[Link]','Pune','123456');
insert into customer () values ('Java','Sun','java@[Link]','New York','456');
insert into customer () values ('Jesse','lool','jesse@[Link]','Jamaica','23456');
insert into customer () values ('Cameroon','Black','cameroon@[Link]','Sydney','34');
SERVLET CODE TO DELETE DATA FROM DATABASE
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/DeleteJdbcQueryServlet")
public class DeleteJdbcQueryServlet extends HttpServlet {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
static String query = null;
String url = null;
String username = null;
String password = null;
public void init(ServletConfig config) throws ServletException {
40 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
url = "jdbc:mysql://localhost:3306/javaee";
username = "root";
password = "root";
try {
[Link]("[Link]").newInstance();
connection = [Link](url, username , password);
}
catch (Exception e) {
[Link]();
}
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws
ServletException, IOException {
doPost(request, response);
protected void doPost(HttpServletRequest request, HttpServletResponse response ) throws
ServletException, IOException {
query = "delete from customer where First_Name='Jonty';";
executeQuery(query);
query = "delete from customer where First_Name='Java';";
executeQuery(query);
}
private void executeQuery(String query) {
try {
statement = [Link]();
[Link](query);
}
catch (SQLException e) {
[Link]();
41 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
}
}
@Override
public void destroy() {
try {
[Link]();
[Link]();
}
catch (SQLException e) {
[Link]();
}
Output after Insert query –
Output after Delete query –
Update Database using JDBC
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
42 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/DeleteJdbcQueryServlet")
public class DeleteJdbcQueryServlet extends HttpServlet {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
static String query = null;
String url = null;
String username = null;
String password = null;
public void init(ServletConfig config) throws ServletException {
url = "jdbc:mysql://localhost:3306/javaee";
username = "root";
password = "root";
try {
[Link]("[Link]").newInstance();
connection = [Link](url, username , password);
}
catch (Exception e) {
[Link]();
}
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response ) throws
ServletException, IOException {
query = "delete from customer where First_Name='Jonty';";
43 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
executeQuery(query);
query = "delete from customer where First_Name='Java';";
executeQuery(query);
}
private void executeQuery(String query) {
try {
statement = [Link]();
[Link](query);
}
catch (SQLException e) {
[Link]();
}
}
@Override
public void destroy() {
try {
[Link]();
[Link]();
}
catch (SQLException e) {
[Link]();
}
44 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE
---------------------------------------------------------------------------------------------------------------
45 UNIT III PREPARED BY : [Link], AP (Sr. G.)/CSE