This document provides an overview of web application development and servlet technology. It discusses the history and evolution of web pages to dynamic web applications. It then defines web applications and the request-response model. Common Gateway Interface (CGI) is introduced as the first technique for dynamic content, along with its limitations which led to the creation of servlets. Key servlet concepts like the servlet interface, generic servlet, HTTP servlet, and servlet lifecycle methods are covered. The document also examines the HttpServletRequest and HttpServletResponse interfaces and their various methods. Finally, it discusses session tracking approaches including cookies and the session API.
1. History of web application
There are 4 components involved
Webpage
Website
Web Browser
Web Server
Earlier, a web page merely displayed static content (html)
But, today’s web application provides interactive experience as if
users are talking face to face (dynamic content).
Chatting
Online shopping
Online reservation
and the list keeps on increasing………….
2. Web Application
What is web application?
Application that runs on WWW is known as web
application.
How does it work?
Request
Response
Client
Server
3.
4. Common Gateway interface
It was the first technique for creating dynamic
content.
With CGI, server passes the request to CGI
program and the o/p is sent to the client
Request
Response
Client
Server
5. Limitations
It creates a new process to run CGI program.
It requires time and significant server resources.
Number of request cannot be handled
concurrently.
Process for CGI 1
Process for CGI 2
Process for CGI 1
Request for CGI 1
Request for CGI 2
Request for CGI 1
Server
6.
7. Limitations
It creates a single process for each CGI program.
It requires time and significant server resources.
Request for CGI 1
Process for CGI 1
Request for CGI 2
Request for CGI 1
Process for CGI 2
Server
8.
9. Definition
Servlet is a Java class that extends the
functionality of web server.
Eg:
Mail Server
Servlet is a class that performs virus scan to attached
files.
10. Benefits
Only one copy of servlet is loaded into JVM.
Each request begins a new thread to servlet than a
process.
Saves time
Response time increases
It is scalable
JVM
Request for Servlet 1
Request for Servlet 2
Request for Servlet 1
Servlet1
thread
Servlet2
13. Servlet Implementation
Servlet use classes and interfaces from 2
packages
javax.servlet
It contains classes to support generic protocol
javax.servlet.http
It extends classes in servlet package to add HTTP
specific functionality.
16. Servlet API
Servlet Interface
GenericServlet Class
HttpServlet Class
HttpServletRequest Interface
HttpServletResponse Interface
Cookie Class
HttpSession Interface
SingleThreadModel Interface
ServletException class
UnavailableException class
ServletContext interface
ServletConfig Interface
17. Servlet Interface
Every servlet must implements the
javax.servlet.Servlet interface.
It can implement in 2 ways:
Directly implementing interface
Extending any of 2 classes:
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
19. service()
Syntax:
public abstract void service(ServletRequest
req,ServletResponse res) throws
ServletException,IOException
It is called whenever the request is made
It must be overridden in servlet
It receives request via ServletRequest and Sends
response via Servlet Response
20. GenericServlet
It provides basic implementation of the
servlet interface for protocol-independent
servlets.
It has init() and destroy() methods to perform
setup and clean-up tasks.
service() method is defined abstract and must
be overidden.
22. HttpServlet
It is an abstract class that is used for
developing HTTP servlets.
It does not override the service() method.
It overrides doGet() to handle GET requests
and doPost() to handle POST requests
27. getParameter()
Syntax:
Public abstract String getParameter(String name)
Description:
Returns value of the named parameter as a string
Returns null if the parameter does not exist or empty
string.
Eg:
String name=req.getParameter(“t1”) //t1 is name of text box
30. Enumeration Methods
hasMoreElements()
Public boolean hasMoreElements()
Returs true if and only if this enumeration object contains at least one
more element to provide; false otherwise.
Eg: while(en.hasMoreElements())
{
}
nextElement()
Public Object nextElement()
Returns the next element of this enumeration if this enumeration object
has at least one more element to provide.
Throws: NoSuchElementException - if no more elements exist.
Eg: en.nextElement()
31. getHeader()
Syntax:
Public String getHeader(String name)
Description
Returns the value of the named header as a string
It takes name of header and retrieve the value of header
Eg:
String val=req.getHeader(name of header)
38. setAttribute()
Syntax:
Public void setAttribute(String name.String value)
Description
It set new attribute of server
It takes 2 argumnets
Name
Value
The new value is appended to the Enumeration returned by
getAttributeNames() method
39. Cookies
Cookie is a bit of information sent by a
webserver to a browser that can be later read
back from that browser.
Cookie class
javax.servlet.http.Cookie class is provided by
servlet API
40. Creating cookie
Cookie can be created with cookie()
constructor
public cookie(String name,String value)
It creates new cookie with initial name and
value.
Eg:
Cookie ck = new Cookie(“emailid”,”abc”);
41. Sending a cookie
Sending - Response
A servlet can send a cookie to client by
passing a cookie object to
addCookie() method of HttpServletResponse
interface.
public void addcookie(Cookie obj);
Eg:
res.addCookie(ck);
42. Reading a cookie
Reading –request
A servlet retrieves cookies by calling
getCookies() method of HttpServletRequest
inerface
Public Cookie[] getCookies();
Returns array of cookie object sent by
browser or null if no cookies are sent
43. Attributes of Cookies
Attribute
Description
Name
Name of cookie
Value
Value of cookie
Version
Set version of cookie
Domain
Domain name that will read a cookie
MaxAge
Expiry date in seconds
-ve value indicates default, it will
expire when browser is closed
0 indicates to delete immediately
Path
Path where cookie is sent
Secure
Boolean value true/false
comment
Comment about it
Attributes can be set and retrieved by setXXX() and getXXX() method of Cookie class
46. setContentType()
Syntax:
Public abstract void setContentType(String type)
Description
It sets the content type of the response to be
specified type.
It sets the Content-type HTTP header
res.setContentType(“text/html”)
47. addCookie
Syntax:
Public abstract void addCookie(Cookie ck)
Description:
Add the specified cookie to the response.
Browsers accept only 20 cookies per site,300 total
per user and size cookie’s size 4096 bytes.
res.addCookie(ck)
48. sendRedirect()
Syntax:
Public abstract void sendRedirect(String location)
throws IOException
Description:
Redirects the response to the specified location.
The location must be absolute URL
Eg:
res.sendRedirect(“http://localhost:8084/test”)
49. encodeURL()
Syntax:
Public abstract String encodeURL(String url)
Description:
Returns specified URL encoded to include the
session information.
String url=res.encodeURL(“http://localhost:8084/test?id=123”)
res.sendRedirect(url);
50. setHeader()
Syntax:
Public abstract void setHeader(String name,String
value)
Description:
Sets the value of the named header as String.
If header has already been set, the new value
overwrites the previous one.
res.setHeader(“Set-Cookie”,”ck”);
51. setStatus()
Syntax:
Public abstract void setStatus(int sc)
Public abstract void setStatus(int sc, String sm)
Description:
It sets HTTP status code.
The code can be specified using numeric value or by using
SC_XXX codes.
res.setStatus(404)
res.setStatus(404,”Sorry ! File not found”)
52. SC_XXX codes
Constants defined in HttpServletResponse
SC_OK
SC_NOT_FOUND
SC_INTERNAL_SERVER_ERROR
SC_BAD_REQUEST
200
404
500
400
53. Session
Session is period between user login and
logout.
Login
Session
logout
Session data should be available in all the
pages after user logins until he logs out.
54. Session Tracking Approaches
HTTP is stateless protocol
To maintain the state of user 4 approaches
are used
Hidden form fields
URL Rewriting
Cookies
Session API
55. Hidden Fields
Hidden fields are not displayed on browser.
They are sent to the sever when the form is
submitted
Eg:
<form action=“login”>
<input type=“hidden” name=“t1” value=“abc”>
</form>
String name=req.getParameter(“t1”);
57. URL Rewriting
With this method, URL can be dynamically
modified or rewritten to include extra
information.
http://localhost:8084/test
http://localhost:8084/test/123
http://localhost:8084/test?id=123
URL
extra path
extra parameter
58. Limitation
Limit to size of URL (255 char)
It cannot be used if method used by target
URL is POST
Parameter name collision might occur
60. Session API
Session tracking is efficient method of
handling session
Every user of a site is associated with a
javax.servlet.http.HttpSession object
A servlet uses its request object’s getSession()
method to retrieve the current session
61. getSession()
Syntax:
Public HttpSession getSession(boolean create)
Description
It returns the current session associated with the user.
If user has not created session, it will create if true is passed
as an argument or returns null if false is passed
To enable session, this method must be called at least once
before any output is written.
HttpSession ses=req.getSession(true);
63. setAttribute()
Syntax:
Public abstract void setAttribute(String name,Object
value)
Description:
Binds the specified object value under specified name in the
session.
Eg:
ses.setAttribute(“id”,”abc”)
64. getAttribute()
Syntax:
Public abstract object getAttribute(String name)
Description:
Returns the object bound in the session under the
specified name or null if session is invalid.
String val=(String)ses.getAttribute(id);
// output abc
65. getAttributeNames()
Syntax:
Public abstract Enumeration getAttributeNames()
Description
Return the enumeration of all names of attributes or null
if not attributes are set
Eg:
Enumeration en=ses.getAttributeNames()
While(en.hasMoreElements())
{
String name=(String)en.nextElement()
}
70. getLastAccessTime()
Syntax:
Public abstract long getLastAccessTime()
Description
Returns the time at which the client last sent a
request with this session, as a long representing
the number of milliseconds since epoch.
72. HTTP Request Methods
doDelete()
Syntax:
protected void doDelete(HttpServletRequest
req,HttpServletResponse res) throws
ServletException,IOException
The delete method is used to delete the
documents directly from the server
76. SingleThreadModel interface
It is defined in javax.servlet package
Syntax:
Public interface SingleThreadModel{
}
If a servlet implements this interface,
The server ensures that each instance of the
servlet handles only one service request at a time.
78. ServletException
It is a class which handles generic exception
thrown by servlet encountering difficulties.
Class Summary
Public class ServletException extends
Exception
{
public ServletException();
public ServletException(String message);
}
79.
Constructs a new ServletException with an
optional descriptive message.
If message is specified, it can be retrieved
using getMessage() method.
80. UnaviableException
A servlet can throw an unavailable exception
at any time to indicate that it is not available
to service client requests
There are 2 types of unavailability
Permanent
Temporary
81. Class Summary
public class UnavailableException extends
ServletException
{
public UnavailableException (int sec,Servlet servlet, String msg)
public UnavailableException(Servlet sevlet,String msg)
public Servlet getServlet()
public int getUnavailableSeconds()
public boolean isPermanent()
}
82. Methods
Public Servlet getServlet()
Public int getUnavailableSeconds()
Returns the servlet that threw this exception
Returns number of seconds for which servlet will
be unavaiable. A –ve value indicated permanent
unavailability.
Public boolean isPermanent()
Returns true if the servlet is unavailable indefintely
83. Servlet Life Cycle
Servlet consist of following cycle
Create and initialize the servlet
Handle zero or more service calls from clients
init()
doGet() or doPost()
Destroy the servlet and then garbage collect it
destroy()
84. Init()
Syntax:
Public void init(ServletConfig config) throws
ServletException
It is used to initialize variables and objects that are
used throughout the java Servlet.
The servletConfig object supplies a servlet with
information about its initialization (init parameters)
available to servlet and not with request
85. ServletConfig() interface
It is used to pass initialization and context
information to servlets
Methods
public abstract String getInitParameter(String name)
public abstract Enumeration getInitParameterNames()
Public abstract ServletContext getServletContext()
87. Destroy()
Public void destroy()
Called when servlet is preparing to unload a
servlet.
Used to clean up any outstanding resources
(database connection, threads, file handle)
88. What is Context?
In terms of Servlet, a context is a directory that
contains a single web application
a set of related html files
JavaBeans
JSP files and/or servlets
The terms context and webapp are pretty much
synonymous. A context directory may contain one or more
servlets.
The ServletContext interface defines methods that can be
used in non-request specific manner.
ServletContext sc=this.getServletContext();
92. getInitParameter()
Syntax:
Public String getInitParameter(String name)
Description:
Context parameters can be used in entire web
application not in specific servlet unlike init
parameter of Config object.
It returns a string containing the value of specified
parameter or null if no init parameter exists.
94. setAttribute()
Syntax:
Public abstract void setAttribute(String name,Object
value)
Description:
Binds the specified object value under specified name in the
context
Eg:
sc.setAttribute(“id”,”abc”)
95. getAttribute()
Syntax:
Public abstract object getAttribute(String name)
Description:
Returns the object bound in the context under the
specified name.
String val=(String)sc.getAttribute(“id”);
// output abc
97. Attributes
Request
Attributes are objects associated with a request. Attributes may
be set by the a servlet to communicate information to another
servlet (via the RequestDispatcher).
Session
A servlet can bind an object attribute into an HttpSession
implementation by name. Any object bound into a session is
available to any other servlet that handles a request identified as
being a part of the same session.
Context
A servlet can bind an object attribute into the context by name.
Any attribute bound into a context is available to any other servlet
that is part of the same Web application.
99. RequestDispatcher() interface
Defines an object that receives requests from the
client and sends them to any resource on the
server. A single client request can be passed to
many resoruce such as:
servlet
HTML file
JSP file
Methods
forward()
include()
100. forward()
Syntax:
public void forward(ServletRequest request, ServletResponse
response) throws ServletException, IOException
Forwards a request from a servlet to another resource (servlet,
JSP file, or HTML file) on the server.
forward should be called before the response has been
committed to the client.
If the response already has been committed, this method throws
an IllegalStateException. Uncommitted output in the response
buffer is automatically cleared before the forward.
rd.forward(req,res)
101. include()
Syntax:
public void include(ServletRequest request, ServletResponse
response) throws ServletException, IOException
Includes the content of a resource (servlet, JSP page, HTML file)
in the response.
The ServletResponse object has its path elements and
parameters remain unchanged from the caller's. The included
servlet cannot change the response status code or set headers;
any attempt to make a change is ignored.
rd.include(req, res);