Chap 3
Chap 3
V BCA
Module III: Java Servlets
Life Cycle of a Servlet
Using Tomcat for Servlet
Development
A Simple Servlet
The Servlet API
Servlet packaging
What is a Java Servlet?
service() method
destroy() method
SERVLET LIFE CYCLE
1. init() method
SERVLET LIFE CYCLE (CONTD.)
1. service() method
SERVLET LIFE CYCLE (CONTD.)
doGet() shall be used when small amount of data and insensitive data like a query has to be sent as a request.
SERVLET LIFE CYCLE (CONTD.)
2b. doPost()
doPost() shall be used when comparatively large amount of sensitive data has to be sent.
SERVLET LIFE CYCLE (CONTD.)
Destroy()
Life Cycle of a Servlet
❑The browser then generates an HTTP request for this URL. This
request is then sent to the appropriate server
❑This method is invoked only when the servlet is first loaded into
memory
❑You will see that it is possible for the servlet to read data that has
been provided in the HTTP request
❑Finally, the server may decide to unload the servlet from its
memory
❑The memory allocated for the servlet and its objects can then be
garbage collected
USING TOMCAT FOR SERVLET DEVELOPMENT
❑Basic steps
2. Start Tomcat.
❑Then println( ) is used to write some simple HTML source code as the
HTTP response
❑Compile this source code and place the HelloServlet.class file in the
Tomcat class files directory
A Simple Servlet
❑Start Tomcat
Interface Description
Class Description
❑Servlet Interface
Method Description
Method Description
Method Description
void log(String s, Throwable e) Write s and the stack trace for e to the
servlet log.
void setAttribute(String attr, Object Sets the attribute specified by attr to the
val) value passed in val.
Object getAttribute(String attr) Returns the value of the attribute
named attr.
String getCharacterEncoding( ) Returns the character encoding of
the request.
The Servlet API
❑The ServletRequest
Method Description
Method Description
void setContentType(String type) Sets the content type for the response to
type.
The Servlet API
❑Methods :- int readLine(byte[] b, int off, int len) it reads the input
stream.
The Servlet API
❑ echo
❑ Printenv
❑ config
❑ fsize
❑ flastmod
❑ include
❑ set
❑ if elif endif else
19.13 COOKIES
HTTP is stateless.
This means that every HTTP request is different from others.
Sometimes, it is necessary to keep track of a sequence of
related requests sent by a client to perform some designated
task.
This is called session tracking.
Cookies are one of the solutions to session tracking.
COOKIES (CONTD.)
Filters are objects that are installed between the client and the
server to inspect requests and responses.
They can transform the request or modify the response or
both.
The filters are not servlets and hence cannot create actual
responses.
Filters process requests before they reach a servlet and/or
process responses after leaving a servlet.
FILTERS (CONTD.)
Servlets are not useful for generating presentation content such as HTML. If the size of the
HTML document is large, it is a tedious process.
Another drawback of the servlet over Java Server Pages (JSP) is that the source has to be
recompiled after any modification is done.
Moreover, the web server has to be restarted to see the effect of the modified code.
However, JSP can perform these tasks automatically.
Servlets often contain presentation logic as well as processing logic, which makes the code
difficult to read, understand and extend. If the presentation logic changes, the servlet code
has to be modified, recompiled, and redeployed.
19.16 SECURITY ISSUES
Servlet Packaging
Here you’ll learn about
(http://www.htmlhelp.com/tools/validator)
❑Form data can be attached to the end of the URL after a question
mark for GET requests, or send to the server on a separate line for
POST requests
Handling Client Request: Form Data
Reading form data from servlets
❑getParameter()
❑getParameterValues()
❑getParameterNames()
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: Form Data
Reading form data from servlets
Handling Client Request: HTTP
Request Headers
HTTP Request Headers
❑HTTP information that is sent from the browser to the server in
the form of request headers
❑Form data results directly from user input and is sent as part of
the URL for GET requests and on a separate line for POST requests
❑Syntax:
public void setHeader(string headername, int headervalue)
❑Example: response.setHeader(“Refresh”, 5);
❑You must set the headers before the first use of the PrintWriter or
OutputStream that transmits the document content
Generating Server Response: HTTP
Response Headers
❑HttpServletResponse also has two specialized methods to set
headers that contain dates and integers
sendRedirect() Sets Location header (as well as sets the status code)
HTTP 1.1 Response Headers
Header Name Meaning
Accept-Ranges tells the client whether or not you accept Range request headers.
Age is used by proxies to indicate how long ago the document was generated by
the original server.
Allow specifies the request methods (GET, POST, etc.)
Cache-Control • the circumstances in which the response document can safely be cached.
Pragma • It can have values public, private or no-cache.
» Public means document is cacheable,
» Private means document is for a single user and can only be stored in
private caches
» no-cache means document should never be cached.
Connection instructs the browser whether to use persistent in HTTP connections or not.
Content-Encoding indicates the way in which the page was encoded during transmission.
HTTP 1.1 Response Headers
Header Name Meaning
Content-Language This header signifies the language in which the document is written. Example:
en, en-us, ru, etc.
Content-Length indicates the number of bytes in the response.
Content-Location • supplies an alternative address for the requested document.
• Content-Location is informational;
Content-Range is sent with partial-document responses and specifies how much of the total
document was sent
Content-Type • gives the MIME type of the response document.
• The default MIME type for servlets is text/plain
Example: application/zip:- Zip archive
image/gif:- GIF image
text/html:- HTML document
video/mpeg:- MPEG video clip
Date specifies the current date in GMT format.
HTTP 1.1 Response Headers
Handling Cookies
Session Tracking
Handling Cookies
Cookies are small bits of textual information that a web server sends
to a browser and that browser returns unchanged when later visiting
the same website or domain
Cookies are text files stored on the client computer and they are
kept for various information tracking purpose
❑Customizing a site
❑Focusing advertising
Handling Cookies
❑Cookies are not a serious security threat but they can present a
significant threat to privacy
❑Since browsers generally only accept 20 cookies per site and 300
cookies total and since each cookie can be limited to 4 kilobytes,
cookies cannot be used to fill up someone’s disk or launch other
denial of service attacks
Handling Cookies
Constructors Description
Before adding the cookie to the outgoing headers, you can set
various characteristics of the cookie by using
setXxx methods
getXxx methods
public String getName( ) This pair of methods gets or sets the name of the cookie.
public void setName(String
cookieName)
Handling Cookies
Methods Description
public String getPath( ) These methods get or set the path to which the cookie applies. If you
public void setPath(String don’t specify a path, the browser returns the cookie only to URLs in or
path) below the directory containing the page that sent the cookie.
public boolean getSecure( ) This pair of methods gets or sets the Boolean value indicating whether
public void setSecure(boolean the cookie should only be sent over encrypted (i.e., SSL) connections.
secureFlag) The default is false; the cookie should apply to all connections.
public String getValue( ) The getValue method looks up the value associated with the cookie;
public void setValue(String The setValue method specifies it.
cookieValue)
public int getVersion( ) These methods get/set the cookie protocol version the cookie complies
public void setVersion(int with. Version 0, the default, follows the original Netscape specification
version) Version 1, not yet widely supported
Handling Cookies
Creating Cookie
Cookie[ ] ck = request.getCookies( );
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue();
}
6. Removing Cookies
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
Session Tracking
1. Cookies
2. URL- Rewriting
4. HttpSession
Session Tracking
1. Cookies ❑Cookies are small pieces of information that are sent in response from
the web server to the client
❑Cookies are stored on client's computer. They have a lifespan and are
destroyed by the client browser at the end of that lifespan
Advantage of cookie
Disadvantage of cookie
2. URL- Rewriting
Disadvantage of URL-Rewriting
4. HTTP Session
❑HttpSession object is used to store entire session with a
specific client
Creating a session
HttpSession session =request.getSession();
// getsession() method returns a session. If the session already
exists, it returns the existing session else create a new session
Destroying a session
session.invalidate( ); //destroy a session
Session Tracking
These methods extract a previously stored value from a session object. They return null if there is no
value associated with the given name. getAttribute is preferred and getValue is deprecated.
2 public void putValue(String name, Object value)
public void setAttribute(String name, Object value)
These methods associate a value with a name. Use putValue with servlets and either setAttribute
(preferred) or putValue (deprecated) with version 2.2 servlets.
3 public void removeValue(String name)
public void removeAttribute(String name)
These methods remove any values associated with the designated name. If the value being removed
implements HttpSessionBindingListener, its valueUnbound method is called.
Session Tracking
Methods in HTTP Session class
These methods return the names of all attributes in the session. Use getValueNames in version 2.1
of the servlet specification. In version 2.2, getValueNames is supported but deprecated; use
getAttributeNames instead.
5 public String getId()
This method returns the unique identifier generated for each session. It is sometimes used as the
key name when only a single value is associated with a session, or when information about sessions
is being logged.
6 public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)
These methods get or set the amount of time, in seconds, that a session should go without access
before being automatically invalidated. A negative value indicates that the session should never time
out