Servlet Programming
Download
Report
Transcript Servlet Programming
Servlet
Programming
The Requirements of server-side programs
Server-side programs run on a middle-tier web server
It acts as a middle layer between a request coming from a
Web browser or other HTTP client and databases or
applications on the HTTP server.
Returning pre-built documents can satisfy many client
requests.
For Example a search engine displays different contents
based on the query, or when the Web page is derived
from data that changes frequently.
The middle-tier need not execute any program to
accomplish this type of request.
Major Responsibilities of server-side
Programs
The program should be able to read the data sent by the
client. Information is transmitted using a HTML form, a
Java Applet or any other HTTP client.
The backend program should be able to gather
information regarding the browser capabilities, the client
machine details and so on.
The backend programs works on a cycle of requestprocess-response. The process requires database
interaction, using remote objects and computation.
The backend program should be able to create HTML
documents dynamically based on the request and send
the newly generated HTML documents to the client.
It must indicate to the browser regarding the document
being returned through HTTP response parameters.
What is a Servlet
Servlets are modules of Java code that run in a
server application on the middle-tier (hence the
name "Servlets", similar to "Applets" on the
client side) to answer client requests.
Servlets are not tied to a specific client-server protocol
but they are most commonly used with HTTP and the
word "Servlet" is often used in the meaning of "HTTP
Servlet".
Since Servlets are written in the portable Java language
and follow a standard framework, they provide a means
to create sophisticated server extensions in a server
and operating system independent way.
Servlets: A Bird’s Eye-view
What is a Servlet Container
A standalone Java program is directly invoked by the
end user and starts its execution from the main method.
But in case of a servlet the client makes a http request
to the Web-Server in order to execute the servlet.
For the servlet to execute it has to be loaded in the
memory, receive the client request and respond back to
the client. These responsibilities are carried out by a
service known as the Servlet container.
Contd…
The Servlet Container, in conjunction with a web
server or application server, provides the network
services over which requests and responses are
set. The container decodes MIME (Multipurpose
Internet Mailing Extensions) based requests and
formats MIME based responses so that the client
browser understands the output generated by the
servlet.
A Servlet container also contains the Servlet and
manages servlet lifecycle.
What is a Servlet Container (Contd.)
A servlet container can either be built into a host
web server or installed as an add-on component
to a Web Server via that server's native
extension API. Servlet containers can also be
built into Application Servers.
All Servlet containers support HTTP as a
protocol for requests and responses, but may
also support other request/response based
protocols such as HTTPS (HTTP over SSL).
The minimum required version of HTTP
specification that a container must implement is
HTTP/1.0. It is strongly suggested that
containers implement the HTTP/1.1
specification as well.
The Request-Process-Response Cycle
A client program, such as a web browser, accesses a
web server and makes an HTTP request. This request
is processed by the web server and is handed off to the
servlet container.
The servlet container determines which servlet to invoke
based on its internal configuration. It calls the servlet
with the object representing the request.
The Request-Process-Response Cycle
(Contd.)
The servlet uses the request object to find out
the identity of the remote user, what HTML form
parameters may have been sent as part of this
request and other relevant data.
The servlet can then perform whatever logic it
was programmed with and can generate data to
send back to the client. It sends the data back
to the client via the response object.
Once the servlet is done with the request, the
servlet container ensures that the response is
properly flushed and returns control back to the
host Web server.
Comparing Sevlets with other
Technologies
Servlets have the following advantages over the other
server extension mechanisms:
They are much faster than CGI scripts because a
different process model is used.
They use a standard API that is supported by many Web
servers.
They have all the advantages of the Java programming
language, including ease of development and platform
independence.
They can access the large set of APIs available for the
Java platform.
Basic Servlet Structure
Servlet Interface
Request Handling methods
Number of Instances
Servlet Life Cycle
A servlet is managed through a well-defined life cycle
that defines how it is loaded, instantiated, handles
requests from clients and how it is taken out of service.
The life cycle is expressed in the API by the init(),
service() and destroy() methods in that order of
execution of the javax.servlet.Servlet interface that all
servlets directly or indirectly implement.
Servlet Life Cycle (Contd.)
Calling the
init method
Servlet
Instance
Servlet Class
Deal with requests:
call the
service method
Destroy the Servlet:
call the
destroy method
ServletConfig
Garbage
Collection
Loading and Instantiation
The servlet container is responsible for
loading and instantiating a servlet. The
instantiation and loading can occur when
the container is started or it can be delayed
until the container determines that it needs
the servlet to service a request.
First, the servlet container locates a class of the servlet’s
type. If needed, the servlet container loads a servlet using
normal Java class loading facilities from a local file system, a
remote file system or other network services. The Container
instantiates an object of that class for use, after loading the
Servlet class.
It is important to note that there can be more that one
instance of a given Servlet class in the servlet container. This
can also occur when a servlet implements the
SingleThreadModel interface and the container creates a
pool of servlet instances to use.
Initialization
After the servlet object is loaded, the container must
initialize the servlet before it can handle requests from
clients. Initialization is provided so that a servlet can
read persistent configuration data, initialize costly
resources (JDBC Database Connections) and perform
other one-time activities.
The container initializes the servlet by calling the
init( ) method of the servlet interface with a unique
object implementing the ServletConfig interface.
This configuration object allows the servlet to
access name-value initialization parameters from
the servlet container's configuration information.
The configuration object also gives the servlet
access to an object implementing the
ServletContext interface that describes the
runtime environment that the servlet is running
within.
Request Handling
After the servlet is properly initialized, the
servlet container uses it to handle requests. A
request object of type ServletRequest
represents each request and the servlet can
create a response to the request by using the
provided object of type ServletResponse.
These objects are passed as parameters to the
service method of the Servlet interface. In the
case of a HTTP request, the container provides
the request and response objects as
implementations on HttpServletRequest and
HttpServletResponse.
End of Service
The Servlet container is not required to
keep a servlet for any period of time. A
Servlet instance may be kept active in a
servlet container for a period of only
milliseconds, for the lifetime of the servlet
container (which could be measured in
days, months, years).
Example
The Servlet alias, Servlet Mapping, Initialization parameters
has to be specified in an xml file called web.xml, which
should be present in the web-inf directory.
The web-inf file is as follows:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>s1 </servlet-name>
<servlet-class>
MyServlet
</servlet-class>
contd…
Example (Contd.)
<init-param>
<param-name>compName</param-name>
<param-value>Sql Star International Ltd.</paramvalue> </init-param>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern> /hello/s1</url-pattern>
</servlet-mapping>
</web-app>
Example (Contd.)
The servlet class is MyServlet.class in web-inf\classes
directory.
The alias s1 is given to the servlet.
The parameter name for the servlet is compName
The value for the parameter is Sql Star International Ltd.
The servlet s1 is mapped to hello/s1
Therefore the URL to the servlet will be:
http://localhost:8080/ourApps/hello/s1
Listing of MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
private String cName;
public void init()
{
System.out.println("My Init method");
ServletConfig conf = getServletConfig();
cName = conf.getInitParameter("compName");
System.out.println("Company Name is : " + cName);
}
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
System.out.println("this is my service method");
}
public void destroy()
{
System.out.println("destroy called. ....");
}
} // end of class ....
A Simple Servlet Generating Plain Text,
HTML, XML
The servlet container creates a
ServletResponse object and passes it as an
argument to the servlet's service() method. This
object assists a servlet in sending a response to
the client.
To send binary data in a body response, use the
ServletOutputStream returned by
getOutputStream(). To send character data, use
the PrintWriter object returned by getWriter().
The charset for the body response can be specified with
setContentType(java.lang.String). For example,
"text/html; ".
The charset can alternately be set using
setLocale(java.util.Locale). If no charset is specified,
ISO-8859-1 is used.
The setContentType() or setLocale() method must be
called before getWriter() for the charset to affect the
construction of the writer.
The following example shows how to send content from
the servlet to the client browser with a content type of
text/text.
Example
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/text");
PrintWriter pw = response.getWriter();
pw.println("this is plain text");
pw.close();
}
Send html content from a servlet
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>A simple HTML
file</title></head>");
pw.println("<body>This is a simple html
file</body></html>");
pw.close(); }
Send an XML file to the client browser
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException{
response.setContentType("text/xml");
PrintWriter pw = response.getWriter();
pw.println("<?xml version=\"1.0\"?>");
pw.println("<friends>");
pw.println("<friend>");
pw.println("<name>Mohan</name><city>Mumbai</city>");
pw.println("</friend>");
pw.println("</friends>");
pw.close();
}
Handling the Client
Request: Form Data
HTML and Forms
The end user of the system needs to send information to
the server-side program.
There are many options for the client; for example htmlforms, applets and other user-agents.
HTML forms are easy to develop and because they are
simple text, the transmission of html is faster than the
other alternatives.
The FORM element in HTML is used to define a form.
A form has several attributes and child elements.
Various Form Attributes and their meaning
action: The backend program to be invoked
when the form is submitted
method: The method of submitting the form
data. (GET/POST)
target: the target frame/window where the
response should be displayed.
The Child Elements of Form
Following are the various Form input types:
Text
TextArea
Select option
Checkbox
Radio
Hidden
Button
Submit
Reset.
Methods
Submit : Upon calling the submit method on a
form the fields are posted to the program
mentioned in the action. The submit button of a
form has a built-in functionality so that it
internally calls the submit method of the form.
Reading Form Data from Servlets
The Request Object encapsulates all information
about the client request. In the HTTP protocol,
this information is transmitted from the client to
the server by the HTTP request headers and
the message body of the request.
Request Parameters
Request parameters are strings sent by the
client to a server as part of a request.
When the request is an HttpServletRequest, the
attributes are populated from the URI query
string and possibly posted form data.
The parameters are stored by the servlet
container as a set of name-value pairs. Multiple
parameter values can exist for any given
parameter name.
The following methods of the ServletRequest interface are
available to access parameters:
getParameter(ParameterName)
getParameterNames()
getParameterValues(ParameterName)
The getParameterValues() method returns an array of String
objects containing all the parameter values associated with a
parameter name. The value returned from the getParameter()
method always equal the first value in the array of String
objects returned by the getParameterValues(). The
getParameterNames() method returns an Enumeration of
parameter names in the request.
Request Parameters (Contd.)
All form data from both the query string and the
post are aggregated into the request parameter
set. The order of this aggregation is that query
string data takes precedence over post body
parameter data. For example, if a request is
made with a query string of a=hello and a post
body of a =goodbye & a=world, the resulting
parameter set would be ordered a=(hello,
goodbye, world)
Posted form data is only read from the input stream of the
request and used to populate the parameter set when all of
the following conditions are met.
The request is an HTTP or HTTPS request.
The HTTP method is POST
The content type is application/x-www-form-urlencoded
The servlet calls any of the getParameter family of methods
on the request object.
If any of the getParameter family of methods is not called, or
not all of the above conditions are met, the post data remains
available for the servlet to read via the request's input
stream.
Attributes
Attributes are objects associated with a request.
Attributes may be set by the container to express
information that otherwise could not be expressed via
the API, or may be set by a servlet to communicate
information to another servlet (via RequestDispatcher).
Attributes are accessed with the following methods of
the ServletRequest interface
getAttribute()
getAttributeNames()
setAttribute()
An Application with Form Data
1.
Single Value Against a Field
A HTML form with the fields fName, fAge, and
fProfession submits to a Servlet named
Servlet1.
The Servlet has to read the form-submitted values
into different String objects.
<form method="get" action="servlet/Servlet1">
Name : <input type="text" name="fName"><br>
Age : <input type="text" name="fAge"><br>
Profession : <select name="fProfession">
<option value="Training">Training</option>
<option value="Consulting">Consulting</option>
<option value="Manager">Manager</option>
<option value="Others">Others</option>
</select>
<br><input type="submit"><input type="reset">
</form>
An Application with Form Data (Contd.)
Create a html form based on the above
code and store it in the ourApps directory.
The servlet Serv1 knows the names of the
form-submitted fields. Since the HTML
form submission method is get, the doGet
(..,..) should be used. The servlet's doGet
method is as follows:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name, profession;
int age;
name = request.getParameter("fName");
profession = request.getParameter("fProfession");
An Application with Form Data (Contd.)
try{
age =Integer.parseInt(request.getParameter("f2"));
pw.println("Values submitted ....<br>");
pw.println("Name : " + name + "<br>");
pw.println("age : " + age + "<br>");
pw.println("Profession : " + profession + "<br>");}
catch(NumberFormatException) {
pw.println("Invalid age .....");}
pw.close(); } // end of dogGet .....
An Application with Form Data
(Contd.)
2. Working with multiple values against a
single field
Consider that a html form has got a field named
hobbies. The field is a list of multiple choices.
<select multiple name="hobbies">
<option value="Swimmimg">Swimming</option>
<option value="Boxing">Boxing</option>
<option value="Music">Music</option>
<option value="Football">Football</option>
<option value="Cricket">Cricket</option>
</select>
An Application with Form Data
(Contd.)
The user selects Boxing, Cricket and Football from the
multiple choice. The servlet now should pick up the
selected values against the field hobbies in the
following manner:
String hobbies[];
hobbies = request.getParameterValues("hobbies"):
for(int i=0; i < hobbies.length; i++){
pw.println(hobbies[i] + "<br>");}
An Application with Form Data (Contd.)
3. Reading form submitted values against
unknown field names
In a scenario where the Servlet programmer does
not know the field names, the
getParameterNames method must be used.
Following is an example where the
servlet displays all the field names and their
corresponding values.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = response.getWriter();
java.util.Enumeration e =
request.getParameterNames();
/*e is a reference to an Enumeration that holds all
the field names as String objects.*/
An Application with Form Data (Contd.)
while(e.hasMoreElement())
{
String fName = (String)e.nextElement();
String fValues[ ] = req.getParameterValues(fName);
for(int ctr=0; ctr < fValues.length; ctr++){
pw.println(fName + " : " + fValues[ctr] + "<br>");
}}
pw.close();
} // end of doGet......
Handling the Client Request:
HTTP Request Headers
What are Request Headers
HTTP request headers are distinct from form data. Form
data results directly from user input and is sent as a part
of the URL for GET requests and on a separate line for
POST requests.
Request headers, on the other hand are directly sent by
the browser and are sent immediately following the GET
or POST request line. The request include the headers
Accept, Accept-Encoding, Connection, Cookie, Host,
Referrer, User-Agent, etc.
Accessing the Request Headers
A Servlet can access the headers of an
HTTP request through the following
methods of the HttpServletRequest
interface.
getHeader
getHeaders
getHeaderNames
Example of HTTP headers against a
request
HeaderServ.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HeaderServ extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Enumeration e = req.getHeaderNames();
Example of HTTP headers (Contd.)
while(e.hasMoreElements())
{ String h = (String)e.nextElement();
Enumeration hVals = req.getHeaders(h);
while(hVals.hasMoreElements()) {
System.out.println(h + " : " +
(String)hVals.nextElement());
} // end of inner while loop
} //end of while loop .....
}
} // end of class .....
Example of HTTP headers (Contd.)
Sample Output :
User-Agent : Mozilla/4.0 (compatible; MSIE 5.0; Windows
NT; DigExt)
Progma : no-cache
Accept : */*
Accept-Encoding : gzip, deflate
Host : 192.9.100.100:8080
Accept-Language : en-us
Connection : keep-Alive
Via : 1.0 proxy
Types of HTTP 1.1 Request Headers
Accept
Accept-Charset
Accept-Encoding
Accept-Language
Authorization
Cache-Control
Connection
Content-Length
Cookie
If-Modified-Since
Referer
Environment Variables
An executing program wanting to access its
environment can do so through environment variables.
Values of environment variables can be used as
conditional evaluation criteria within the program to
allow for conditional execution.
This leads to writing a generalized program that has the
ability to execute different code segments based on the
environment in which it is executing. Examples are
shell scripts in UNIX accessing their shell environment
settings through environment variables.
Widely used environmental variables
REMOTE_ADDR:
This header designates the IP Address of the client that
made the request as a String. To read this value use
HttpServletRequest’s getRemoteAddr method. Note that
if the client is accessing the Server via the proxy server
then the REMOTE_ADDR gives the IP Address of the
proxy server.
REMOTE_HOST:
Indicates the fully qualified domain name (For
Example : abcd.com) of the client that made the
request. If the domain cannot be determined then
the IP Address is returned. Read this value using
HttpServletRequest’s getRemoteHost method.
REQUEST_METHOD:
This header specifies the HTTP request type. Which
is usually GET or POST. Read this value using
HttpServletRequest’s method named getMethod .
Widely used environmental variables
(Contd.)
SCRIPT_NAME:
This header specifies the path to the servlet,
relative to the server’s root directory. It can be
accessed through HttpServletRequest’s
getServletPath method.
SERVER_NAME:
Gives the host name of the server machine.
Obtained via HttpServletRequest’s
getServerName() method.
SERVER_PORT:
The port of the server is returned as an int value via
HttpServletRequest’s getServerPort method.
SERVER_PROTOCOL:
Indicates the protocol name and version used in the
request line( HTTP1.0 or HTTP1.1). Access this
value via HttpServletRequest’s getProtocol
method.
Widely used environmental variables
(Contd.)
CONTENT_LENGTH:
Only against POST requests, this variable stores the
number of bytes of data sent. In order to read the value
use the HttpServletRequest’s getContentLength method
that returns an int value.
CONTENT_TYPE:
Designates the MIME type of attached data. Use
HttpServletRequest’s getContentType method to read
this header.
DOCUMENT_ROOT:
This header specifies the real directory corresponding to
the URL. Read this header by using the
ServletContext’s getRealPath method.
HTTP_HEADER_NAME:
Headers of the form HTTP_COOKIE,
HTTP_USER_AGENT, HTTP_REFERER are accessed
by the HttpServletRequest’s getHeader method.
Widely used environmental variables
(Contd.)
PATH_INFO:
This header supplies any path information attached to the
URL after the address of the servlet but before the query
data. Access the value of PATH_INFO by using
HttpServletRequest’s getPathInfo method.
PATH_TRANSLATED:
This header gives the path information mapped to a real
path on the server. Use the ServletContext’s
getRealPath method to read this value.
QUERY_STRING:
For GET requests, this variable gives the attached
data as a string with values still URL-Encoded.
You rarely want to use raw data in servlets;
instead use HttpServletRequest’s getParameter
method to access individual parameter values.
However if you want the raw data read it through
HttpServletRequest’s getQueryString method.
Example
The following program retrieves the client request specific
information:
EnvServ.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class EnvServ extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException {
String contextPath = req.getContextPath();
Example (Contd.)
System.out.println("context path : " + contextPath);
long l = req.getDateHeader("Modified-Since");
System.out.println("Modified Since : " + l);
String methodName = req.getMethod();
System.out.println("request method : " + methodName);
String pathTranslated = req.getPathTranslated();
System.out.println("pathTranslated : " + pathTranslated);
String qs = req.getQueryString();
System.out.println("query String : " + qs);
String ru = req.getRemoteUser();
System.out.println("Remote User : " + ru);
String sessId = req.getRequestedSessionId();
System.out.println("SessionId : " + sessId);
String uri = req.getRequestURI();
System.out.println("URI : " + uri);
String sp = req.getServletPath();
System.out.println("Servlet Path : " + sp);
String ce = req.getCharacterEncoding();
System.out.println("Character Encoding : " + ce);
Example (Contd.)
String ct = req.getContentType();
System.out.println("content type : " + ct);
Locale locale = req.getLocale();
System.out.println("Locale : " + locale.toString());
String protocol = req.getProtocol();
System.out.println("Protocol : " + protocol);
String rp = req.getRealPath("/ourApps/servlet/EnvServ");
System.out.println("real path : " + rp);
String raddr = req.getRemoteAddr();
System.out.println("Remote Address : " + raddr);
String rh = req.getRemoteHost();
System.out.println("Remote Host : " + rh);
String sn = req.getServerName();
System.out.println("Server Name: " + sn);
int sport = req.getServerPort();
System.out.println("Server Port : " + sport);
} // end of doGet ......
} // end of class . ....
Example (Contd.)
Sample output
context path : /ourApps
Modified Since : -1
request method : GET
pathTranslated : null
query String : null
Remote user : null
Session Id : null
URI : /ourApps/servlet/EnvServ
Servlet Path : /servlet/EnvServ
Character Encoding : null
Locale : en_US
Protocol : HTTP/1.0
real path : c:\jakarta-tomcat-3.2.1\webApps\ourApps\servlet\EnvServ
Remote Address : 192.9.200.174
Remote Host : PROXY
Handling Cookies
The Stateless Nature of the HTTP Protocol
As the content of Web pages became interactive
and dynamic, the prospect of using Web pages as
a front-end for querying and displaying data to
applications that could be deployed on the Web
became a distinct possibility.
HTTP is the protocol that Web browsers and Web
servers use to transfer hypertext and images.
When a client browser requests a file from a Web
server, the Web server locates and sends the
requested file back to the client which is then
rendered by the client browser.
Once the Web server sends the request back to
the client browser, the connection is torn down.
There is therefore, no session maintained
between the client and the server.
Cookies
Session tracking through HTTP cookies is the most
used session tracking mechanism and is required to
be supported by all servlet containers.
The servlet container sends a cookie to the client.
The client will then return the cookie on each
subsequent request to the server unambiguously
associating the request with a session.
The name of the session tracking cookie must be
JSESSIONID.
A cookie is an object that a server creates and
places on the client when the client connects to
it. A cookie contains state information.
Cookies are valuable for tracking user activities.
For example, assume that a user visits an
online bookstore. A cookie can save the user’s
name, address, email-id and other information.
The user does not need to enter this data each
time he or she visits the online bookstore.
The names and values of cookies are stored on
the client machine. Some of the information
that is saved includes the cookie’s:
Name
Value
Expiration date
and path
Some Problems with Cookies
Cookies are never interpreted or executed in
any way and thus cannot be used to insert
viruses or attack your system.
Browsers generally only accept 20 cookies per
site and 300 cookies total and since each
cookie is limited to 4 k.b., cookies cannot be
used to fill up someone’s disk.
Cookies present a significant threat to privacy.
The Servlet Cookie API
The HttpServletRequest interface provides
the getCookie method to obtain an array of
cookies that are present in the request.
These cookies are data sent from the client
to the server on every request that the
client makes.
Typically, the only information that the client
sends back as part of a cookie
is
the
cookie name and the cookie value.
Other cookie attributes that can be set
when the cookie is sent to the
browser,
such as comments, are not typically
returned.
The Servlet Cookie API (Contd.)
Constructor Summary
Cookie(java.lang.String name,
java.lang.String value) Constructs a cookie
with a specified name and value.
Method Summary
java.lang.Object
clone(): Overrides the
standard java.lang.Object.clone method to
return a copy of this cookie.
java.lang.String
getComment(): Returns
The Servlet Cookie API (Contd.)
java.lang.String getPath() Returns the path on the
server to which the browser returns this cookie.
java.lang.String getValue() Returns the value of the
cookie.
int getVersion() Returns the version of the protocol this
cookie complies with.
voidsetComment(java.lang.String purpose) Specifies a
comment that describes a cookie's purpose.
void
setDomain(java.lang.String pattern)
Specifies the domain within which this cookie
should be presented.
void
setMaxAge(int expiry) Sets the
maximum age of the cookie in seconds.
void
setValue(java.lang.String newValue)
Assigns a new value to a cookie after the cookie
is created.
void
setVersion(int v) Sets the version of the
cookie protocol this cookie complies with.
The Servlet Cookie API (Contd.)
API for Placing Cookies in the Response
Headers
Method in HttpServletResponse
void
addCookie(Cookie cookie)
API for Reading Cookies from the Client
Method in HttpServletRequest
Cookies[]
getCookies()
Examples of Setting and Reading
Cookies
Example : A HTML that accepts cookie name
and cookie value. A Servlet that sends
accepted name, values from the HTML
Form to the Browser and displays a list of
name-value pair.
The HTML Form
<form method="get" action="servlet/CookieServ">
Cookie Name : <input type="text"
name="cookie_name"><br>
Cookie Value : <input type="text"
name="cookie_value"><br>
<input type=submit>
</form>
Examples of Setting and Reading
Cookies (Contd.)
The Servlet: CookieServ.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServ extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String cName = req.getParameter("cookie_name");
String cValue = req.getParameter("cookie_value");
Cookie cookie = new Cookie(cName, cValue);
res.addCookie(cookie);
Examples of Setting and Reading
Cookies (Contd.)
Cookie cookies[] = req.getCookies();
pw.println("<table><tr><th>Cookie Name</th><th>Cookie Value</th></tr>");
for(int ctr=0; ctr < cookies.length; ctr++)
{
pw.println("<tr><td>" +
cookies[ctr].getName() + "</td><td>" +
cookies[ctr].getValue() + "</td></tr>");
}
pw.println("</table>");
pw.println("<p>Details Accepted...");
pw.close();
}
} // end of class ....
Servlet Context and
Session Tracking
What is a ServletContext
The ServletContext defines a servlet's view of the web
application within which the servlet is running.
The ServletContext also allows access to resources
available to it. Using such an object, a servlet can obtain
URL references to resources and set and store
attributes that other servlets in the context can use.
The Container provider is responsible for providing an
implementation of the ServletContext interface in the
servlet container.
A ServletContext is rooted at a specific path within a
web server.
For example a context could be located at
http://www.bestbooks.com/catalog. All requests that start
with /catalog request path, which is known as the
context path, will be routed to this servlet context.
Scope of a ServletContext
There is one instance of the ServletContext
interface associated with each web
application deployed into a container.
Servlets that exist in a container that were
not deployed as part of a web application
are implicitly part of the default web
application and are contained by the default
ServletContext.
Context Attributes
A servlet can bind an object into the context by name.
Any object bound into a context is available to any other
servlet that is part of the same application.
The following methods of ServletContext interface allow
access to this functionality:
setAttribute()
getAttribute()
getAttributeNames()
removeAttribute()
Accessing ServletContext
Within your servlet code, call
getServletContext ( )
The ServletContext is contained in
ServletConfig object , which the Web
server provides to a servlet when the
servlet is initialized
init (ServletConfig servletConfig) in Servlet
interface
Example – CatalogServlet.java
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
//Get the context-wide attribute value from
ServletContext object
bookDB = (BookDB)
getServletContext().getAttribute("bookDB");
if (bookDB ==null)
throw new UnavailableException("Couldn;t get
database"); } }
Why Session Tracking
The Hypertext Transfer Protocol (HTTP) is by design a
stateless protocol. It opens a separate connection to the
Web Server, and the server does not automatically
maintain information about a client.
These cause a number of difficulties.
For example when clients at an online store add an item
to their shopping carts, the server has to have a
mechanism of knowing what is already in them.
Similarly, when clients decide to proceed to
checkout, the server must be able to
determine which previously created
shopping carts are theirs.
To build effective web applications, it is
imperative that a series of different
requests from a particular client can be
associated with each other. Using the
session object solves this problem.
Session Tracking
Session tracking is the capability of a server to maintain
the current state of a single client ’s sequential requests.
Done by
Basic Authentication
Hidden fields
URL rewriting
Cookies
Session API ’s
Basic Authentication
HTTP server has a built-in capability to restrict access to some or
all of its pages to a given set of registered users.
The first time a browser attempts to access one of these pages, the
HTTP server replies that it needs special user authentication.
When the browser receives this response, it usually pops open a
window asking the user for a name and password appropriate for a
page.
Once the user enters the user name and password, the browser
attaches it with request and sends it again to the server.
The servlet extracts the user-name from the request and handles
the request appropriately if it thinks that the user making the
request is a valid one.
Basic Authentication (Contd.)
Method : getRemoteUser()
Servlet uses this method to extract the user’s name from the
HTTP request.
This method returns name of the user making the request as a
String.
It returns null if the access to the servlet was not restricted.
Advantage
Simple to implement
Disadvantage
Each user has to register for an account with the web site.
Each time user access the restricted page, she has to provide
the user-name and password.
Cookies
A Cookie is a keyed piece of data that is created by the
server and stored by the client browser.
A Cookie is stored on a client and contains state information.
Browsers maintain their own list of cookies.
Cookies are very useful in session racking.
Some of the information that is saved includes the cookie’s:
name
Value
expiration date
domain and path
Java Session Tracking API
Java provides following interface for session tracking
javax.servlet.http.HttpSession
A servlet uses its request object's getSession() method
to retrieve the current HttpSession object.
Following two methods can be used
public HttpSession
HttpSession.getSession(boolean create)
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
public HttpSession HttpSession.getSession(boolean
create)
Returns the current HttpSession associated with
this request or, if there is no current session and
create is true, returns a new session.
Java Session Tracking API
(Contd.)
To add data to an HttpSession use following
method:
public void HttpSession.putValue(String name,
Object value)
“name” is any attribute name
To retrieve an object from a session, use
getValue():
public Object HttpSession.getValue(String name)
To get the names of all of the objects bound to a
session use :
public String[] HttpSession.getValueNames()
Returns an array of strings containing the names of all
attributes bound to this session.
To specify the time (in seconds) for which session
must be active use :
public void
HttpSession.setMaxInactiveInterval(int interval).
The negative value indicates that session should never
expire.
Example – HitCounter.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HitCounter extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession(true);
// Increment the hit count for this page. The value is saved
// in this client's session under the name “HitCount".
Integer count = (Integer)session.getValue("HitCount");
Example – HitCounter.java
(Contd.)
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
sesion.putValue("HitCount", count);
out.println("<HTML><HEAD><TITLE>Hit Counter</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
// Display the hit count for this page
out.println("You've visited this page " + count + " times."));
out.println("<P>");
out.println("</BODY></HTML>");
}}
URL Rewriting
In cookie-based session tracking, the session ID is
saved on the client in a persistent cookie.
Many browsers does not accept cookies.
In these situations the Server adopts the URL rewritting
as a Session tracking mechanism.
In this servlet rewrites (encodes along with Session ID)
every local URL before sending it to the client.
In case if the encoding is not supported the URL
remains unchanged.
URL Rewriting (Contd.)
Servlet API provides following two methods to perform this encoding :
public String HttpServletResponse.encodeUrl(String url)
Encodes (rewrites) the specified URL to include the session ID
and returns the new URL
All URLs emitted by a servlet should be run through this
method.
Eg.: The Servlet showing the link to OrderDetails servlet uses
the URL encoding
out.println("Click <A HREF=\"" + res.encodeUrl(“/servlet/OrderDetails”) +
"\">here</A>");
out.println("to open the Order Details.");
public String
HttpServletResponse.encodeRedirectUrl(Stri
ng url)
Encodes (rewrites) the specified URL to include
the session ID and returns the new URL,
All URLs passed to the sendRedirect() method of
HttpServletResponse should be run through this
method.
Eg. : The Servlet redirecting the user to
NewServlet
res.sendRedirect(res.encodeRedirectUrl("/servlet/NewServlet"));
Java Servlet Architecture
Javax.servlet.Servlet
Javax.servlet.ServletConfig
Javax.servlet.GenericServlet
Javax.servlet.http.HttpServlet
Javax.io.seriaziable