UNIT-III
HTTP (Hyper Text Transfer Protocol)
• The Hypertext Transfer Protocol (HTTP) is application-level protocol for
collaborative, distributed, hypermedia information systems.
• It is the data communication protocol used to establish communication between
client and server.
• It is used to send and receive data on the web.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data
like image files, query results, HTML files etc on the World Wide Web (WWW)
with the default port is TCP 80.
• It provides the standardized way for computers to communicate with each other .
There are three fundamental features that make the HTTP a simple and powerful
protocol used for communication:
1.HTTP is media independent: It specifies that any type of media content can be
sent by HTTP as long as both the server and the client can handle the data content.
2.HTTP is connectionless: It is a connectionless approach in which HTTP client
i.e., a browser initiates the HTTP request and after the request is sent the client
disconnects from server and waits for the response.
3.HTTP is stateless: The client and server are aware of each other during a current
request only. Afterwards, both of them forget each other. Due to the stateless nature
of protocol, neither the client nor the server can retain the information about
different request across the web pages.
GET POST
1) In case of Get request, In case of post request, large
only limited amount of data can amount of data can be sent because
be sent because data is sent in data is sent in body.
header.
2) Get request is not Post request is secured because data
secured because data is exposed in is not exposed in URL bar.
URL bar.
Static Web pages:
• Static Web pages are very simple.
• It is written in languages such as HTML, JavaScript, CSS, etc.
• static web pages when a server receives a request for a web page, then the server
sends the response to the client without doing any additional process. And these
web pages are seen through a web browser.
• In static web pages, Pages will remain the same until someone changes it
manually.
Dynamic Web Pages:
• Dynamic Web Pages are written in languages such as CGI, AJAX, ASP, ASP.NET,
etc.
• In dynamic web pages, the Content of pages is different for different visitors.
• It takes more time to load than the static web page.
• Dynamic web pages are used where the information is changed frequently, for
example, stock prices, weather information, etc.
SL.
Static Web Page Dynamic Web Page
NO
In static web pages, Pages will remain same until someone In dynamic web pages, Content of pages
1.
changes it manually. are different for different visitors.
2. Static Web Pages are simple in terms of complexity. Dynamic web pages are complicated.
In dynamic web page, Information are
3. In static web pages, Information are change rarely.
change frequently.
Static Web Page takes less time for loading than dynamic web Dynamic web page takes more time for
4.
page. loading.
5. In Static Web Pages, database is not used. In dynamic web pages, database is used.
Dynamic web pages are written in
Static web pages are written in languages such as: HTML,
6. languages such as:PHP,JSP,SERVLET,
JavaScript, CSS, etc.
CGI, AJAX, ASP, ASP.NET, etc.
Dynamic web pages contains application
7. Static web pages does not contain any application program .
program for different services.
INTRODUCTION TO SERVLETS
• Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
• Today we all are aware of the need of creating dynamic web pages s i.e the ones
which have the capability to change the site contents according to the time or are
able to generate the contents according to the request received by the client.
• Servlets are the Java programs that run on the Java-enabled web server or
application server.
• They are used to handle the request obtained from the web server, process the
request, produce the response, and then send response back to the web server.
• Properties of Servlets:
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from web server
Execution of Servlets:
Execution of Servlets involves six basic steps:
1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser displays it on the
screen. Servlet Architecture:
What is a web application?
A web application is an application accessible from the web. A web
application is composed of web components like Servlet, JSP, Filter, etc.
and other elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and respond to the HTTP
request.
Need For Server-Side Extensions:
The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages.
Actually, to provide the facility of dynamic Web pages, Web pages need a container
or Web server. To meet this requirement, independent Web server providers offer
some proprietary solutions in the form of APIs (Application Programming
Interface).
The Servlet technology is similar to other Web server extensions such as Common
Gateway Interface (CGI)
scripts and Hypertext Preprocessor (PHP). However, Java Servlets are more
acceptable since they
solve the limitations of CGI such as low performance and low degree scalability.
CGI (Common Gateway Interface)
• CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1.If the number of clients increases, it takes more time for sending the response.
2.For each request, it starts a process, and the web server is limited to start
processes.
3.It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI.
• The web container creates threads for handling the multiple requests to the
Servlet. Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads
are low.
• In simple words, it is a system that manages Java Servlet components on top of
the Web
• server to handle the Web client requests.
The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
5. The API designed for Java Servlet automatically acquires the advantages of Java
platform such as platform independent and portability.
Servlets API’s:
Servlets are build from two packages:
javax.servlet(Basic)
javax.servlet.http(Advance)
Various classes and interfaces present in these packages are:
LIFE CYCLE OF A SERVLET (Servlet Life Cycle):
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method isinvoked
There are three states of a servlet: new, ready and end.
• The servlet is in new state if servlet instance is created.
• After invoking the init() method, Servlet comes in the ready state.
• In the ready state, servlet performs all the tasks. When the web container invokes
the destroy() method, it shifts to the end state.
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 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.
Syntax:
public void init() throws ServletException
{
// Initialization code...
}
4) service() method is invoked:
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
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.
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
}
5) destroy() method is invoked:
• 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...
}
Architecture Diagram:
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet
container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
DEPLOYING SERVLETS:
There are given 6 steps to create a servlet example.
These steps are required for all the servers.
The servlet example can be created by three ways:
1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http
request specific method such as doGet(), doPost(), doHead() etc
Here, we are going to use apache tomcat server in this example. The steps are as
follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. 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 responds to the client.
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.
1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. 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.
Example:
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.
Two ways to load the jar file
1. set classpath
2. 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 WEBINF/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>
• <web-app> represents the whole application.
• <servlet> is sub element of <web-app> and represents the servlet.
• <servlet-name> is sub element of <servlet> represents the name of the servlet.
• <servlet-class> is sub element of <servlet> represents the class of the servlet.
• <servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
• <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.
6) How to access the servlet:
Open browser and write http://hostname:portno/contextroot/urlpattern of servlet.
Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
• The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.
Interfaces in javax.servlet package
1.Servlet
2.ServletRequest
3.ServletResponse
4.RequestDispatcher
5.ServletConfig
6.ServletContext
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
1.GenericServlet
2.ServletInputStream
3.ServletOutputStream
4.ServletRequestWrapper
5.ServletResponseWrapper
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
6.HttpServletRequest
7.HttpServletResponse
8.HttpSession
9.HttpSessionListener
10.HttpSessionAttributeListener
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1.HttpServlet
2.Cookie
3.HttpServletRequestWrapper
4.HttpServletResponseWrapper
Servlet Interface
Servlet interface provides common behavior to all the servlets.Servlet interface
defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the
requests, and to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
• There are 5 methods in Servlet interface. The init, service and destroy are the life
cycle methods of servlet. These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only
once.
Public void service(ServletRequest provides response for the incoming request. It is
request,ServletResponse response) invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is
being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
Servlet Example by implementing Servlet interface
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.
• GenericServlet class can handle any type of request so it is protocol-independent.
• You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.
Methods of GenericServlet class
• There are many methods in GenericServlet class. They are as follows:
1.public void init(ServletConfig config) is used to initialize the servlet.
2.public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time
when user requests for a servlet.
3.public void destroy() is invoked only once throughout the life cycle and indicates
that servlet is being destroyed.
4.public ServletConfig getServletConfig() returns the object of ServletConfig.
5.public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6.public void init() it is a convenient method for the servlet programmers, now
there is no need to call super.init(config)
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
<html lang="en">
<head>
<title>Login page</title>
</head>
<body>
<h1> Login Form </h1>
<form method="post" action="login">
Username: <input type="text" name="username">
Password: <input type="password" name="pass">
</form>
</body>
</html>
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class LoginDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
String name=request.getParameter("username"); //will return value
out.println("Welcome "+name);
out.close();
}
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Servlet Terminology Description
Website: static vs dynamic It is a collection of related web pages that may
contain text, images, audio and video.
HTTP It is the data communication protocol used to
establish communication between client and server.
HTTP Requests It is the request send by the computer to a web
server that contains all sorts of potentially
interesting information.
Get vs Post It gives the difference between GET and POST
request.
Container It is used in java for dynamically generating the
web pages on the server side.
Server: Web vs Application It is used to manage the network resources and for
running the program or software that provides
services.
Content Type It is HTTP header that provides the description
about what are you sending to the browser.
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. We will develop a servlet that illustrates
their use.
Servlets parse the form(client) data 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.
• Client pass some information from browser to web server uses GET Method or POST
Method.
• If a client send the data to the servlet, that data will be available in the object of
HttpServletRequest interface. In case of getParameter() method we have to pass input
parameter name and it will give the value.