IT3401-WE Unit 5
IT3401-WE Unit 5
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.
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 {
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>
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
Constructor Description
Method Description
public changes
void the name of the
setName(String
name)
For adding cookie or getting the value from the cookie, we need some
methods provided by other interfaces. They are:
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.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
vletResponse response){
try{
String n=request.getParameter("userName");
out.print("Welcome "+n);
}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-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