0% found this document useful (0 votes)
35 views32 pages

IT3401-WE Unit 5

Uploaded by

agignatius
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)
35 views32 pages

IT3401-WE Unit 5

Uploaded by

agignatius
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/ 32

UNIT-V

Servlets and Database Connectivity

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, you can collect input from users through web
page forms, present records from a database or another
source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI). But
Servlets offer several advantages in comparison with the CGI.
• Performance is signi icantly better.
• Servlets execute within the address space of a Web
server. It is not necessary to create a separate process to
handle each client request.
• Servlets are platform-independent because they are
written in Java.
• Java security manager on the server enforces a set of
restrictions to protect the resources on a server
machine. So servlets are trusted.
• The full functionality of the Java class libraries is
available to a servlet. It can communicate with applets,
databases, or other software via the sockets and RMI
mechanisms that you have seen already.
Servlets Architecture The following diagram shows the
position of Servlets in a Web
Application.

Servlets Tasks
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.
Servlets Packages
Java Servlets are Java classes run by a web server that has an
interpreter that supports the Java Servlet speci ication.
Servlets can be created using the javax.servlet and
javax.servlet.http packages, which are a standard part of the
Java's enterprise edition, an expanded version of the Java class
library that supports largescale development projects.
These classes implement the Java Servlet and JSP
speci ications. At the time of writing this tutorial, the versions
are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any
other Java class. After you install the servlet packages and add
them to your computer's Classpath, you can compile servlets
with the JDK's Java compiler or any other current compiler.
Architecture Diagram
The following igure depicts a typical servlet life-cycle
scenario.

• FirstAdvantages
the HTTPOfrequests
Servlets :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.
1. As servlets support all protocols like FTP, SMTP, HTTP
etc. they can be used to develop any kind of web
applications like E-commerce, Content management
systems, chat based or ile based web applications etc.

2. As servlets are fully compatible with Java, you can make


use of wide range of available Java APIs inside the
servlets.

3. As they run on Java enabled servers, You need not to


worry about garbage collection and memory leaks. JVM
handles them for you.

4. Since servlets are written in Java, they are portable and


platform independent. You can run them on any
operating systems and on any web servers available
today.

5. Servlets inherit security features from JVM and web


server.

6. As servlets are written in Java, you can extend them


according to your requirements.

7. As servlets are compiled into bytecodes, they are faster


than any other server-side scripting languages.

2.EXPLAIN SERVLET LIFECYCLE.?


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.
Now let us discuss the life cycle methods in detail.

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 servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet
be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets
created, with each user request resulting in a new thread that is handed
off to doGet or doPost as appropriate. The init() method simply creates
or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code... }

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.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException { }

The service () method is called by the container and service method


invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.
So you have nothing to do with service() method but you override either
doGet() or doPost() depending on what type of request you receive from
the client.
The doGet() and doPost() are most frequently used methods with in
each service request. Here is the signature of these two methods.

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.
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 your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for
garbage collection. The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}

3.Explain Form GET and POST actions in servlets?


GET Method The GET method sends the encoded user
information appended to the page request. The page and the
encoded information are separated by the ? (question mark)
symbol as follows − http://www.test.com/hello?key1 =
value1&key2 = value2
The GET method is the default method to pass information
from browser to web server and it produces a long string that
appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information
to pass to the server. The GET method has size limitation: only
1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and
will be accessible through QUERY_STRING environment
variable and Servlet handles this type of requests using
doGet() method.
POST Method
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. Servlet
handles this type of requests using doPost() method.
Reading Form Data using Servlet Servlets handles form data
parsing automatically using the following methods depending
on the situation −
• 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.
GET Method Example using URL
Here is a simple URL which will pass two values to HelloForm
program using GET method.
http://localhost:8080/HelloForm? irst_name =
ZARA&last_name = ALI
Given below is the HelloForm.java servlet program to handle
input given by web browser. We are going to use
getParameter() method which makes it very easy to access
passed information −
// Import required java libraries
import java.io.*; import
javax.servlet.*; import
javax.servlet.http.*;

// Extend HttpServlet class public class HelloForm extends


HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter(); String title =


"Using GET Method to Read Form Data"; String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType + "<html>\n" +
"<head><title>" + title + "</title></head>\n" + "<body
bgcolor = \"#f0f0f0\">\n" + "<h1 align = \"center\">"
+ title + "</h1>\n" + "<ul>\n" + " <li><b>First
Name</b>: " + request.getParameter(" irst_name")
+ "\n" + " <li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n"
+ "</body>" + "</html>" );
}
}
Assuming your environment is set up properly, compile
HelloForm.java as follows −
$ javac HelloForm.java If everything goes ine, above
compilation would produce HelloForm.class ile. Next you
would have to copy this class ile in
<Tomcatinstallationdirectory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml ile
located in <Tomcat-installation-
directory>/webapps/ROOT/WEBINF/ <servlet>

</servlet>

<servlet-mapping> <servlet-name>HelloForm</servlet-
name> <url-pattern>/HelloForm</url-pattern> </servlet-
mapping> Now
type http://localhost:8080/HelloForm? irst_name=ZARA&last
_name=ALI in your browser's Location:box and make sure you
already started tomcat server, before iring above command in
the browser. This would generate following result −
Using GET Method to Read Form Data
• First Name: ZARA
• Last Name: ALI
GET Method Example Using Form
Here is a simple example which passes two values using HTML
FORM and submit button. We are going to use same Servlet
HelloForm to handle this input.
<html> <body> <form action = "HelloForm" method =
"GET"> First Name: <input type = "text" name =
" irst_name"> <br /> Last Name: <input type = "text"
name = "last_name" /> <input type = "submit" value =
"Submit" /> </form> </body>
</html>
Keep this HTML in a ile Hello.htm and put it in
<Tomcatinstallationdirectory>/webapps/ROOT directory.
When you would access http://localhost:8080/Hello.htm, here
is the actual output of the above form.
First Name: Last Name:

Try to enter First Name and Last Name and then click submit
button to see the result on your local machine where tomcat
is running. Based on the input provided, it will generate
similar result as mentioned in the above example.
POST Method Example Using Form
Let us do little modi ication in the above servlet, so that it can
handle GET as well as POST methods. Below is
HelloForm.java servlet program to handle input given by
web browser using GET or POST methods. // Import required
java libraries import java.io.*; import javax.servlet.*; import
javax.servlet.http.*;
// Extend HttpServlet class public class HelloForm extends
HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Dat a";

String docType = "<!doctype html public \"-


//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType + "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" + "<h1 align =
\"center\">" + title + "</h1>\n" + "<ul>\n" + "
<li><b>First Name</b>: " +
request.getParameter(" irst_name") + "\n" + "
<li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n"
+ "</body>" "</html>" );
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using
Hello.htm with the POST method as follows −
<html> <body>

<form action = "HelloForm" method = "POST" >


First Name: <input type = "text" name = " irst_name">

Last Name: <input type = "text" name = "last_name" />


<input type = "submit" value = "Submit" />
<br />

</form> </body> </html>


Here is the actual output of the above form, Try to enter First
and Last Name and then click submit button to see the result
on your local machine where tomcat is running.
First Name: Last Name:

4. Explain Cookies in servlets?


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 quali iers, a maximum
age, and a version number.
How Cookie works
By default, each request is considered as a new request. 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.
PlayNext
Unmute Current TimeA 0:00
/
DurationA 18:10 Loaded: 0.37%
A
Fullscreen

Backward Skip 10sPlay VideoForward Skip 10s


1. Non-persistent cookie
2. 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

1. Simplest technique of maintaining the state.

2. Cookies are maintained at client side.


Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.

2. Only textual information can be set in Cookie object.


Note: Gmail uses cookie technique for login. If you disable the
cookie, gmail won't work. Cookie class
javax.servlet.http.Cookie class provides the functionality of
using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, constructs a cookie with a


String value) speci ied name and value.

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie
class.

Method Description

public void Sets the maximum age of


setMaxAge(int the cookie in seconds.
expiry)
public String Returns the name of the
getName() cookie. The name cannot
be changed after creation.

public String Returns the value of the


getValue() cookie.

public changes
void the name of the
setName(String
name)

public void changes the value of the


setValue(String cookie.
value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some
methods provided by other interfaces. They are:

1. public void addCookie(Cookie ck)


2. public Cookie[] getCookies()

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 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 cooki
e ck.setMaxAge(0);//changing the maximum age to 0
secon ds
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
}
Simple example of Servlet Cookies
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, HttpSer

response.setContentType("text/html");
PrintWriter out = response.getWriter();
vletResponse response){
try{

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie ob


ject response.addCookie(ck);//adding cookie in the
respons e
//creating submit button out.print("<form
action='servlet2'>"); out.print("<input
type='submit' value='go'>");
out.print("</form>");

}catch(Exception e){System.out.println(e);}
out.close();

}
}
SecondServlet.java import
java.io.*; import
javax.servlet.*; import
javax.servlet.http.*;
public class SecondServlet
extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServ
letResponse response){
try{

<servlet -mapping>
response.setContentType("text/html");
<servlet -name>s1</servlet
PrintWriter -name>
out = response.getWriter();
<url-pattern>/servlet1</url-pattern>

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> <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>
Output
5.Explain Database Connectivity using JDBC?
Database connectivity in servlet. There are different
approaches to communicating with databases through servlet
components. We need to perform the servlet to database
communication due to the following main reasons: -
• To save the inputs coming from the end -user through
forms to database software. Example: - Email Id
registration.
• To save the result generated by servlet Component in
database software. Example: - Bill generation
• To get inputs from the database software to the Servlet
component.
statement generation
Example:- Balance inquiry, account
For servlet to database software
communication, we need to place JDBC
code/Hibernate code/Spring
JDBC/Spring ORM/Spring Data code in
Servlet Component. Since JDBC is the most
basic one therefore here we will discuss
servlet to database communication
through JDBC code.
Different Approaches for Database Connectivity in Servlet
There are 4 approaches for Database Connectivity in Servlet.
Approach-1:- Writing logics in multiple methods.
• Create JDBC Connection in the init()
• Use the JDBC Connection in the service(-,-)/doXxx(-,-)
• Close JDBC Connection in the destroy method.
Here JDBC Connection (con) must be taken as an instance
variable of the Servlet Component class.
The disadvantage of this approach:- Since JDBC Connection is
an instance variable, it is not thread-safe by default. So, we
should use the synchronization concept.
Advantage:- All the requests coming to Servlet Component
will use a single JDBC Connection to interact with database
software, due to this the performance will be improved.
Note:- This approach is outdated and nowadays no one is
using this approach (except the maintenance side).
Approach-2:- Write all the logics in service(-,-) or doXxx(,-)
method.
• Create JDBC Connection in service(-,-
)/doXxx(-,-) method.
• Use JDBC Connection in service(-,-)/doXxx(-,-) method.
• Close JDBC Connection in service(-,-)/doXxx(-,-) method.
Note:- Here JDBC Connection (con) will be a local variable to
service(-,-)/doXxx(-,-) method.
Disadvantage:- The JDBC Connection (con) is a local variable
so, every request which is given to the servlet will create one
JDBC Connection object with database software, hence the
performance will be poor.
Advantage:- Since JDBC Connection is a local variable, it is
thread-safe by default. Hence there is no need to work with
the synchronization concept.
Approach-3:- Use server-managed JDBC connection from
the connection pool.
• Get JDBC Connection object from JDBC Connection pool
being from service(-,-)/doXxx(-,-) • Use JDBC Connection
object in service(-,-)/doXxx(-,-) • Return JDBC connection
back to JDBC connection pool being from service(-,-
)/doXxx(-,-)
Advantage:- Here JDBC connection is local to service(-
,)/doXxx(-,-) method. So, it becomes thread-safe.
We can get all the advantages of the JDBC connection pool. The
main advantages of the JDBC connection pool are,
• Reusability of JDBC connection objects.
• With minimum JDBC connection objects, we can make
max clients/requests talking with database software.
• Programmer is free from creating connection objects,
managing connection objects, and destroying connection
objects.
Web servers are also supplying existing created JDBC
connections. Therefore programmers should not worry about
how to create JDBC connections, manage them and destroy
them. These tasks will be done by the web server itself. The
programmer will just fetch those JDBC connections and use
them in the servlet component. Moreover, one JDBC
connection can be used for multiple requests, therefore
performance will be good compared to approach2.
Approach4:- Use DAO class for the persistence operation.
What is DAO:- The Java class/component that separates
persistence logic from other logics of the application and
makes that logic as lexible logic to modify and reusable logic
is called DAO (Data access object).
In this approach, we can use either approach-2 or approach3
to get the JDBC connection. The main task in this approach,
• Write JDBC code (persistence logic) in DAO class either by
using direct connection object or server-managed pooled
connection object.
• Create a DAO class object in Servlet Component and use its
persistence logic in Servlet Component

You might also like