Академический Документы
Профессиональный Документы
Культура Документы
Introduction to Servlet
Servlets are modules that run inside request/response-oriented servers,
such as Java-enabled web servers, and extend them in some manner. For
example, a servlet might be responsible for taking data in an HTML order-entry
form and applying the business logic used to update a company's order
database.
Servlets are to servers what applets are to browsers.
The Servlet API, which you use to write servlets, assumes nothing about
how a servlet is loaded, the server environment in which the servlet runs, or the
protocol used to transmit data to and from the user. This allows servlets to be
embedded in many different web servers.
Servlets are an effective substitute for CGI scripts: they provide a way to
generate dynamic documents that is both easier to write and faster to run. They
also address the problem of doing server-side programming with platformspecific APIs. Servlets are developed with the Java Servlet API, a standard Java
extension.
Example Uses
A few of the many applications for servlets include,
Processing data Posted over HTTPS using an HTML form, including
purchase order or credit card data. A servlet like this could be part of an
order-entry and processing system, working with product and inventory
databases, and perhaps an on-line payment system.
Allowing collaboration between people. A servlet can handle multiple
requests concurrently; they can synchronize requests to support systems
such as on-line conferencing.
Forwarding requests. Servlets can forward requests to other servers and
servlets. This allows them to be used to balance load among several
servers that mirror the same content. It also allows them to be used to
partition a single logical service over several servers, according to task
type or organizational boundaries.
Being a community of active agents. A servlet writer could define active
agents that share work among each other. Each agent would be a servlet,
and the agents could pass data among themselves.
Servlets are modules of Java code that run in a server application
Servlets are not restricted to but most commonly used with HTTP
Servlets use extension classes in
javax.servlet
Servlets vs CGI
:
A Servlet does not run in a separate process
A Servlet stays in memory between requests
There is only a single instance which answers all requests concurrently. This
saves memory and allows a Servlet to manage persistent data
CGI requires more memory & CPU time. Every link to every CGI program
causes web server to create a separate process in which to run CGI.
Servlet vs Applet:
An applet is a Java plug-in for web browser. Whereas servlet is a Java plug-in
for web server.
An applet extends the capabilities of web browser. Servlets are the Java
components that extends the capabilities of web server.
Applets adds functionality to web pages, but it has problems of compatibility &
bandwidth issues. Applets are programs embedded directly into web pages with
a web page; byte-code of an applet is downloaded to client box & executed by
browser. For big size applets the download time is very high. To run an Applet,
you must have compatible browser, but servlet code is being executed on server
side & no issues with browsers compatibility or long download times.
Servlets Can Do:
1. Dynamically build & return an HTML file based on client request.
2. Process user input passed by HTML form & return proper response.
3. Provide user authentication & other security mechanisms.
4. Interacts with server resources like database, other applications & network
files.
5. Process input from many clients
6. Automatically attach web page design elements like headers / footers to all
pages returned by server.
7. Forward requests from one server to another & communicates with other
server resources.
Web
Server
Request
Response
GenericServlet
service()
HttpServlet:
After extending this class it is not necessary to implement service()
method, as this class has by default implements it. The form is:
protected void service (HttpServletRequest req, HtppServletResponse res)
throws ServletException, IOException
This class has following methods, requires same parameters listed in service ()
method.
Client
Web
Server
Request
Response
service ()
doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
JSDK is a package freely available from JavaSoft that includes all tools
needs to begin servlets.
It includes packages like javax.servlet & javax.servlet.http etc. that
contains all classes related to servlets.
It has simple test web server useful for testing servlet operations.
Directory Structure:
o JSDK
bin
- Contains test servlet runner
boc
- Contains class & interface documentation that
apidoc can be viewed with any web browser
images
examples lib
- contains /lib/jsdk.jar file, which compiler uses to
compile servlet API.
Src
- Contains source code for servlet API.
Servlet Lifecycle
Servers load and run servlets, which then accept zero or more requests
from clients and return data to them. They can also remove servlets. These are
the steps of a servlets lifecycle.
a. init() - When a server loads a servlet, it runs the servlet's init method. The
server calls the init method once, when it loads the servlet, and will not call
it again unless it is reloading the servlet. The server can not reload a
servlet until after it has removed the servlet by calling the destroy method.
Initialization is allowed to complete before client requests are handled (that
is, before the service method is called) or the servlet is destroyed.
The form of init() is :
public void init (ServletConfig config) throws ServletException
b. service() - After the server loads and initializes the servlet, the servlet is
able to handle client requests. It processes them in its service method.
Each client's request has its call to the service method run in its own
servlet thread: the method receives the client's request, and sends the
client its response.
Servlets can run multiple service methods at a time. It is important,
therefore, that service methods be written in a thread-safe manner. For
example, if a service method might update a field in the servlet object, that
access should be synchronized. If, for some reason, a server should not
run multiple service methods concurrently, the servlet should implement
the SingleThreadModel interface. This interface guarantees that no two
threads will execute the servlet's service methods concurrently.
The form of service () is :
public void service (ServletRequest req, ServletResponse res) throws
ServletException, IOException
c. destroy() - Servlets run until they are removed from the service, for example,
at the request of a system administrator. When a server removes a servlet,
it runs the servlet's destroy method. The method is run once; the server
will not run it again until after it reloads and reinitializes the servlet. When
the destroy method runs, however, other threads might be running service
requests. If, in cleaning up, it is necessary to access shared resources
(such as network connections to be closed), that access should be
synchronized.
The form of destroy () is :
public void destroy ()
1.
2.
3.
4.
javax.servlet classes
Methods:
1. public abstract String getAuthType()- returns a string describing the
authentication scheme employed by client.
2. public abstract Cookie[ ] getCookies() Returns cookies from request in
form of an array of cookie objects.
3. public abstract String getMethod() Returns HTTP method i.e get, post,
put used by request.
4. public abstract String getPathInfo()- Returns any path information
following server path but prior to query string.
5. public abstract String getQueryString() Returns query string of a URL.
6. public abstract String getServletPath()- Returns path to servlet being
invoked. Ex. http://localhost:8080/servlet/GetPathServlet/html/public
op- /servlet/GetPathServlet
7. public abstract String getRemoteUser()- Returns name of user making
request.
8. public abstract int getRequestedSessionId()- Returns session id
contained in request.
9. public abstract String getRequestURL()- Returns part of requested URL
left of QueryString.
Status code (301) indicating that the resource has permanently moved to a
new location, and that future references should use a new URI with their
requests.
SC_MOVED_TEMPORARILY
Status code (302) indicating that the resource has temporarily moved to
another location, but that future references should still use the original URI
to access the resource.
SC_NOT_ACCEPTABLE
Status code (406) indicating that the resource identified by the request is
only capable of generating response entities which have content
characteristics not acceptable according to the accept headerssent in the
request.
SC_NOT_FOUND
Status code (404) indicating that the requested resource is not available.
SC_OK
Status code (200) indicating the request succeeded normally.
SC_REQUEST_TIMEOUT
Status code (408) indicating that the client did not produce a requestwithin
the time that the server was prepared to wait.
SC_SERVICE_UNAVAILABLE
Status code (503) indicating that the HTTP server is temporarily
overloaded, and unable to handle the request.
HttpSession--This interface is implemented by servlets to enable them to
support browser-server sessions that span multiple HTTP requestresponse pairs. Since HTTP is a stateless protocol, session state is
maintained externally using client-side cookies or URL rewriting. This
interface provides methods for reading and writing state values and
managing sessions.
HttpSession defines methods, which store these types of data:
Standard session properties, such as an identifier for the session, and the
context for the session.
Application layer data, accessed using this interface and stored using a
dictionary-like interface.
The following code snippet illustrates getting and setting the session data value.
//Get the session object - "request" represents the HTTP servlet request
HttpSession session = request.getSession(true);
//Get the session data value - an Integer object is read from
//the session, incremented, then written back to the session.
//sessiontest.counter identifies values in the session
Integer ival = (Integer) session.getValue("sessiontest.counter");
if (ival==null)
ival = new Integer(1);
else
ival = new Integer(ival.intValue() + 1);
session.putValue("sessiontest.counter", ival);
An implementation of HttpSession represents the server's view of the session.
The server considers a session to be new until it has been joined by the client.
Until the client joins the session, the isNew method returns true. A value of true
can indicate one of these three cases:
Methods:
1. public abstract HttpSession getSession (String sessionId)
Returns the session bound to the specified session ID.
Parameters: sessionID - the ID of a particular session object
Returns: The session name. Returns null if the session ID does not refer to a
valid session.
2. public abstract Enumeration getIds()
Returns an enumeration of all of the session IDs in this context.
Returns: an enumeration of all session IDs in this context
javax.servlet.http classes
Cookie--This class represents an HTTP cookie. Cookies are used to maintain
session state over multiple HTTP requests. They are named data values that are
created on the Web server and stored on individual browser clients. The Cookie
class provides the method for getting and setting cookie values and attributes.
public class Cookie
extends Object
implements Cloneable
should see the cookie. By default, cookies are only returned to the host
which saved them.
4. public String getDomain()
Returns the domain of this cookie.
5. public void setMaxAge(int expiry)
Sets the maximum age of the cookie. The cookie will expire after that many
seconds have passed. Negative values indicate the default behaviour: the cookie
is not stored persistently, and will be deleted when the user agent (web browser)
exits. A zero value causes the cookie to be deleted.
6. public int getMaxAge()
Returns the maximum specified age of the cookie. If none was specified, a
negative value is returned, indicating the default behaviour described with
setMaxAge.
7. public void setPath(String uri)
This cookie should be presented only with requests beginning with this
URL. Basically, URLs in the same "directory" as the one which set the cookie,
and in subdirectories, can all see the cookie unless a different path is set.
8. public String getPath()
Returns the prefix of all URLs for which this cookie is targetted.
9. public void setSecure (boolean flag)
Indicates to the user agent that the cookie should only be sent using a
secure protocol (https). This should only be set when the cookie's originating
server used a secure protocol to set the cookie's value.
10. public boolean getSecure()
Returns the value of the 'secure' flag.
11. public String getName()
Returns the name of the cookie. This name may not be changed after the
cookie is created.
12. public void setValue(String newValue)
Sets the value of the cookie. BASE64 encoding is suggested for use with
binary values.
With version zero cookies, you need to be careful about the kinds of values
you use. Values with various special characters (whitespace, rackets and
parentheses, the equals sign, comma, double quote, slashes, question marks,
the "at" sign, colon, and semicolon) should be avoided. Empty values may not
behave the same way on all browsers.
13. public String getValue()
Returns the value of the cookie.
14. public int getVersion()
15. public void setVersion(int v)
Sets the version of the cookie protocol used when this cookie saves itself.
16. public Object clone()
Returns a copy of this object.
Overrides: clone in class Object
Example:
// Create a new Cookie
Cookie c=new Cookie(name,abcd);
// Set life of cookie, that expires in 2 days.
c.setMaxAge(2*24*60*60);
// Add cookie to clients machine.
res.addCookie(c)
operation also automatically supports the HEAD operation. (HEAD is a GET that
returns no body in the response; it just returns the request HEADer fields.)
The GET operation is expected to be safe: without any side effects for
which users might be held responsible. For example, most form queries have no
side effects. Requests intended to change stored data should use some other
HTTP method.
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
2. getLastModified
protected long getLastModified(HttpServletRequest req)
Gets the time the requested entity was last modified; the default
implementation returns a negative number, indicating that the modification time is
unknown and hence should not be used for conditional GET operations or for
other cache control operations as this implementation will always return the
contents.
Implementations supporting the GET request should override this method
to provide an accurate object modification time. This makes browser and proxy
caches work more effectively, reducing the load on server and network
resources.
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
Returns:
The time the requested entity was last modified, as the difference,
measured in milliseconds, between that time and midnight, January 1, 1970
UTC. Negative numbers indicate this time is unknown.
3. doPost
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP POST operation; the default implementation reports an
HTTP BAD_REQUEST error. Servlet writers who override this method should
read any data from the request (for example, form parameters), set entity
headers in the response, access the writer or output stream and, finally, write any
response data using the servlet output stream. The headers that are set should
include content type, and encoding.
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
4. doPut
protected void doPut(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP PUT operation; the default implementation reports an
HTTP BAD_REQUEST error. The PUT operation is analogous to sending a file
via FTP.
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
5. doDelete
protected void doDelete (HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP DELETE operation; the default implementation reports
an HTTP BAD_REQUEST error. The DELETE operation allows a client to
request a URI to be removed from the server.
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
6. doOptions
protected void doOptions(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP OPTIONS operation; the default implementation of this
method automatically determines what HTTP Options are supported. For
example, if a servlet writer subclasses HttpServlet and overrides the doGet
method, then this method will return the following header:
Allow: GET,HEAD,TRACE,OPTIONS
Parameters:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
7. doTrace
protected void doTrace(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
enteringServiceMethod();
try {
super.service(req, resp);
} finally {
leavingServiceMethod();
}
}
The destroy method should check the serviceCounter, and if there are any
long-running methods, set the shuttingDown variable. This variable will let the
threads still handling client requests know that it is time to shut down. The
destroy method should then wait for the service methods to complete, in order to
provide a clean shutdown.
public void destroy() {
/* Check to see whether there are still service methods running,
* and if there are, tell them to stop. */
if (numServices() > 0) {
setShuttingDown(true);
}
/* Wait for the service methods to stop. */
while(numService() > 0) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e) {
}
}
}
where servlet-name corresponds to the name you have given your servlet. For
example, to run the Phone Servlet, which has the property
servlet.phone.code=PhoneServlet, you would use the following URL. (It assumes
that servletrunner is running on your machine, localhost, at port 8080, and that
the phone servlet is located in the servlet directory provided to servletrunner at
startup:
http://localhost:8080/servlet/phone
Another example, the survey servlet, is run as a result of submitting a form. The
URL used for the servlet by the survey-form in the HTML file is:
http://demo:8080/servlet/survey
Assignments:
1. Write a servlet to design HTML page, with proper title, headings.
2. Write a servlet to check username & password passed from html page. If it
is Scott & tiger, display welcome message else show the same html
page again. [With res.sendRedirect (http://localhost:8080/login.html)]
3. WAP to accept two numbers from html display addition of them.
4. Write a Servlet to display html forms control names & their values.
5. Write Servlet to create html page for the feedback of product. Store the
feedback in a database.
6. Write a servlet to maintain a shopping cart, using session valriables.
7. Write a servlet to add a Cookie to clients machine that stores username,
current date & time. Display the same.
8. Write a servlet to accept a name of background color from user, change
the background color as per the color entered. [Design HTML using
servlet].
req,
For declaring variables, the better place is within service method for multiclient application, because each call to service() is handled by a separate
thread, the variables will be protected( each request has its own copy) &
cannot be modified by other requests.
SingleThreadModel Interface:
Defines no methods & simply serves as a flag to server. If a servlet
implements this interface, server guarantees that no more than one thread
can execute service()/ doGet()/ doPost() methods a time for a particular
servlet instance.
Ex:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
public class greetings extends HttpServlet implements SingleThreadModel
{
String username;
public void service (HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContenetType("text/html");
PrintWriter pw=res.getWriter();
username=req.getParamter (name);
printgreeting(pw);
pw.close ();
}
private void printgreeting(PrintWriter out)
{
out.println (Hello:+username);
}
}
Server-Sides includes:
It allows you to embed servlet calls withinan HTML document, using
<servlet>tag. These documents should use .shtml file extension. This
indicates to server that HTML includes SSI directives & should be passed to a
specialized SSI servlet for processing.
<servlet name=SERVLET_NAME
code=CLASS_NAME
INIT_PARAM1=VALUE1
INIT_PARAM2=VALUE2.
>
</servlet>
Example:
1. A servlet that returns a standard header.
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
public class hservlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType (text/html);
PrintWriter pw=res.getWriter();
pw.println (<h1>Welcome</h1>);
pw.close ();
}
}