Professional Documents
Culture Documents
Servlets Notes PDF
Servlets Notes PDF
Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 1
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
utilities.
Powerful. Java servlets let you easily do several things that are difficult or impossible
with the regular CGI. For one thing, servlets can talk directly to Web server (regular
CGI programs can't). This simplifies operations that need to look up images and other
data stored in the standard places. Servlets can also share data among each other,
making the 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 computation.
Portable. Servlets are written in Java and followsss a well-standardized API.
Consequently, servlets written for, say I-Planet Enterprise Server can alsp run
virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported
directly or via a plugin on the almost every major Web server.
Inexpensive. There are also a number of free or very inexpensive Web servers
available that are good for "personal" use or low-volume Web sites. However, with
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 servlets support to it (if it doesn't come preconfigured to support
servlets) is generally free or cheap.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 2
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 3
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here are the signature of these two methods.
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet
container.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 4
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
Servlets - Examples
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 5
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel
(Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as
well in CLASSPATH.
Assuming your environment is setup properly, go in ServletDevel directory and compile
HelloWorld.java as follows:
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using
any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 6
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
If everything goes fine, above compilation would produce HelloWorld.class file in the
same directory. Next section would explain how a compiled servlet would be deployed in
production.
Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installation-
directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml
file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 7
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 8
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the
file paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands
today, the servlet API support Http Servlets, but in later date it can be extended for
another type of servlets.
Inexpensive
There are number of free web servers available for personal use or for commercial
purpose. Web servers are relatively expensive. So by using the free available web servers
you can add servlet support to it.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 9
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
Note: Most Servlets, however, extend one of the standard implementations of that interface,
namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 10
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
If data is sensitive
Data is greater than 1024 characters
If your application don't need bookmarks.
*10. .How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
doPost(request, response);
}
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 11
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
11. Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it.
The default service function invokes the doXXX() method corresponding to the method of the
HTTP request.For example, if the HTTP request method is GET, doGet() method is called by
default. A servlet should override the doXXX() method for the HTTP methods that servlet
supports. Because HTTP service method check the request method and calls the appropriate
handler method, it is not necessary to override the service method itself. Only override the
appropriate doXXX() method.
12.What are the differences between the ServletConfig interface and the ServletContext
interface?
ServletConfig ServletContext
The ServletConfig interface is implemented
by the servlet container in order to pass
A ServletContext defines a set of methods
configuration information to a servlet. The
that a servlet uses to communicate with its
server passes an object that implements the
servlet container.
ServletConfig interface to the servlet's init()
method.
There is one ServletContext for the entire
There is one ServletConfig parameter per
webapp and all the servlets in a webapp
servlet.
share it.
The param-value pairs for ServletConfig The param-value pairs for ServletContext
object are specified in the <init-param> object are specified in the <context-param>
within the <servlet> tags in the web.xml file tags in the web.xml file.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 12
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
context, the original request context is previous request scope objects, with all of its
retained parameters and attributes are no longer
available after a redirect.
(Variables will need to be passed by via the
session object).
redirect is marginally slower than a forward,
Forward is marginally faster than redirect. since it requires two browser requests, not
one.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 13
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
*15. What is session?
A session refers to all the requests that a single client might make to a server in the course of
viewing any pages associated with a given application. Sessions are specific to both the
individual user and the application. As a result, every user of an application has a separate
session and has access to a separate set of session variables.
For more information read the class notes and Java2 complete reference
Typical example: Putting things one at a time into a shopping cart, then checking out--each
page request must somehow be associated with previous requests.
URL rewriting : URL rewriting is a method of session tracking in which some extra data
(session ID) is appended at the end of each URL. This extra data identifies the session.
The server can associate this session identifier with the data it has stored about that
session. This method is used with browsers that do not support cookies or where the
user has disabled the cookies.
Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in
every dynamically generated form page for the client. When the client submits the
form to the server the hidden fields identify the client.
Cookies : Cookie is a small amount of information sent by a servlet to a Web browser.
Saved by the browser, and later sent back to the server in subsequent requests. A
cookie has a name, a single value, and optional attributes. A cookie's value can
uniquely identify a client.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 14
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer
communication can use SSL's support via HTTPS for generating a unique session key as
part of the encrypted conversation.
Cookies are usually persistent, so for low-security sites, user data that needs to be
stored long-term (such as a user ID, historical information, etc.) can be maintained
easily with no server interaction.
For small- and medium-sized session data, the entire session data (instead of just the
session ID) can be kept in the cookie.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 15
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
URL rewriting works just about everywhere, especially when cookies are turned off.
Multiple simultaneous sessions are possible for a single user. Session information is
local to each browser instance, since it's stored in URLs in each page being displayed.
This scheme isn't foolproof, though, since users can start a new browser instance using
a URL for an active session, and confuse the server by interacting with the same session
through two instances.
Entirely static pages cannot be used with URL rewriting, since every link must be
dynamically written with the session state. It is possible to combine static and dynamic
content, using (for example) templating or server-side includes. This limitation is also a
barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages
Every URL on a page which needs the session information must be rewritten each time
a page is served. Not only is this expensive computationally, but it can greatly increase
communication overhead.
URL rewriting limits the client's interaction with the server to HTTP GETs, which can
result in awkward restrictions on the page.
URL rewriting does not work well with JSP technology.
If a client workstation crashes, all of the URLs (and therefore all of the data for that
session) are lost.
Setting timeout in the deployment descriptor: This can be done by specifying timeout
between the <session-timeout>tags as follows:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
This will set the time for session timeout to be ten minutes.
Setting timeout programmatically: This will set the timeout for a specific session. The
syntax for setting the timeout programmatically is as follows:
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 16
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
24. A client sends requests to two different web components. Both of the components
access the session. Will they end up using the same session object or different session ?
Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping
between client and a session.
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet
when it receives a request for that servlet first time. This is called lazy loading.
The servlet specification defines the <load-on-startup> element, which can be
specified in the deployment descriptor to make the servlet container load and initialize
the servlet as soon as it starts up.
The process of loading a servlet before any request comes in is called preloading or
preinitializing a servlet.
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not
required to recompile anything to change the input or output of the Web application.
It intercepts the request from a client before it reaches the servlet and modifies the
request if required.
It intercepts the response from the servlet back to the client and modifies the request
if required.
There can be many filters forming a chain, in which case the output of one filter
becomes an input to the next filter. Hence, various modifications can be performed on
a single request and response.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 17
Servlets Notes
Sample Q & A on Servlets WEB TECHNOLOIGIES
Lifecycle management : It manages the life and death of a servlet, such as class loading,
instantiation, initialization, service, and making servlet instances eligible for garbage
collection.
Communication support : It handles the communication between the servlet and the Web
server.
Multithreading support : It automatically creates a new thread for every servlet request
received. When the Servlet service() method completes, the thread dies.
Declarative security : It manages the security inside the XML deployment descriptor file.
JSP support : The container is responsible for converting JSPs to servlets and for maintaining
them.
M.Gangappa,
Assoc Professor, CSE,VNRVJIET 18