SlideShare a Scribd company logo
1 of 46
Download to read offline
Unit III
Servlets
Dr. Vasanti Dutta
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. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side programming
language. However, there were many disadvantages to this
technology.
• There are many interfaces and classes in the Servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
Class notes for Servlet by Dr. V. Dutta 2
Servlet Features
• 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.
Class notes for Servlet by Dr. V. Dutta 3
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.
• 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.
• 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.
Class notes for Servlet by Dr. V. Dutta 4
Basic architecture of web application and depicts where HTTP stands.
Class notes for Servlet by Dr. V. Dutta 5
HTTP
• 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.
• 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.
• 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.
Class notes for Servlet by Dr. V. Dutta 6
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.Class notes for Servlet by Dr. V. Dutta 7
Static Website Dynamic Website
Prebuilt content is same every
time the page is loaded.
Content is generated quickly and
changes regularly.
It uses the HTML code for
developing a website.
It uses the server side languages such
as PHP,SERVLET, JSP, and
ASP.NET etc. for developing a website.
It sends exactly the same
response for every request.
It may generate different HTML for
each of the request.
The content is only changed
when someone publishes and
updates the file (sends it to the
web server).
The page contains "server-side" code
which allows the server to generate the
unique content when the page is loaded.
Flexibility is the main
advantage of static website.
Content Management System (CMS) is
the main advantage of dynamic website.
Class notes for Servlet by Dr. V. Dutta 8
HTTP is request/response protocol which is based on client/server
based architecture. In this protocol, web browser, search engines, etc.
behave as HTTP clients and the Web server like Servlet behaves as a
server
Class notes for Servlet by Dr. V. Dutta 9
The HTTP client sends the request to the server in the form of
request message which includes following information:
• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header
The HTTP request method indicates the method to be performed on
the resource identified by the Requested URI (Uniform Resource
Identifier).
Class notes for Servlet by Dr. V. Dutta 10
HTTP
Request
Description
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like
GET request with extra info sent with the request.
HEAD Asks for only the header part of whatever a GET would
return. Just like GET but with no body.
TRACE Asks for the loopback of the request message, for testing
or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested
URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at
the request URL can respond
Class notes for Servlet by Dr. V. Dutta 11
GET POST
1) In case of Get request,
only limited amount of data can be
sent because data is sent in header.
In case of post request, large
amount of data can be sent
because data is sent in body.
2) Get request is not secured
because data is exposed in URL bar.
Post request is secured because
data is not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be
bookmarked.
4) Get request is idempotent. i.e
second request will be ignored until
response of first request is delivered
Post request is non-
idempotent.
5) Get request is more efficient and
used more than Post.
Post request is less efficient and
used less than get.Class notes for Servlet by Dr. V. Dutta 12
Class notes for Servlet by Dr. V. Dutta 13
CGI
• 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.
There are many problems in CGI technology (Disadvantages):
• If the number of clients increases, it takes more time for
sending the response.
• For each request, it starts a process, and the web server is
limited to start processes.
• It uses platform dependent language e.g. C, C++, perl.
Class notes for Servlet by Dr. V. Dutta 14
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. The
advantages of Servlet are as follows:
• 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.
Class notes for Servlet by Dr. V. Dutta 15
Class notes for Servlet by Dr. V. Dutta 16
Class notes for Servlet by Dr. V. Dutta 17
Servlet Container
• It provides the runtime environment for JavaEE (j2ee)
applications. The client/user can request only a static
WebPages from the server. If the user wants to read the web
pages as per input then the servlet container is used in java.
• The servlet container is the part of web server which can be
run in a separate process. We can classify the servlet container
states in three types:
Class notes for Servlet by Dr. V. Dutta 18
• The servlet container is the part of web server which can be
run in a separate process. We can classify the servlet container
states in three types:
• Standalone: It is typical Java-based servers in which the
servlet container and the web servers are the integral part of a
single program. For example:- Tomcat running by itself
• In-process: It is separated from the web server, because a
different program runs within the address space of the main
server as a plug-in. For example:- Tomcat running inside the
JBoss.
• Out-of-process: The web server and servlet container are
different programs which are run in a different process. For
performing the communications between them, web server
uses the plug-in provided by the servlet container.
Class notes for Servlet by Dr. V. Dutta 19
Servlet Container functions
• Life Cycle Management
• Multithreaded support
• Object Pooling
• Security etc.
Class notes for Servlet by Dr. V. Dutta 20
Server
• Server is a device or a computer program that accepts and
responds to the request made by other program, known as
client. It is used to manage the network resources and for
running the program or software that provides services.
There are two types of servers:
• Web Server (Apache Tomcat and Resin etc). : It can be used
for servlet, jsp, struts, jsf etc. It can't be used for EJB.
• Application Server: It contains Web and EJB containers. It can
be used for servlet, jsp, struts, jsf, ejb etc. It is a component
based product that lies in the middle-tier of a server centric
architecture. Examples : Jboss, Glassfish, Weblogic,
Websphere.
Class notes for Servlet by Dr. V. Dutta 21
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.
Class notes for Servlet by Dr. V. Dutta 22
Interfaces and Classes in javax.servlet package
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
Class notes for Servlet by Dr. V. Dutta 23
Interfaces and Classes in javax.servlet.http
package
• HttpServletRequest
• HttpServletResponse
• HttpSession
• HttpSessionListener
• HttpSessionAttributeListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext
(deprecated now)
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils (deprecated now)
Class notes for Servlet by Dr. V. Dutta 24
Class notes for Servlet by Dr. V. Dutta 25
Methods of Servlet Interface
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
request,ServletResponse
response)
provides response for the incoming
request. It is 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.
Class notes for Servlet by Dr. V. Dutta 26
Functions of Web-Container
• loads the servlet class.
• instantiates the servlet class.
• calls the init method passing the ServletConfig object
else
• 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.
Class notes for Servlet by Dr. V. Dutta 27
Steps : Web container handling the request
 maps the request with the servlet in the web.xml file.
 creates request and response objects for this request
 calls the service method on the thread
 The public service method internally calls the protected
service method
 The protected service method calls the doGet method
depending on the type of request.
 The doGet method generates the response and it is passed to
the client.
 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.
Class notes for Servlet by Dr. V. Dutta 28
Class notes for Servlet by Dr. V. Dutta 29
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
}}
Steps for creating Servlet in Eclipse
1) For creating a dynamic web project click on File Menu -> New -> Project..->
Web -> dynamic web project -> write your project name e.g. first -> Finish.
2) For creating a servlet, explore the project by clicking the + icon -> explore the
Java Resources -> right click on src -> New -> servlet -> write your servlet name
e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -> Build Path -> Configure Build
Path -> click on Libraries tab in Java Build Path -> click on Add External JARs
button -> select the servlet-api.jar file under tomcat/lib -> ok.
4) Start the server and deploy the project:
For starting the server and deploying the project in one step, Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll ->
finish.
5) Now tomcat server has been started and project is deployed. To access the servlet
write the url pattern name in the URL bar of the browser. In this case Hello then
enter.
Class notes for Servlet by Dr. V. Dutta 30
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header information, attributes etc. Its
methods are:
public String getParameter(String name): is used to obtain the value of a parameter by name.
public String[] getParameterValues(String name): returns an array of String containing all
values of given parameter name. It is mainly used to obtain values of a Multi select list box.
java.util.Enumeration getParameterNames():returns an enumeration of all of the request
parameter names.
public int getContentLength():Returns the size of the request entity data, or -1 if not known.
public String getCharacterEncoding():Returns the character set encoding for the input of this
request.
public String getContentType():Returns the Internet Media Type of the request entity data, or
null if not known.
public ServletInputStream getInputStream() throws IOException: Returns an input stream for
reading binary data in the request body.
public abstract String getServerName() :Returns the host name of the server that received the
request.
public int getServerPort(): Returns the port number on which this request was received.
Class notes for Servlet by Dr. V. Dutta 31
Example of ServletRequest to display the name of the user
1) index.html
<form action="welcome" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>
Class notes for Servlet by Dr. V. Dutta 32
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close(); }}
RequestDispatcher interface
The RequestDispatcher interface provides the facility of dispatching the
request to another resource it may be html, servlet or jsp. This interface
can also be used to include the content of another resource also. It is
one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
• public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:
Forwards a request from a servlet to another resource (servlet, JSP
file, or HTML file) on the server.
• public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException: Includes
the content of a resource (servlet, JSP page, or HTML file) in the
response.
Class notes for Servlet by Dr. V. Dutta 33
Class notes for Servlet by Dr. V. Dutta 34
The getRequestDispatcher() method
The getRequestDispatcher() method of ServletRequest interface
returns the object of RequestDispatcher. Syntax :
public RequestDispatcher getRequestDispatcher(String resource)
;
RequestDispatcher rd=request.getRequestDispatcher("servlet
2");
//servlet2 is the url-pattern of the second servlet
rd.forward(request, response);
//method may be include or forward
•
Class notes for Servlet by Dr. V. Dutta 35
Example of RequestDispatcher interface
• index.html file: for getting input from the user.
• Login.java file: a servlet class for processing the response. If
password is servet, it will forward the request to the welcome
servlet.
• WelcomeServlet.java file: a servlet class for displaying the
welcome message.
• web.xml file: a deployment descriptor file that contains the
information about the servlet.
Class notes for Servlet by Dr. V. Dutta 36
Class notes for Servlet by Dr. V. Dutta 37
Class notes for Servlet by Dr. V. Dutta 38
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
// WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n); } }
Class notes for Servlet by Dr. V. Dutta 39
//Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response); }
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response); } } }
Class notes for Servlet by Dr. V. Dutta 40
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Session Tracking
• Session tracking is a mechanism that servlets use to maintain state about
a series of requests from the same user (that is, requests originating from
the same browser) across some period of time. Sessions are shared among
the servlets accessed by a client.
• The HttpSession object is used for session management. A session
contains information specific to a particular user across the whole
application. When a user enters into a website (or an online application)
for the first time HttpSession is obtained via request.getSession(), the user
is given a unique ID to identify his session. This unique ID can be stored
into a cookie or in a request parameter.
• The HttpSession stays alive until it has not been used for more than the
timeout value specified in tag in deployment descriptor file( web.xml).
The default timeout value is 30 minutes, this is used if you don’t specify
the value in tag. This means that when the user doesn’t visit web
application time specified, the session is destroyed by servlet container.
The subsequent request will not be served from this session anymore, the
servlet container will create a new session.Class notes for Servlet by Dr. V. Dutta 41
Class notes for Servlet by Dr. V. Dutta 42
Cookies :A webserver can assign a unique session ID as a cookie to each
web client and for subsequent requests from the client they can be
recognized using the received cookie.
This may not be an effective way because many time browser does not
support a cookie, so not recommended to use this procedure to maintain
the sessions.
Class notes for Servlet by Dr. V. Dutta 43
Few methods of HttpSession
public void setAttribute(String name, Object value): Binds the
object with a name and stores the name/value pair as an attribute of
the HttpSession object. If an attribute already exists, then this
method replaces the existing attributes.
public Object getAttribute(String name): Returns the String
object specified in the parameter, from the session object. If no
object is found for the specified attribute, then the getAttribute()
method returns null.
public Enumeration getAttributeNames(): Returns an
Enumeration that contains the name of all the objects that are bound
as attributes to the session object.
public void removeAttribute(String name): Removes the given
attribute from session.
setMaxInactiveInterval(int interval): Sets the session inactivity
time in seconds. This is the time in seconds that specifies how long a
sessions remains active since last request received from client.
MyServlet2.java
and index.html
Class notes for Servlet by Dr. V. Dutta 44
index.html
<form action="login"> User Name:<input
type="text" name="userName"/><br/>
Password:<input type="password"
name="userPassword"/><br/>
<input type="submit" value="submit"/>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp); } }}
MyServlet1.java
Class notes for Servlet by Dr. V. Dutta 45
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setAttribute("upass",password);
pwriter.print("<a href='welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp); } }}
web.xml
Class notes for Servlet by Dr. V. Dutta 46
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

More Related Content

What's hot

Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsArun Gupta
 
Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java ProgrammingChris Schalk
 
Optimizing LAMPhp Applications
Optimizing LAMPhp ApplicationsOptimizing LAMPhp Applications
Optimizing LAMPhp ApplicationsPiyush Goel
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF WorkshopIdo Flatow
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 ConferenceRoger Kitain
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using PhpSudheer Satyanarayana
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2Gera Paulos
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web apiMaurice De Beijer [MVP]
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web APIDamir Dobric
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Gera Paulos
 
REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transferTricode (part of Dept)
 
Apache Thrift : One Stop Solution for Cross Language Communication
Apache Thrift : One Stop Solution for Cross Language CommunicationApache Thrift : One Stop Solution for Cross Language Communication
Apache Thrift : One Stop Solution for Cross Language CommunicationPiyush Goel
 
Proxy Server
Proxy ServerProxy Server
Proxy ServerNetwax Lab
 
Basic Server PPT (THDC)
Basic Server PPT (THDC)Basic Server PPT (THDC)
Basic Server PPT (THDC)Vineet Pokhriyal
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Peter R. Egli
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web ServiceHoan Vu Tran
 

What's hot (20)

Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 
Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java Programming
 
Optimizing LAMPhp Applications
Optimizing LAMPhp ApplicationsOptimizing LAMPhp Applications
Optimizing LAMPhp Applications
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
 
Servlet
ServletServlet
Servlet
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
 
HTML5 Refresher
HTML5 RefresherHTML5 Refresher
HTML5 Refresher
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web API
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)
 
REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transfer
 
Apache Thrift : One Stop Solution for Cross Language Communication
Apache Thrift : One Stop Solution for Cross Language CommunicationApache Thrift : One Stop Solution for Cross Language Communication
Apache Thrift : One Stop Solution for Cross Language Communication
 
Proxy Server
Proxy ServerProxy Server
Proxy Server
 
Basic Server PPT (THDC)
Basic Server PPT (THDC)Basic Server PPT (THDC)
Basic Server PPT (THDC)
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
 

Similar to Servlet classnotes

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt20521742
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overviewramya marichamy
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptMouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 

Similar to Servlet classnotes (20)

Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Servlets
ServletsServlets
Servlets
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Java part 3
Java part  3Java part  3
Java part 3
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
JAVA
JAVAJAVA
JAVA
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Ftp servlet
Ftp servletFtp servlet
Ftp servlet
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 

More from Vasanti Dutta

Networking lec1 4
Networking lec1 4Networking lec1 4
Networking lec1 4Vasanti Dutta
 
Networking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VIINetworking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VIIVasanti Dutta
 
Networking lecture1
Networking lecture1Networking lecture1
Networking lecture1Vasanti Dutta
 
Jcv course contents
Jcv course contentsJcv course contents
Jcv course contentsVasanti Dutta
 
Lecture notesmap
Lecture notesmapLecture notesmap
Lecture notesmapVasanti Dutta
 

More from Vasanti Dutta (6)

MCA-5 unit1
MCA-5 unit1MCA-5 unit1
MCA-5 unit1
 
Networking lec1 4
Networking lec1 4Networking lec1 4
Networking lec1 4
 
Networking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VIINetworking lectures unit 2, MCA VII
Networking lectures unit 2, MCA VII
 
Networking lecture1
Networking lecture1Networking lecture1
Networking lecture1
 
Jcv course contents
Jcv course contentsJcv course contents
Jcv course contents
 
Lecture notesmap
Lecture notesmapLecture notesmap
Lecture notesmap
 

Recently uploaded

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Dr. Mazin Mohamed alkathiri
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

Servlet classnotes

  • 2. 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. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. • There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc. Class notes for Servlet by Dr. V. Dutta 2
  • 3. Servlet Features • 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. Class notes for Servlet by Dr. V. Dutta 3
  • 4. 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. • 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. • 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. Class notes for Servlet by Dr. V. Dutta 4
  • 5. Basic architecture of web application and depicts where HTTP stands. Class notes for Servlet by Dr. V. Dutta 5
  • 6. HTTP • 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. • 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. • 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. Class notes for Servlet by Dr. V. Dutta 6
  • 7. 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.Class notes for Servlet by Dr. V. Dutta 7
  • 8. Static Website Dynamic Website Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website. Class notes for Servlet by Dr. V. Dutta 8
  • 9. HTTP is request/response protocol which is based on client/server based architecture. In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web server like Servlet behaves as a server Class notes for Servlet by Dr. V. Dutta 9
  • 10. The HTTP client sends the request to the server in the form of request message which includes following information: • The Request-line • The analysis of source IP address, proxy and port • The analysis of destination IP address, protocol, port and host • The Requested URI (Uniform Resource Identifier) • The Request method and Content • The User-Agent header • The Connection control header • The Cache control header The HTTP request method indicates the method to be performed on the resource identified by the Requested URI (Uniform Resource Identifier). Class notes for Servlet by Dr. V. Dutta 10
  • 11. HTTP Request Description GET Asks to get the resource at the requested URL. POST Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body. TRACE Asks for the loopback of the request message, for testing or troubleshooting. PUT Says to put the enclosed info (the body) at the requested URL. DELETE Says to delete the resource at the requested URL. OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond Class notes for Servlet by Dr. V. Dutta 11
  • 12. GET POST 1) In case of Get request, only limited amount of data can be sent because data is sent in header. In case of post request, large amount of data can be sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar. Post request is secured because data is not exposed in URL bar. 3) Get request can be bookmarked. Post request cannot be bookmarked. 4) Get request is idempotent. i.e second request will be ignored until response of first request is delivered Post request is non- idempotent. 5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.Class notes for Servlet by Dr. V. Dutta 12
  • 13. Class notes for Servlet by Dr. V. Dutta 13
  • 14. CGI • 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. There are many problems in CGI technology (Disadvantages): • If the number of clients increases, it takes more time for sending the response. • For each request, it starts a process, and the web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl. Class notes for Servlet by Dr. V. Dutta 14
  • 15. 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. The advantages of Servlet are as follows: • 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. Class notes for Servlet by Dr. V. Dutta 15
  • 16. Class notes for Servlet by Dr. V. Dutta 16
  • 17. Class notes for Servlet by Dr. V. Dutta 17
  • 18. Servlet Container • It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. • The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Class notes for Servlet by Dr. V. Dutta 18
  • 19. • The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: • Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself • In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. • Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container. Class notes for Servlet by Dr. V. Dutta 19
  • 20. Servlet Container functions • Life Cycle Management • Multithreaded support • Object Pooling • Security etc. Class notes for Servlet by Dr. V. Dutta 20
  • 21. Server • Server is a device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services. There are two types of servers: • Web Server (Apache Tomcat and Resin etc). : It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB. • Application Server: It contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. Examples : Jboss, Glassfish, Weblogic, Websphere. Class notes for Servlet by Dr. V. Dutta 21
  • 22. 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. Class notes for Servlet by Dr. V. Dutta 22
  • 23. Interfaces and Classes in javax.servlet package • Servlet • ServletRequest • ServletResponse • RequestDispatcher • ServletConfig • ServletContext • SingleThreadModel • Filter • FilterConfig • FilterChain • ServletRequestListener • ServletRequestAttributeListener • ServletContextListener • ServletContextAttributeListener GenericServlet ServletInputStream ServletOutputStream ServletRequestWrapper ServletResponseWrapper ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent ServletException UnavailableException Class notes for Servlet by Dr. V. Dutta 23
  • 24. Interfaces and Classes in javax.servlet.http package • HttpServletRequest • HttpServletResponse • HttpSession • HttpSessionListener • HttpSessionAttributeListener • HttpSessionBindingListener • HttpSessionActivationListener • HttpSessionContext (deprecated now) HttpServlet Cookie HttpServletRequestWrapper HttpServletResponseWrapper HttpSessionEvent HttpSessionBindingEvent HttpUtils (deprecated now) Class notes for Servlet by Dr. V. Dutta 24
  • 25. Class notes for Servlet by Dr. V. Dutta 25
  • 26. Methods of Servlet Interface 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 request,ServletResponse response) provides response for the incoming request. It is 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. Class notes for Servlet by Dr. V. Dutta 26
  • 27. Functions of Web-Container • loads the servlet class. • instantiates the servlet class. • calls the init method passing the ServletConfig object else • 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. Class notes for Servlet by Dr. V. Dutta 27
  • 28. Steps : Web container handling the request  maps the request with the servlet in the web.xml file.  creates request and response objects for this request  calls the service method on the thread  The public service method internally calls the protected service method  The protected service method calls the doGet method depending on the type of request.  The doGet method generates the response and it is passed to the client.  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. Class notes for Servlet by Dr. V. Dutta 28
  • 29. Class notes for Servlet by Dr. V. Dutta 29 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 }}
  • 30. Steps for creating Servlet in Eclipse 1) For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish. 2) For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish. 3) add jar file in eclipse IDE: For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok. 4) Start the server and deploy the project: For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish. 5) Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter. Class notes for Servlet by Dr. V. Dutta 30
  • 31. ServletRequest Interface An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header information, attributes etc. Its methods are: public String getParameter(String name): is used to obtain the value of a parameter by name. public String[] getParameterValues(String name): returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box. java.util.Enumeration getParameterNames():returns an enumeration of all of the request parameter names. public int getContentLength():Returns the size of the request entity data, or -1 if not known. public String getCharacterEncoding():Returns the character set encoding for the input of this request. public String getContentType():Returns the Internet Media Type of the request entity data, or null if not known. public ServletInputStream getInputStream() throws IOException: Returns an input stream for reading binary data in the request body. public abstract String getServerName() :Returns the host name of the server that received the request. public int getServerPort(): Returns the port number on which this request was received. Class notes for Servlet by Dr. V. Dutta 31
  • 32. Example of ServletRequest to display the name of the user 1) index.html <form action="welcome" method="get"> Enter your name<input type="text" name="name"><br> <input type="submit" value="login"> </form> Class notes for Servlet by Dr. V. Dutta 32 import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class DemoServ extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); String name=req.getParameter("name");//will return value pw.println("Welcome "+name); pw.close(); }}
  • 33. RequestDispatcher interface The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration. There are two methods defined in the RequestDispatcher interface. • public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. • public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP page, or HTML file) in the response. Class notes for Servlet by Dr. V. Dutta 33
  • 34. Class notes for Servlet by Dr. V. Dutta 34
  • 35. The getRequestDispatcher() method The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax : public RequestDispatcher getRequestDispatcher(String resource) ; RequestDispatcher rd=request.getRequestDispatcher("servlet 2"); //servlet2 is the url-pattern of the second servlet rd.forward(request, response); //method may be include or forward • Class notes for Servlet by Dr. V. Dutta 35
  • 36. Example of RequestDispatcher interface • index.html file: for getting input from the user. • Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet. • WelcomeServlet.java file: a servlet class for displaying the welcome message. • web.xml file: a deployment descriptor file that contains the information about the servlet. Class notes for Servlet by Dr. V. Dutta 36
  • 37. Class notes for Servlet by Dr. V. Dutta 37
  • 38. Class notes for Servlet by Dr. V. Dutta 38 index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> // WelcomeServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); } }
  • 39. Class notes for Servlet by Dr. V. Dutta 39 //Login.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } }
  • 40. Class notes for Servlet by Dr. V. Dutta 40 web.xml <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
  • 41. Session Tracking • Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. Sessions are shared among the servlets accessed by a client. • The HttpSession object is used for session management. A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session. This unique ID can be stored into a cookie or in a request parameter. • The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session.Class notes for Servlet by Dr. V. Dutta 41
  • 42. Class notes for Servlet by Dr. V. Dutta 42 Cookies :A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way because many time browser does not support a cookie, so not recommended to use this procedure to maintain the sessions.
  • 43. Class notes for Servlet by Dr. V. Dutta 43 Few methods of HttpSession public void setAttribute(String name, Object value): Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then this method replaces the existing attributes. public Object getAttribute(String name): Returns the String object specified in the parameter, from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null. public Enumeration getAttributeNames(): Returns an Enumeration that contains the name of all the objects that are bound as attributes to the session object. public void removeAttribute(String name): Removes the given attribute from session. setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is the time in seconds that specifies how long a sessions remains active since last request received from client.
  • 44. MyServlet2.java and index.html Class notes for Servlet by Dr. V. Dutta 44 index.html <form action="login"> User Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPassword"/><br/> <input type="submit" value="submit"/> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); HttpSession session=request.getSession(false); String myName=(String)session.getAttribute("uname"); String myPass=(String)session.getAttribute("upass"); pwriter.print("Name: "+myName+" Pass: "+myPass); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
  • 45. MyServlet1.java Class notes for Servlet by Dr. V. Dutta 45 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Hello "+name); pwriter.print("Your Password is: "+password); HttpSession session=request.getSession(); session.setAttribute("uname",name); session.setAttribute("upass",password); pwriter.print("<a href='welcome'>view details</a>"); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
  • 46. web.xml Class notes for Servlet by Dr. V. Dutta 46 <web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>