L21Servelets - IT Knowledge Base
Download
Report
Transcript L21Servelets - IT Knowledge Base
Java Servelets
What Is a Servlet?
A servlet is a Java programming language class used to extend the
capabilities of servers that host applications accessed via a requestresponse programming model.
Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by Web servers.
For such applications, Java Servlet technology defines HTTP-specific
servlet classes.
The javax.servlet and javax.servlet.http packages provide
interfaces and classes for writing servlets.
All servlets must implement the Servlet interface, which defines
life-cycle methods.
When implementing a generic service, you can use or extend the
GenericServlet class provided with the Java Servlet API.
The HttpServlet class provides methods, such as doGet and
doPost, for handling HTTP-specific services.
A servlet is a server side software
component, written in java that
dynamically extends the functionality of a
server.
Unlike applets servlets don’t display GUI.
It works behind the scene on server and
results of servlet’s processing are returned
to the client.
Advantages
Capable of running in same process space a the web
server.
Compiled.
Crash resistant
Cross platform
Durable
Dynamically loaded across the network
Extensible
Multithreaded
Protocol independent
Written in java
Functions
Dynamically build and return an HTML file
based on client request.
Process user input of HTML Form and
return appropriate response.
Facilitate communication among many
clients.
Interact with server resources like
database, other application.
Multiplayer games.
Advantage of Servlets Over
CGI
Java servlets are more efficient, easier to use, more powerful, more portable, and
cheaper than traditional CGI and than many alternative CGI-like technologies. (More
importantly, servlet developers get paid more than Perl programmers :-).
Efficient.
–
–
–
–
–
With traditional CGI, a new process is started for each HTTP request.
If the CGI program does a relatively fast operation, the overhead of starting the process can
dominate the execution time.
With servlets, the Java Virtual Machine stays up, and each request is handled by a
lightweight Java thread, not a heavyweight operating system process.
Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program,
then the code for the CGI program is loaded into memory N times.
With servlets, however, there are N threads but only a single copy of the servlet class.
Servlets also have more alternatives than do regular CGI programs for optimizations such as
caching previous computations, keeping database connections open, and the like.
Convenient.
–
–
You already know Java.
Why learn Perl too? Besides the convenience of being able to use a familiar language,
servlets have an extensive infrastructure for automatically parsing and decoding HTML form
data, reading and setting HTTP headers, handling cookies, tracking sessions, and many
other such utilities.
Powerful.
–
–
–
–
–
Portable.
–
–
–
Java servlets let you easily do several things that are difficult or impossible with regular CGI.
For one thing, servlets can talk directly to the Web server (regular CGI programs can't).
This simplifies operations that need to look up images and other data stored in standard
places.
Servlets can also share data among each other, making useful things like database
connection pools easy to implement.
They can also maintain information from request to request, simplifying things like session
tracking and caching of previous computations.
Servlets are written in Java and follow a well-standardized API.
Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged
on Apache, Microsoft IIS, or WebStar.
Servlets are supported directly or via a plugin on almost every major Web server.
Inexpensive.
–
–
–
There are a number of free or very inexpensive Web servers available that are good for
"personal" use or low-volume Web sites.
However, with the major exception of Apache, which is free, most commercial-quality Web
servers are relatively expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet
support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap
Servlet API
It doesn’t run as an application rather it is loaded in
memory and as instance is created.
When a servlet instance is created its init() is called.
Servlets are required to respond to new connections to
the server.
When a new connection is detected, a call is made to
the service() of the servlet.
service() takes two parameters defined by interface type
called ServletRequest and ServletResponse.
Servlet class is abstract because service() is defined not
implemented; so to implement a servlet, it is necessary
to override this method.
Servlet class is not protocol specific.
A subclass of Servlet class, the HttpServlet class
is provided to handle http protocol.
Two interfaces are defined for use with
HttpServlet class
– HttpServletRequest
– HttpServletResponse
These extend the ServletRequest &
ServletResponse.
Life Cycle of Servlet
Servlet life cycle is defined by
javax.servlet.Servlet inteface.
All servlets must implement
javax.servlet.Servlet interface to run in a
servlet engine.
Servlet Class
Instantiation & loading
Servlet engine can
instantiate more than one
servlet instance
Initialization
init(ServletConfig conf)
Garbage Collection
Server no longer
has a reference to
the object
Destruction
destroy()
Ready
service()
A service() executes
for each servlet instance
Creating servlets
protected void service(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException
Standard HTTP requests like Get and Post
are supported by doGet() and doPost().
HttpServletRequest
getMethod()
– Returns get/post with which request was made.
getQueryString()
getRemoteUser()
getRequestSessionId()
getSession(boolean)
– If FALSE returns current valid session otherwise
creates a new session.
isRequestedSessionIdValid()
getCookies()
HttpServletResponse
addCookie(Cookie)
– Add cookie to response
encodeUrl(String)
sendRedirect(String)
sendError(int)
Cookie Class
Cookie used for session management with HTTP
and HTTPS.
Used to get browsers to hold small data
associated with user’s browsing.
Cookies are named and have single value.
Assigned by the servers using fields added to
HTTP response headers.
Cookies are saved one at a time into HTTP
response headers using
javax.servlet.http.HttpServletResponse.addCooki
e().
Web browsers are expected to support 20
cookies per host of at least 4KB each.
HTTP request fields are retrieved using
javax.servlet.http.HttpServletRequest.getC
ookie().
This returns all cookies found in request.
Cookie Class
Cookie(String,String)
setDomain(String)
getDomain()
setMaxAge(int)
– Age in sec; 0 to delete
getMaxAge()
setValue(String)
getValue()
getName()
Example
FirstServlet.html
FirstServlet.java
STEPS
Set
classpath=c:/jsdk2.0/lib/jsdk.jar;C:/jsdk2.0/src
Compile .java file
– .class file should be in example directory
Run servletrunner
Run FirstServlet.html in browser
– C:\JSDK2.0\examples\FirstServlet.html
Survey.html
Survey.java