0% found this document useful (0 votes)
23 views79 pages

6 Servlets

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views79 pages

6 Servlets

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

SERVLETS

Introduction
Java Servlets are programs that run on a Web or
Application server and act as a middle layer between a
requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
Using Servlets, we can collect input from users through
web page forms, present records from a database or another
source, and create web pages dynamically.
Properties of Servlets :
Servlets work on the server-side.
Servlets capable of handling complex request obtained from
web server.
Web application
A web application is an application accessible from the
web.
A web application is composed of web components like
Servlet, JSP, Filter, etc. and other elements such as
HTML, CSS, and JavaScript.
The web components typically execute in Web Server and
respond to the HTTP request.
Servlets
Execution of Servlets :
Execution of Servlets involves the six basic steps:
 The clients send the request to the web server.
 The web server receives the request.
 The web server passes the request to the corresponding servlet.
 The servlet processes the request and generate the response in the
form of output.
 The servlet send the response back to the web server.
 The web server sends the response back to the client and the client
browser displays it on the screen.
Architecture of Servlet
CGI (Common Gateway Interface)
CGI is actually an external application which is written
by using any of the programming languages like C or C+
+.
This is responsible for processing client requests and
generating dynamic content.
Disadvantages of CGI
There are many problems in CGI technology:
 If the number of clients increases, it takes more time for sending the
response.
 For each request, it starts a process, and the web server is limited to
start processes.
 It uses platform dependent language e.g. C, C++, perl.
How CGI works
Advantages of Servlet
Better performance: because it creates a thread for
each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
Secure: because it uses java language.
Servlet
Life Cycle of a Servlet
A servlet life cycle can be defined as the entire process
from its creation till the destruction. The following are the
paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's
request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector
of the JVM.
Architecture Diagram
Architecture Diagram
First the HTTP requests coming to the server are delegated
to the servlet container.
The servlet container loads the servlet before invoking the
service() method.
Then the servlet container handles multiple requests by
spawning multiple threads, each thread executing the
service() method of a single instance of the servlet.
Life cycle methods
The init() Method
The init method is called only once.
It is called only when the servlet is created, and not called
for any user requests afterwards.
So, it is used for one-time initializations, just as with the
init method of applets.
The init() method simply creates or loads some data that
will be used throughout the life of the servlet.
public void init() throws ServletException { // Initialization
code... }
Life cycle methods
The service() Method
The service() method is the main method to perform the actual
task.
The servlet container (i.e. web server) calls the service() method
to handle requests coming from the client( browsers) and to
write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
The service() method checks the HTTP request type (GET,
POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException { }
Life cycle methods
The doGet() and doPost() are most frequently used methods
with in each service request.
The doGet() Method
A GET request results from a normal request for a URL or
from an HTML form that has no METHOD specified and it
should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The doPost() Method
A POST request results from an HTML form that
specifically lists POST as the METHOD and it should be
handled by doPost() method.
Life cycle methods
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The destroy() Method
The destroy() method is called only once at the end of the
life cycle of a servlet.
This method gives the servlet a chance to close database
connections, halt background threads, write cookie lists
or hit counts to disk, and perform other such cleanup
activities.
public void destroy() { // Finalization code... }
Java Servlet classes
Servlets are Java classes which service HTTP requests and
implement the javax.servlet.Servlet interface.
 Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed
to handle HTTP requests.
GET and POST
Two common methods for the request-response between a
server and client are:
GET- It requests the data from a specified resource
POST- It submits the processed data to a specified resource
Anatomy of Get Request
GET /RegisterDao.jsp?name1=value1&name2=value2
The GET method sends the encoded user information
appended to the page request. The page and the encoded
information are separated by the ?
Never use the GET method if you have password or other
sensitive information to pass to the server.
Anatomy of Post Request
A generally more reliable method of passing information to a
backend program is the POST method.
This packages the information in exactly the same way as
GET method, but instead of sending it as a text string after
a ? (question mark) in the URL it sends it as a separate
message.
This message comes to the backend program in the form of
the standard input which you can parse and use for your
processing.
POST/RegisterDao.jsp HTTP/1.1

Host: www. javatpoint.com


name1=value1&name2=value2
Reading Form Data using Servlet
getParameter() − You call request.getParameter() method
to get the value of a form parameter.
getParameterValues() − Call this method if the
parameter appears more than once and returns multiple
values, for example checkbox.
getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request.
protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request.
GET POST

1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in
sent in header. body.

2) Get request is not secured because data Post request is secured because data is not
is exposed in URL bar. exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means


second request will be ignored until Post request is non-idempotent.
response of first request is delivered

5) Get request is more efficient and used Post request is less efficient and used less
more than Post. than get.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>Welcome</body></html>”);
out.close();
}
Deployment container – gets the
information about the servlet to be invoked
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
GET Method Example Using Form
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet { public void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println("<html>\n" + "<head><title>" + title + "</title></head>\
n“ + "<h1 align = \"center\">" + title + "</h1>\n" + "<ul>\n" + "
<li><b>First Name</b>: " + request.getParameter("first_name") +
"\n" + " <li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n" + "</body>"
+ "</html>" ); } }
HTML Code
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body> irst Name: Last Name:
</html>
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>

OUTPUT:
Using GET Method to Read Form Data
 First Name: ARUN
 Last Name: KUMAR
POST Method Example Using Form
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n“ + "<h1
align = \"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " +
request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n" + "</body>" "</html>" ); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
}
HTML Code
<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Passing Checkbox Data to Servlet Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckBox extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Checkbox Data";
out.println("<html>\n" + "<head><title>" + title + "</title></head>\n" + "<h1 align = \"center\">" + title
+ "</h1>\n" + "<ul>\n" + " <li><b>
Maths Flag : </b>: " + request.getParameter("maths") + "\n" + " <li><b>
Physics Flag: </b>: " + request.getParameter("physics") + "\n" + " <li><b>
Chemistry Flag: </b>: " + request.getParameter("chemistry") + "\n" + "</ul>\n" + "</body>"
"</html>" );
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
} }
HTML Code
<html>
<body>
<form action = "CheckBox" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>

OUTPUT:
Reading Checkbox Data
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
Session Tracking in Servlets
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state
using session tracking techniques. Each time user requests
to the server, server treats the request as the new request.
So we need to maintain the state of an user to recognize to
particular user.
HTTP is stateless that means each request is considered as
the new request. It is shown in the figure given below:
Why use Session Tracking?
To recognize the user It is used
to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted
between the multiple client requests.
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.
In cookies technique, we add cookie with response from
the servlet.
So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added
with request by default. Thus, we recognize the user as the
old user.
Types of Cookie
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
 Non-persistent cookie
It is valid for single session only. It is removed each time when user
closes the browser.
 Persistent cookie
It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.

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
javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for
cookies.
Useful Methods of CookieDescription
Method class
public void setMaxAge(int Sets the maximum age of the cookie in
expiry) 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 changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
Cookies
How to create Cookie?
Cookie ck=new Cookie("user","sonoo jaiswal");//
creating cookie object
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){

out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing
name and value of cookie
}
In this example, we are storing the name of the user in the
cookie object and accessing it in another servlet. As we
know well that session corresponds to the particular user.
So if you access it from too many browsers with different
values, you will get the different value.
index.html

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse respons
e){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Hidden Form Field
In case of Hidden Form Field a hidden (invisible)
textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden field
and get it from another servlet. This approach is better if we
have to submit form in all the pages and we don't want to
depend on the browser.
<input type="hidden" name="uname" value="Vimal Jaiswal"
>
Here, uname is the hidden field name and Vimal Jaiswal is
the hidden field value.
Hidden Form Field
Real application of hidden form field
It is widely used in comment form of a website. In
such case, we store page id or page name in the hidden
field so that each page can be uniquely identified.
Advantage of Hidden Form Field
It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
It is maintained at server side.
Extra form submission is required on each pages.
Only textual information can be used.
Example of using Hidden Form Field

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response
)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
URL Rewriting
In URL rewriting, we append a token or identifier to the
URL of the next Servlet or the next resource. We can send
parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign,
a parameter name/value pair is separated from another
parameter using the ampersand(&).
 When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server.
From a Servlet, we can use getParameter() method to
obtain a parameter value.
Example
Advantage of URL Rewriting
It will always work whether cookie is disabled or not
(browser independent).
Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


It will work only with links.
It can send Only textual information.
Example of using URL Rewriting
In this example, we are maintaning the state of the user
using link. For this purpose, we are appending the name of
the user in the query string and getting the value from the
query string in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
HttpSession interface
In such case, container creates a session id for each user.
The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two tasks:
 bind objects
 view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
HttpSession Object
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
 public HttpSession getSession():
Returns the current session associated with this request, or if the request does not
have a session, creates one.
 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
 public String getId():Returns a string containing the unique identifier value.
 public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
 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.
 public void invalidate():Invalidates this session then unbinds any objects bound
to it.
Example of using HttpSession
In this example, we are setting the attribute in the session scope in
one servlet and getting that value from the session scope in another
servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
JDBC
JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent connectivity
between the Java programming language and a wide range
of databases.
The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with
database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
JDBC Architecture
The JDBC API supports both two-tier and three-tier
processing models for database access but in general, JDBC
Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager
connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific
drivers to provide transparent connectivity to heterogeneous
databases.
The JDBC driver manager ensures that the correct driver is
used to access each data source. The driver manager is
capable of supporting multiple concurrent drivers connected
to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location
of the driver manager with respect to the JDBC drivers and the
Java application −
Common JDBC Components
The JDBC API provides the following interfaces and classes −
 DriverManager: This class manages a list of database drivers.
Matches connection requests from the java application with the
proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used
to establish a database Connection.
 Driver: This interface handles the communications with the database
server. You will interact directly with Driver objects very rarely.
Instead, you use DriverManager objects, which manages objects of
this type. It also abstracts the details associated with working with
Driver objects.
 Connection: This interface with all methods for contacting a
database. The connection object represents communication context,
i.e., all communication with database is through connection object
only.
Common JDBC Components
Statement: You use objects created from this interface to
submit the SQL statements to the database. Some derived
interfaces accept parameters in addition to executing
stored procedures.
ResultSet: These objects hold data retrieved from a
database after you execute an SQL query using Statement
objects. It acts as an iterator to allow you to move through
its data.
SQLException: This class handles any errors that occur
in a database application.
JDBC Drivers Types
JDBC driver implementations vary because of the wide
variety of operating systems and hardware platforms in
which Java operates.
Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below

Type 1: JDBC-ODBC Bridge Driver
Type 2: JDBC-Native API
Type 3: JDBC-Net pure Java
Type 4: 100% Pure Java
Type 1: JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC
drivers installed on each client machine. Using ODBC,
requires configuring on your system a Data Source Name
(DSN) that represents the target database.
When Java first came out, this was a useful driver because
most databases only supported ODBC access but now this
type of driver is recommended only for experimental use
or when no other alternative is available.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into
native C/C++ API calls, which are unique to the database.
These drivers are typically provided by the database
vendors and used in the same manner as the JDBC-ODBC
Bridge. The vendor-specific driver must be installed on
each client machine.
If we change the Database, we have to change the native
API, as it is specific to a database and they are mostly
obsolete now, but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's
overhead.
Type 3: JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access
databases. The JDBC clients use standard network
sockets to communicate with a middleware application
server. The socket information is then translated by the
middleware application server into the call format
required by the DBMS, and forwarded to the database
server.
This kind of driver is extremely flexible, since it requires
no code installed on the client and a single driver can
actually provide access to multiple databases.
You can think of the application server as a JDBC
"proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the
application server's configuration in order to effectively
use this driver type.
Your application server might use a Type 1, 2, or 4 driver
to communicate with the database, understanding the
nuances will prove helpful.
Type 4: 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates
directly with the vendor's database through socket
connection. This is the highest performance driver
available for the database and is usually provided by the
vendor itself.
This kind of driver is extremely flexible, you don't need to
install special software on the client or server. Further,
these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of
the proprietary nature of their network protocols, database
vendors usually supply type 4 drivers.
Type 4: 100% Pure Java
Which Driver should be Used?
If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or
type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level
driver, and is typically used for development and testing
purposes only.
Accessing a Database
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
static final String USER = "root"; static final String PASS =
"password";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
out.println("<html>\n" + "<head><title>" + title +
"</title></head>\n" + "<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection Connection conn =
DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql; sql = "SELECT id, first, last, age FROM
Employees"; ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next())
{ //Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values out.println("ID: " + id + "<br>"); out.println(", Age: " + age
+ "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>"); } out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}
}

You might also like