Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 1
Unit-3: Servlets:
3.1 What is a Server?
A server is a computer that responds to requests from a client
Typical requests: provide a web page, upload or download a file, send email
A server is also the software that responds to these requests; a client could be the browser or
other software making these requests
Typically, your little computer is the client, and someone else’s big computer is the server
However, any computer can be a server
It is not unusual to have server software and client software running on the same computer
Ex: Apache Tomcat is a Server Apache is a very popular server
o 66% of the web sites on the Internet use Apache
o Apache is:
Full-featured and extensible
Efficient
Robust
Secure
Up to date with current standards
Open source
Free
3.1.1 What is Web Application Development?
Web application development involves development of Dynamic HTML applications that can
interact with database
In the development of web based applications the interaction of Web application works on this
way
Browser CGI or Servlet Server
HTML
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 2
3.1.2 What Is a Servlet?
A servlet is a small Java program that runs within a Web server.
Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper Text
Transfer Protocol.
Servlet is an opposite of applet as a server-side applet.
Applet is an application running on client while servlet is running on server.
Servlets are server side components that provide a powerful mechanism for developing web
applications.
Using servlets we can create fast and efficient server side applications and can run it on any servlet
enabled web server.
Servlet runs entirely inside the JVM (Java Virtual Machine).
Since the servlet runs on server side so it does not depend on browser compatibility.
“The Helper Application is nothing but a SERVLET”
Client Server
Request
Response
Servlet
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 3
The content of the dynamic web pages need to be generated dynamically.
In the early days of the Web, a server could dynamically construct a page by creating a separate
process to handle each client request.
The process would open connections to one or more databases in order to obtain the necessary
information.
It communicated with the Web server via an interface known as the Common Gateway Interface
(CGI).
3.2 What is CGI?
CGI (Common gateway interface) written in pearl language which acts as an
interface between client and server to deal with request and response
CGI allowed the separate process to read data from the HTTP request and write data to
the HTTP response.
JOBS of CGI and SERVLET
o Explicit, implicit data sent by client to server is processed and another explicit ,
implicit data is returned
o Explicit data information received from client GUI ex: username , password
o Implicit data HTTP information that is generated by the client (browser)
rather than user.
o Http information contains data about request such as cookies, media types, and
compression scheme.
3.2.1 How Does CGI works? Why use Servlet when CGI is available?
In CGI every time a request is made a new process starts
Ex: let say 100 instances of an application require CGI program to process their request
simultaneously, the CGI program must be loaded 100 times in memory. (100 copies are made)
It Degrades the performance as the instance increases
Once CGI program terminates all the data used by the process is lost and cannot be used by other
programs
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 4
3.2.2 What makes Servlet better?
Java Servlet technology avoids drawbacks of CGI,
First only one copy is loaded in JVM no matter the number of simultaneous requests made.
Each request begins a thread to the java servlet rather than a new process. This saves memory and
increases response time.
It is persistent java servlet remains alive after the request is fulfilled. And data used by
servlet can be retained and can be used for business requirement of J2ee applications.
Servlets Architecture:
Following diagram shows the position of Servlets in a Web Application.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 5
3.3 A Simple JAVA Servlet
A java Servlet is a java class that reads request sent from a client and responds by sending
information to the client.
The java class must extend HttpServlet and override the Httpservlet’s doGet() or doPost()
methods
doGet() used when request is sent using the METHOD=“GET” attribute of HTML
doPost() used when request is sent using the METHOD=“POST” attribute of HTML
Both doGet() and doPost() requires two arguments
The first argument is an HttpservletRequest object
The secons argument is an HttpservletResponse object
The HttpSevletRequest used to receive request from cleint.
The HttpServletResponse is used to Respond to Client.
(format of data response depends on client, ex: data given is in the form of a HTML or XML
page if the client is a browser)
Both throws ServletExcetion and IOException
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException{
res.setContentType(“text/html”)
PrintWriter out=res.getWriter();
out.println("<html>“);
out.println("<head><title>Java Servlet</title></head>");
out.println("<body>“);
out.println(“<p> My First Servlet program </p> “);
out.println("</body></html>");
}
}
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 6
3.4 Servlet Lifecycle
• The Servlet lifecycle is simple, there is only one main state – “Initialized”.
Initialized
Does not exist
constructor()
init() destroy()
Service() Executes doGet() or doPost()
Destroy can be
overridden to
Cloase DB
connections
Init can be
overriden to open
DB connections
init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a
servlet.
They are implemented by every servlet and are invoked at specific times by the server.
Procedure:
First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server.
Second, this HTTP request is received by web server, web server maps this request to a particular
servlet.
The servlet is dynamically retrieved & loaded into the address space of the server.
Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
is first loaded into memory.
It is possible to pass initialization parameters to the servlet so it may configure itself.
Fourth, the server invokes the service ( ) method of the servlet. This method is called to process
the HTTP request. It may also formulate an HTTP response for the client.
The service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The server calls the
destroy( ) method to relinquish any resources such as file handles that are allocated for the
servlet.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 7
3.5 The Servlet API
Packages
javax.servlet
The javax.servlet package contains a number of classes and interfaces that describe
and define the contracts between a servlet class and the runtime environment
provided for an instance of such a class by a conforming servlet container.
javax.servlet.http
The javax.servlet.http package contains a number of classes and interfaces that
describe and define the contracts between a servlet class running under the HTTP
protocol and the runtime environment provided for an instance of such a class by a
conforming servlet container.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 8
The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
Interface Summary
RequestDispatcher
Defines an object that receives requests from the client and sends them to
any resource (such as a servlet, HTML file, or JSP file) on the server.
Servlet Defines methods that all servlets must implement.
ServletConfig
A servlet configuration object used by a servlet container to pass information
to a servlet during initialization.
ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet
container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file.
ServletRequest Defines an object to provide client request information to a servlet.
ServletResponse Defines an object to assist a servlet in sending a response to the client.
The Servlet Interface Methods:
Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being
taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup
parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
void init(ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is being
placed into service.
void service(ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a request.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 9
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Summary
GenericServlet Defines a generic, protocol-independent servlet.
ServletInputStream
Provides an input stream for reading binary data from a client
request, including an efficient readLine method for reading data one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletRequestAttributeEvent
This is the event class for notifications of changes to the attributes
of the servlet request in an application.
ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.
The GenericServlet Class
The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
GenericServlet implements the Servlet and ServletConfig interfaces.
In addition, a method to append a string to the server log file is available.
The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.
The Servlet Exception Classes
javax.servlet defines two exceptions.
The first is ServletException, which indicates that a servlet problem has occurred.
The second is UnavailableException, which extends ServletException. It indicates that a servlet
is unavailable.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 10
3.6 Reading Servlet Parameters
The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request.
The example contains two files. A Web page is defined in PostParameters.htm and a servlet is
defined in PostParametersServlet.java.
File Name: PostParametersServlet.java
package ServletPrograms;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class prog2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>user password</title></head>");
out.println("<body>");
String username=request.getParameter("username");
String password=request.getParameter("password");
out.println("username = "+username);
out.println("<br>");
out.println("password = "+password);
out.println("</body></html>");
out.close();
}
}
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 11
File Name: PostParameters.html
<html>
<body>
<form action="prog2" method="post">
<table>
<tr>
<td><B>username</b></td>
<td><input type=text name="username"></td>
</tr>
<tr><td><B>password</b></td>
<td><input type=password name="password"></td>
</tr>
</table>
<input type=submit value="submit">
</form>
</body>
</html>
Deployment Descriptor • How does the Container know which Servlet the client has requested for?
A Servlet can have 3 names
Client known URL name
Deployer known secret internal name
Actual file name
Web.xml file
<web-app>
<servlet>
<servlet-name> prog2</servlet-name>
<servlet-class>Programs.prog2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> prog2</servlet-name>
<url-pattern>prog2</ url-pattern >
</servlet-mapping>
</web-app>
Web.xml file
It is a deployment descriptor which is by default
created by netbean, but in manual procedure we have
to create it. With respect to practical exam students
should write this file contents too. This file is
common for all servlet programs with only change in
servlet-name, url, class name as highlighted below
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 12
Output:
The javax.servlet.http Package
The javax.servlet.http package contains a number of interfaces classes that are commonly used by
servlet developers.
Interface Summary
HttpServlet
HttpServletRequest
Extends the ServletRequest interface to provide request information for HTTP servlets.
HttpServletResponse
Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.
HttpSession
Provides a way to identify a user across more than one page
request or visit to a Web site and to store information about that
user.
3.7 doGet and doPost methods of Servlet
The default service() method in an HTTP servlet routes the request to another method based on
the HTTP transfer method (POST, and GET).
HTTP POST requests from HTML file are routed to the doPost() method, HTTP GET requests
are routed to the doGet() method.
Most operations that involve forms use either a GET or a POST operation, so for most servlets
override either doGet() or doPost().
Implementing both methods is a good practice to provide both input types or pass the request
object to a central processing method.
Submit from Prog2.html File Result from Prog2.java Servlet File
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 13
Example Program using HTTP doGet() method:
The doGet() method is the method inside a servlet that gets called every time a request from a
html or jsp page is submitted.
The control first reaches the doGet() method of the servlet and then the servlet decides what
functionality to invoke based on the submit request. The get method called when the type of page
submission is "GET".
doGet is used when there is are requirement of sending data appended to a query string in the
URL.
The doGet models the GET method of Http and it is used to retrieve the info on the client from
some server as a request to it.
The doGet cannot be used to send too much info appended as a query stream. GET puts the form
values into the URL string.
GET is limited to about 256 characters (usually a browser limitation) and creates really ugly
URLs.
package ServletPrograms;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class doGetDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>user password</title></head>");
out.println("<body>");
String username=request.getParameter("username");
String password=request.getParameter("password");
out.println("username = "+username);
out.println("<br>");
out.println("password = "+password);
out.println("</body></html>");
out.close();
}
}
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 14
Example Program using HTTP doPost() method:
The doPost() method is the method inside a servlet that gets called every time a requests from a
HTML or jsp page calls the servlet using "POST" method.
doPost allows you to have extremely dense forms and pass that to the server without clutter or
limitation in size. e.g. you obviously can't send a file from the client to the server via doGet.
doPost has no limit on the amount of data you can send and because the data does not show up on
the URL you can send passwords.
But this does not mean that POST is truly secure. It is more secure in comparison to doGet
method.
package ServletPrograms;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class doPostDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>user password</title></head>");
out.println("<body>");
String username=request.getParameter("username");
String password=request.getParameter("password");
out.println("username = "+username);
out.println("<br>");
out.println("password = "+password);
out.println("</body></html>");
out.close();
}
}
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 15
3.8 Difference between HTTP doGet and HTTP doPost methods of Servlet
Difference Type GET (doGet()) POST (doPost())
HTTP Request The request contains only the
request line and HTTP header.
Along with request line and header it
also contains HTTP body.
URL Pattern Query string or form data is
simply appended to the URL as
name-value pairs.
Form name-value pairs are sent in the
body of the request, not in the URL
itself.
Parameter passing The form elements are passed to
the server by appending at the
end of the URL.
The form elements are passed in the
body of the HTTP request.
Size The parameter data is limited
(the limit depends on the
container normally 4kb)
Can send huge amount of data to the
server.
Idempotency GET is Idempotent(can be
applied multiple times without
changing the result)
POST is not idempotent(warns if applied
multiple times without changing the
result)
Usage Generally used to fetch some
information from the host.
Generally used to process the sent data.
Security Not Safe - A person standing
over your shoulder can view
your userid/pwd if submitted
via Get (Users can see data in
address bar.)
Safe - No one will be able to view what
data is getting submitted (Data hidden
from users.)
Data Format Supports ASCII. Supports ASCII + Binary.
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 16
3.9 Servlet Context:
ServletContext is a interface which helps us to communicate with the servlet container.
There is only one ServletContext for the entire web application and the components of the web
application can share it.
The information in the ServletContext will be common to all the components.
Remember that each servlet will have its own ServletConfig.
The ServetContext is created by the container when the web application is deployed and after that
only the context is available to each servlet in the web application.
Web application initialization:
First of all the web container reads the deployment descriptor file and then creates a name/value
pair for each <context-param> tag.
After creating the name/value pair it creates a new instance of ServletContext.
It’s the responsibility of the Container to give the reference of the ServletContext to the context
init parameters.
The servlet and jsp which are part of the same web application can have the access of the
ServletContext.
The Context init parameters are available to the entire web application not just to the single
servlet like servlet init parameters.
How can we do the mapping of the Context init parameters in web.xml
Web.xml File:
<servlet>
<servlet-name>Mapping</servlet-name>
<servlet-class>ContextMapping</servlet-class>
</servlet>
<context-param>
<param-name>Email</param-name>
<param-value>[email protected]</param-value>
</context-param>
In the servlet code we will write this as
ServletContext context = getServletContext();
pw.println(context.getInitParameter("Email");
Department of MCA TEA-I-Unit-3 - Servlets-Notes KNS Institute of Technology
Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 17
Example program using the use of Servlet Context
package ServletPrograms;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class ServletContextDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>user password</title></head>");
out.println("<body>");
ServletContext context = getServletContext();
pw.println(context.getInitParameter("Email");
out.println("</body></html>");
}
}