0% found this document useful (0 votes)
21 views31 pages

Ip-Unit Iii Notes

nil

Uploaded by

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

Ip-Unit Iii Notes

nil

Uploaded by

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

UNIT III

Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions-
Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat Web
Server- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example. JSP:
Understanding Java Server Pages- Creating HTML forms by embedding JSP code.

Servlet
 Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
 Servlet technology is robust and scalable because of java language.
 There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is Servlet

 Servlet is a technology which is used to create a web application.


 Servlet is an API that provides many interfaces and classes including documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a dynamic web
page.

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.

Java Servlet Architecture


Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an HTML form on
a Web page or it could also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing
the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document
can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.

Servlet Life Cycle


1) Servlet class is loaded

 The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

 The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.

3) init method is invoked

 The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

 The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

5) destroy method is invoked

 The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:

public void destroy()

Servlet Example1

public class HelloWorld extends GenericServlet

public void service(ServletRequest request, ServletResponse response )

throws IOException

response.setContentType("text/html");

PrintWriter out = response.getWriter();


out.println("<h1> Hello World </h1>");

out.close();

Servlet Example2

public class HelloWorld extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response )

throws IOException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<h1> Hello World </h1>");

out.close();

Installing and Configuring Apache Tomcat Web Server


Steps to create a servlet

 There are given 6 steps to create a servlet example. These steps are required for all the
servers.
 Here, we are going to use apache tomcat server in this example. The steps are as
follows:
o Create a directory structure
o Create a Servlet
o Compile the Servlet
o Create a deployment descriptor
o Start the server and deploy the project
o Access the servlet

1)Create a directory structures

 The directory structure defines that where to put the different types of files so that
web container may get the information and respond to the client.
 The Sun Microsystem defines a unique standard to be followed by all the server
vendors. Let's see the directory structure that must be followed to create the servlet.
 As you can see that the servlet class file must be in the classes folder. The web.xml
file must be under the WEB-INF folder.

2)Create a Servlet

 There are three ways to create the servlet.


o By implementing the Servlet interface
o By inheriting the GenericServlet class
o By inheriting the HttpServlet class
 The HttpServlet class is widely used to create the servlet because it provides methods
to handle http requests such as doGet(), doPost, doHead() etc.
 In this example we are going to create a servlet that extends the HttpServlet class. In
this example, we are inheriting the HttpServlet class and providing the
implementation of the doGet() method. Notice that get request is the default request.

DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different
jar files:

Jar file Server


1) servlet-api.jar Apache Tomcat
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss

 Two ways to load the jar file


o set classpath
o paste the jar file in JRE/lib/ext folder
 Put the java file in any folder. After compiling the java file, paste the class file of
servlet in WEB-INF/classes directory.

4)Create the deployment descriptor (web.xml file)

 The deployment descriptor is an xml file, from which Web Container gets the
information about the servet to be invoked.
 The web container uses the Parser to get the information from the web.xml file. There
are many xml parsers such as SAX, DOM and Pull.
 There are many elements in the web.xml file. Here is given some necessary elements
to run the simple servlet program.

web.xml file

<web-app>

<servlet>

<servlet-name>sonoojaiswal</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sonoojaiswal</servlet-name>

<url-pattern>/welcome</url-pattern>

</servlet-mapping>

</web-app>

 Description of the elements of web.xml file


 There are too many elements in the web.xml file. Here is the illustration of some
elements that is used in the above web.xml file. The elements are as follows:
o <web-app> represents the whole application.
o <servlet> is sub element of <web-app> and represents the servlet.
o <servlet-name> is sub element of <servlet> represents the name of the servlet.
o <servlet-class> is sub element of <servlet> represents the class of the servlet.
o <servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
o <url-pattern> is sub element of <servlet-mapping>. This pattern is used at
client side to invoke the servlet.

5)Start the Server and deploy the project

 To start Apache Tomcat server, double click on the startup.bat file under apache-
tomcat/bin directory.
 You need to perform 2 tasks:
o set JAVA_HOME or JRE_HOME in environment variable (It is required to
start server).
o Change the port number of tomcat (optional). It is required if another server is
running on same port (8080).

Deploy the servlet project

 Copy the project and paste it in the webapps folder under apache tomcat.

6) How to access the servlet

 Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For


example:
 http://localhost:9999/demo/welcome

How Servlet works?


 It is important to learn how servlet works for understanding the servlet well. Here, we
are going to get the internal detail about the first servlet program.
 The server checks if the servlet is requested for the first time.
 If yes, web container does the following tasks:
o loads the servlet class.
o instantiates the servlet class.
o calls the init method passing the ServletConfig object
 else
o calls the service method passing request and response objects
 The web container calls the destroy method when it needs to remove the servlet such
as at time of stopping server or undeploying the project.

How web container handles the servlet request?

 The web container is responsible to handle the request. Let's see how it handles the
request.
o maps the request with the servlet in the web.xml file.
o creates request and response objects for this request
o calls the service method on the thread
o The public service method internally calls the protected service method
o The protected service method calls the doGet method depending on the type of
request.
o The doGet method generates the response and it is passed to the client.
o After sending the response, the web container deletes the request and response
objects. The thread is contained in the thread pool or deleted depends on the
server implementation.

Form GET and POST actions


Form GET action

index.html

<!DOCTYPE html>
<html>
<head>
<title>doGet Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“get">
Enter Name:<input type="text" name="uname"><br><br>
Enter Age:<input type=“text" name=“uage"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String age=request.getParameter(“uage");
out.println("<h3>Welcome to doGet Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Age:"+age);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Form POST Actions


index.html
<!DOCTYPE html>
<html>
<head>
<title>doPost Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“post">
Enter Name:<input type="text" name="uname"><br><br>
Enter Password:<input type="password" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
public class MySerlvet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
out.println("<h3>Welcome to doPost Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Password:"+pwd);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Session Tracking in Servlets


 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.
Session Tracking Techniques
 There are four techniques used in Session tracking:
o Cookies
o Hidden Form Field
o URL Rewriting
o HttpSession

1. 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.
Types of Cookie
 There are 2 types of cookies in servlets.
o Non-persistent cookie
o Persistent cookie
 Non-persistent cookie
o It is valid for single session only. It is removed each time when user closes the
browser.
 Persistent cookie
o 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.
How to create Cookie?
 Let's see the simple code 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?


 Let's see the simple code to delete cookie. It is mainly used to logout or signout the
user.
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?
 Let's see the simple code to get all the 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
}

Example

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 response){
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);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

2) 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.
 Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

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
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);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
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();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
3)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.
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
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);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

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.
How to get the HttpSession object ?
 The HttpServletRequest interface provides two methods to get the object of
HttpSession:

o public HttpSession getSession():Returns the current session associated with


this request, or if the request does not have a session, creates one.
o 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.

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);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
DATABASE CONNECTIVITY
JDBC
• Java Database Connectivity (JDBC) is an application programming interface (API)
for the programming language Java, which defines how a client may access a database
• It is Java based data access technology and used for Java database connectivity
• JDBC allows multiple implementations to exist and be used by the same application
• The JVM uses a JDBC driver to translate generalized JDBC calls into vendor specific
database calls
JDBC Architecture

• JDBC API
– JDBC API provides universal data access from the Java programming
language
– Using the JDBC API, you can access virtually any data source, from relational
databases to spreadsheets and flat files
– The JDBC API is comprised of two packages:
• java.sql
• javax.sql
• JDBC Driver Manager
– The DriverManager class acts as an interface between user and drivers
– It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver
– The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver()
• JDBC Driver
– A JDBC driver is a software component enabling a Java application to
interact with a database
– JDBC drivers are analogous to ODBC drivers, ADO.NET data providers,
and OLE DB providers
– To connect with individual databases, JDBC (the Java Database
Connectivity API) requires drivers for each database
– The JDBC driver gives out the connection to the database and implements
the protocol for transferring the query and result between client and
database.
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Type 2 - Native API Driver
• Type 3 – Network-Protocol Driver
• Type 4 – Database-Protocol Driver
• Type 1 that calls native code of the locally available ODBC driver.
• Type 2 that calls database vendor native library on a client side. This code then talks
to database over the network.
• Type 3, the pure-java driver that talks with the server-side middleware that then talks
to the database.
• Type 4, the pure-java driver that uses database native protocol.


Type 1 - JDBC-ODBC Bridge

Uses a bridging technology to access a database. JDBC-ODBC bridge is an
example. It provides a gateway to the ODBC.
• Type 2 - Native API Driver
• Native API drivers.
• Driver contains Java code that calls native C/C++ methods provided by the
database vendors.
• Type 3 – Network-Protocol Driver
• Generic network API that is then translated into database-specific access at the
server level.
• The JDBC driver on the client uses sockets to call a middleware application on
the server that translates the client requests into an API specific to the desired
driver. Extremely flexible.
• Type 4 – Database-Protocol Driver
• Using network protocols built into the database engine talk directly to the
database using Java sockets. Almost always comes only from database
vendors.
Type-1 JDBC-ODBC Bridge
• Converts JDBC method calls into ODBC function calls
• Platform-dependent
• ODBC must be installed on the computer having the driver
• Sun (now Oracle) provided a JDBC-ODBC Bridge
river: sun.jdbc.odbc.JdbcOdbcDriver.
• Advantages
– Almost any database for which an ODBC driver is installed can be accessed,
and data can be retrieved.
• Disadvantages
– Performance overhead
– The ODBC driver needs to be installed on the client machine.
– Not suitable for applets
– Specific ODBC drivers are not always available on all platforms
– No support from JDK 1.8 (Java 8) onwards.
Type 2 - Native API Driver

• It is a database driver implementation that uses the client-side libraries of the database
• converts JDBC method calls into native calls of the database API
• Advantages
– As there is no implementation of JDBC-ODBC bridge, it may be considerably
faster than a Type 1 driver.
• Disadvantages
– The vendor client library needs to be installed on the client machine.
– Not all databases have a client-side library.
– This driver is platform dependent.
– No Applets support
Type 3 – Network-Protocol Driver

• Pure Java driver for database middleware


• It is a database driver implementation which makes use of a middle tier between the
calling program and the database
• The middle-tier (application server) converts JDBC calls directly or indirectly into a
vendor-specific database protocol.
• platform-independent
• Advantages
– Since the communication between client and the middleware server is
database independent, there is no need for the database vendor library on the
client.
– The middleware server can provide typical middleware services like caching,
load balancing, logging, and auditing.
– A single driver can handle any database, provided the middleware supports it.
• Disadvantages
– Requires database-specific coding to be done in the middle tier.
– The middleware layer added may result in additional latency, but is typically
overcome by using better middleware services.
Type-4 Database-Protocol driver (Pure Java driver)
• a database driver implementation that converts JDBC calls directly into a vendor-
specific database protocol
• Written completely in Java
• Platform independent
• Advantages
– These drivers don't translate the requests into an intermediary format (such as
ODBC).
– The client application connects directly to the database server.
– The JVM can manage all aspects of the application-to-database connection
• Disadvantages
– Drivers are database specific, as different database vendors use widely
different network protocols.
Which Driver should be Used?
• Type is 4: If you are accessing one type of database, such as Oracle, Sybase, or IBM
• Type 3: If your Java application is accessing multiple types of databases at the same
time
• Type 2: When a type 3 or type 4 driver is not available
• Type 1: It is typically used for development and testing purposes only.
Basic steps to use a database in Java
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
JDBC program example
import java.sql.*;
public class DatabaseAccess
{
public static void main(String args[]) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next())
{
System.out.println("Roll No: " + rs.getInt(1) + "<br>");
System.out.println("Name: " + rs.getString(2) + "<br>");
}
stmt.close(); conn.close();
}
catch(SQLException se) { se.printStackTrace(); }
}
}

• Class.forName()
– The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
• DriverManager class
– The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
– public static Connection getConnection(String url,String
userName,String password):establish the connection with the specified url,
username and password.
• Connection interface
– A Connection is the session between java application and database.
– public Statement createStatement():creates a statement object that can be
used to execute SQL queries.
– public void close(): closes the connection and Releases a JDBC resources
immediately.
• Statement interface
– provides methods to execute queries with the database.
– public ResultSet executeQuery(String sql): is used to execute SELECT
query. It returns the object of ResultSet.
– public int executeUpdate(String sql): is used to execute specified query, it
may be create, drop, insert, update, delete etc.
• ResultSet interface
– maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.
– public boolean next():is used to move the cursor to the one row next from
the current position.
– public int getInt(int columnIndex):return the data of specified column index
of the current row as int.
– public int getInt(String columnName):return the data of specified column
name of the current row as int.
– public String getString(int columnIndex):return the data of specified
column index of the current row as String.
– public String getString(String columnName):return the data of specified
column name of the current row as String.
• PreparedStatement interface
– a subinterface of Statement
– It is used to execute parameterized query.
– Eg.: String sql="insert into emp values(?,?,?)";

JSP – Java Server Page

 JSP technology is used to create web application just like Servlet technology.
 It can be thought of as an extension to Servlet because it provides more functionality
than servlet such as expression language, JSTL, etc.
 A JSP page consists of HTML tags and JSP tags.
 The JSP pages are easier to maintain than Servlet because we can separate designing
and development.
 It provides some additional features such as Expression Language, Custom Tags, etc.

Advantages
1) Extension to Servlet
2) Easy to maintain
3) Fast Development: No need to recompile and redeploy
4) Less code than Servlet

The Lifecycle of a JSP Page


 The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method)
JSP Scripting Elements

 The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


 A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>

Example
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Expression tag

 The code placed within JSP expression tag is written to the output stream of the
response.
 So you need not write out.print() to write data. It is mainly used to print the values of
variable or method.

Syntax of JSP expression tag


<%= statement %>

Example

<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Declaration Tag

 The JSP declaration tag is used to declare fields and methods.


 The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
 So it doesn't get memory at each request.

Syntax
<%! field or method declaration %>
Example
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare The jsp declaration tag can declare variables as
variables not methods. well as methods.

The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.
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:
o page directive
o include directive
o taglib directive
 Syntax of JSP Directive
<%@ directive attribute="value" %>

JSP page directive


 The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
Attribute Meaning
Name
Import Used to import class, interface or all the members of a package.
contentType Defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.
Extends Defines the parent class that will be inherited by the generated servlet.
Info Sets the information of the JSP page
Buffer Sets the buffer size in kilobytes to handle output generated by the JSP page.
Language Specifies the scripting language used in the JSP page.
isELIgnored We can ignore the Expression Language (EL) in jsp by the isELIgnored
attribute.
isThreadSafe If you want to control this behaviour of JSP page, you can use isThreadSafe
attribute of page directive
Session Used to set session
errorPage If exception occurs in the current page, it will be redirected to the error
page.
isErrorPage declare that the current page is the error page.

Include Directive
 The include directive is used to include the contents of any resource it may be jsp file,
html file or text file.
 The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include
static resource).

Advantage of Include directive


 Code Reusability
Syntax
<%@ include file="resourceName" %>

Example
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Taglib directive

 The JSP taglib directive is used to define a tag library that defines many tags.
 We use the TLD (Tag Library Descriptor) file to define the tags.
 In the custom tag section we will use this tag so it will be better to learn it in custom
tag.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example

<html>

<body>

<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>

</html>

Action Tags

 There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
 The action tags are used to control the flow between pages and to use Java Bean. The
Jsp action tags are given below.

JSP Action Tags Description


jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in
jsp:plugin.
page1.jsp

<html>

<body>

<h2>this is index page</h2>

<jsp:forward page="page2.jsp" >

<jsp:param name=“email" value=“[email protected]" />

</jsp:forward>

</body>

</html>

page2.jsp

<html>

<body>

<%= request.getParameter(“email") %>

</body>

</html>

jsp:include

<html>

<body>

<h2>this is index page</h2>

<jsp:include page=“page2.jsp" />

<h2>end section of index page</h2>

</body>

</html>

Creating HTML forms by embedding JSP code.

<html>

<head>

<title>Using GET Method to Read Form Data</title>

</head>

<body>
<h1>Using GET Method to Read Form Data</h1>

<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

<li><p><b>Last Name:</b>

<%= request.getParameter("last_name")%>

</p></li>

</ul>

</body>

</html>

You might also like