1. What is the Servlet? 1. What is the Servlet?
A servlet is a Java programming language class that is used to extend the capabilities of
A servlet is a Java programming language class that is used to extend the capabilities of serversservers that host applications accessed by means of a
that host applications accessed by means of a request- response programming model.request- response programming model. 2. What are the new features added to Servlet 2.5?
2. What are the new features added to Servlet 2.5? Following are the changes introduced in Servlet 2.5: Following are the changes introduced in Servlet 2.5:
•
• A new dependency on J2SE 5.0A new dependency on J2SE 5.0 •
• Support for annotationsSupport for annotations •
• Loading the classLoading the class •
• Several web.xml conveniencesSeveral web.xml conveniences •
• A handful of removed restrictionsA handful of removed restrictions •
• Some edge case clarificationsSome edge case clarifications
3. What are the uses of Servlet? 3. What are the uses of Servlet? Ty
Typical uses for pical uses for HTTP Servlets include:HTTP Servlets include:
•
• Processing and/or storing data submitted by an HTML form.Processing and/or storing data submitted by an HTML form.
•
• Providing dynamic content, e.g. returning the Providing dynamic content, e.g. returning the results of aresults of adatabase querydatabase queryto the client.to the client. •
• A Servlet can handle multiple request concurrently and be used to dA Servlet can handle multiple request concurrently and be used to d evelop highevelop high
performance system performance system
•
• Managing state information on top of the Managing state information on top of the stateless HTTPstateless HTTP, e.g. for an on, e.g. for an online shopping cartline shopping cart
system which manages shopping carts for many concurrent customers and maps every system which manages shopping carts for many concurrent customers and maps every request to the
request to the right customer.right customer. 4. What are the advantages of Servlet ove
4. What are the advantages of Servlet over CGI?r CGI? Servlets have several advantages over CGI: Servlets have several advantages over CGI:
•
• A Servlet does not run in a separate process. This removes the overhead of creating a newA Servlet does not run in a separate process. This removes the overhead of creating a new
process for each request. process for each request.
•
• A Servlet stays in memory between requests. A CGI program (and probably also anA Servlet stays in memory between requests. A CGI program (and probably also an
extensive runtime system or interpreter) needs to be loaded a
extensive runtime system or interpreter) needs to be loaded a nd started for each CGInd started for each CGI request.
request.
•
• There is only a single instance which answers all There is only a single instance which answers all requests concurrentlyrequests concurrently. This saves. This saves
memory and allows a Servlet to easily manage persistent data. memory and allows a Servlet to easily manage persistent data.
•
• Several web.xml conveniencesSeveral web.xml conveniences •
• A handful of removed restrictionsA handful of removed restrictions •
• Some edge case clarificationsSome edge case clarifications
5. What are the phases of the servlet life cycle? 5. What are the phases of the servlet life cycle? The life cycle of a servlet consists of the
•
• Servlet class loadingServlet class loading: For each servlet : For each servlet defined in the defined in the deployment descriptor of the Webdeployment descriptor of the Web
application
application, the servlet container locates and , the servlet container locates and loads a class of the type of the loads a class of the type of the servlet. Thisservlet. This can happen when
can happen when the servlet engine itself is started, or later when a the servlet engine itself is started, or later when a client request isclient request is actually delegated to the servlet.
actually delegated to the servlet.
•
• Servlet instantiationServlet instantiation: After loading, it instantiates one or more object instances of the: After loading, it instantiates one or more object instances of the
servlet class to service the client requests. servlet class to service the client requests.
•
• Initialization (call the init method)Initialization (call the init method): After instantiation, the container initializes a: After instantiation, the container initializes a
servlet before it is ready to handle client requ
servlet before it is ready to handle client requests. The container initializes the servlet byests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read
the init() method, the servlet can read configuration parameters from the deploymentconfiguration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked descriptor or perform any other one-time activities, so the init() method is invoked onceonce and only once b
and only once by the servlet container.y the servlet container.
•
• Request handling (call the service method)Request handling (call the service method): After the servlet is initialized, the: After the servlet is initialized, the
container may keep it ready for hand
container may keep it ready for handling client requests. When client requests arrive, theyling client requests. When client requests arrive, they are delegated to the servlet through
are delegated to the servlet through the service() method, passing the request andthe service() method, passing the request and
response objects as parameters. In the case of HTTP requests, the request and response response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse
objects are implementations of HttpServletRequest and HttpServletResponse respectively
respectively. In the . In the HttpServlet class, the service() method HttpServlet class, the service() method invokes a different handler invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
method for POST requests, and so on.
•
• Removal from service (call the destroy method)Removal from service (call the destroy method): A : A servlet container may decide servlet container may decide toto
remove a servlet from service for various reasons, such as
remove a servlet from service for various reasons, such as to conserve memory resources.to conserve memory resources. T
To do this, the servlet container co do this, the servlet container calls the destroy() method on the servlet. Once thealls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage
Now the servlet instance is eligible for garbage collectioncollection The life cycle of a servlet is controlled
The life cycle of a servlet is controlled by the container in which the servlet hby the container in which the servlet has beenas been deployed.
6. Why do we need a
6. Why do we need a constructor in a servlet if we use the constructor in a servlet if we use the init method?init method? Even though there is an
Even though there is an init method in a servlet which gets cainit method in a servlet which gets called to initialize it, a constructor islled to initialize it, a constructor is still required to instantiate the servlet. Even though you a
still required to instantiate the servlet. Even though you a s thes thedeveloperdeveloperwould never need towould never need to explicitly call the servlet's constructor, it is still being used by the container (the container still explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance
uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old javaof the servlet). Just like a normal POJO (plain old java object) that might have an init method
object) that might have an init method, it is no use calling the , it is no use calling the init method if you haven'tinit method if you haven't constructed an object to call it o
constructed an object to call it on yet.n yet. 7. How the servlet is loaded?
7. How the servlet is loaded? A servlet can be loaded when: A servlet can be loaded when:
•
• First request is made.First request is made. •
• Server starts up (auto-load).Server starts up (auto-load).
•
• There is only a single instance which answers all There is only a single instance which answers all requests concurrentlyrequests concurrently. This saves. This saves
memory and allows a Servlet to easily manage persistent data. memory and allows a Servlet to easily manage persistent data.
•
• Administrator manually loads.Administrator manually loads.
8. How a Servlet is unloaded? 8. How a Servlet is unloaded? A servlet is unloaded when: A servlet is unloaded when:
•
• Server shuts down.Server shuts down. •
9. What is Servlet interface? 9. What is Servlet interface? The central abstraction
The central abstraction in the Servlet API is the Servlet interface. All servlets implement thisin the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending
interface, either directly or , more commonly by extending a class that implements it.a class that implements it.
Note: Most Servlets, howev
Note: Most Servlets, howeverer, extend one of the , extend one of the standard implementations of that interface,standard implementations of that interface, namely
namely javax.servlet.GenericServletjavax.servlet.GenericServletandandjavax.servlet.http.HttpServletjavax.servlet.http.HttpServlet..
10. What is the Gen
10. What is the GenericServlet class?ericServlet class?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods dec
interface. In addition to the methods declared in these two interfaces, this class also provideslared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol. Note: This class is known as generic servlet, since it is not specific to any protocol.
11. What’
11. What’s the s the difference between GenericServlet and difference between GenericServlet and HttpServlet?HttpServlet?
GenericServlet HttpServlet
GenericServlet HttpServlet
The GenericServlet is an abstract class that is The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP extended by HttpServlet to provide HTTP protocol-specific methods.
protocol-specific methods.
An abstract class that
An abstract class that simplifies writing HTTPsimplifies writing HTTP servlets. It extends the GenericServlet base class servlets. It extends the GenericServlet base class and provides an framework for handling the and provides an framework for handling the HTTP protocol.
HTTP protocol. The GenericServlet does not include
The GenericServlet does not include protocol-specific methods for handling request
specific methods for handling request parameters, cookies, sessions and setting parameters, cookies, sessions and setting
response headers. response headers.
The HttpServlet subclass passes generic service The HttpServlet subclass passes generic service method requests to the relevant doGet() or method requests to the relevant doGet() or doPost() method.
doPost() method.
GenericServlet is not specific to any protocol.
GenericServlet is not specific to any protocol. HttpServlet only supports HTTP and HTTPSHttpServlet only supports HTTP and HTTPS protocol.
12. Why is HttpServlet declared
12. Why is HttpServlet declared abstract?abstract?
The HttpServlet class is declared abstract because the default implementations of the main The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and
service methods do nothing and must be overridden. This is a convenience must be overridden. This is a convenience implementation of theimplementation of the Servlet interface, which means that developers do not need to implement all service methods. If Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle
your servlet is required to handle doGet()doGet() requests for example, there is no need to write arequests for example, there is no need to write a doPost()
doPost() method too.method too.
13. Can servlet have a constructor? 13. Can servlet have a constructor?
One can definitely have constructor in servlet.Even
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for you can use the constrctor in servlet for initialization purpose,but this type of
initialization purpose,but this type of approch is not approch is not so common. Yso common. You can perform ou can perform commoncommon operations with the constructor as you normally do.The on
operations with the constructor as you normally do.The on ly thing is that you cannot call thatly thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In
constructor explicitly by the new keyword as we normally do.In the case of servlet, servletthe case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called b
container is responsible for instantiating the servlet, so the constructor is also called b y servlety servlet container only.
container only. 14.
14.What are the types of protocols supported by HttpServlet?What are the types of protocols supported by HttpServlet?
It extends the GenericServlet base class and provides a framework for handling the HTTP It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and
protocol. So, HttpServlet only supports HTTP and HTTPS protocol.HTTPS protocol.
15.What is the difference between doGet() and
15.What is the difference between doGet() and doPost()?doPost()?
#
# ddooGGeett(()) ddooPPoosstt(())
1 1
In doGet() the parameters are appended to In doGet() the parameters are appended to the URL and sent along with header the URL and sent along with header information.
information.
In doPost(), on the other hand will (typically) In doPost(), on the other hand will (typically) send the information through a socket back to send the information through a socket back to the webserver and it won't show up
the webserver and it won't show up in thein the URL bar.
URL bar.
2 2
The amount of information you can send The amount of information you can send back using a GET is restricted as URLs can back using a GET is restricted as URLs can
only be 1024 characters. only be 1024 characters.
Y
You can ou can send much more send much more information to theinformation to the server this way - and it's not restricted to server this way - and it's not restricted to textual data either. It is possible to
textual data either. It is possible to send filessend files and even binary data such
and even binary data such as serialized Javaas serialized Java objects!
objects!
3 3
doGet() is a request for information; it does doGet() is a request for information; it does not (or should not) change anything on the not (or should not) change anything on the server
server. (doGet() should be . (doGet() should be idempotent)idempotent)
doPost() provides information (such as doPost() provides information (such as placing an order for merchandise) that the placing an order for merchandise) that the
server is expected to remember server is expected to remember 4
4 PPaarraammeetteerrs s aarre e nnoot t eennccrryypptteedd PPaarraammeetteerrs s aarre e eennccrryypptteedd
5 5
doGet() is faster if we set the response doGet() is faster if we set the response content length since the same connection is content length since the same connection is used. Thus increasing the performance used. Thus increasing the performance
doPost() is generally used to update or post doPost() is generally used to update or post some information to the
some information to the serverserver.doPost is.doPost is slower compared to doGet since doPost does slower compared to doGet since doPost does not write the content length
not write the content length 6
6 doGdoGet(et() sho) should be iuld be idempdempoteotent. int. i.e. do.e. dogetget should be able to be repeated safely many should be able to be repeated safely many times
times
This method does not need to be idempotent. This method does not need to be idempotent. Operations requested through POST can have Operations requested through POST can have side effects for which the user can be held side effects for which the user can be held
accountable. accountable. 7
7 doGet() should be safe without any sidedoGet() should be safe without any side effects for which user is held responsible
effects for which user is held responsible This method does not need This method does not need to be either safeto be either safe 8
8 IIt t aalllloowws s bbooookkmmaarrkkss.. IIt t ddiissaalllloowws s bbooookkmmaarrkkss.. 16. When to use doGet() and
16. When to use doGet() and when doPost()?when doPost()?
Always prefer to use GET (As because GET is faster than POST), except mentioned in Always prefer to use GET (As because GET is faster than POST), except mentioned in thethe following reason:
following reason:
•
• If data is sensitiveIf data is sensitive •
• Date is greater than 1024 charactersDate is greater than 1024 characters •
• If your application don't need bookmarks.If your application don't need bookmarks.
17. How do I support
17. How do I support both GET and POST from the same Servlet?both GET and POST from the same Servlet? The easy way is, just support POST
The easy way is, just support POST, then have your doGe, then have your doGet method call your doPost method:t method call your doPost method:
public void
public void doGet(HttpServletRequestdoGet(HttpServletRequest requestrequest, HttpServletResponse, HttpServletResponse responseresponse)) throws
throws ServletException, IOExceptionServletException, IOException {
{
doPost(
doPost(requestrequest,, responseresponse);); }
}
18. Should I override the service() method? 18. Should I override the service() method? W
We never override the service e never override the service method, since the HTTP Servlets have already taken care of it .method, since the HTTP Servlets have already taken care of it . The default service function invokes the d
The default service function invokes the doXXX() method corresponding to the method oXXX() method corresponding to the method of theof the HTTP request.For example, if the HTTP request method
HTTP request.For example, if the HTTP request method is GETis GET, doGet() method is , doGet() method is called bycalled by default. A
default. A servlet should override the servlet should override the doXXX() method for the doXXX() method for the HTTP methods that servletHTTP methods that servlet supports. Because HTTP service method check the request method and
supports. Because HTTP service method check the request method and calls the appropriatecalls the appropriate handler method, it is not necessary to ove
handler method, it is not necessary to override the service method itself. Only override therride the service method itself. Only override the appropriate doXXX() method.
appropriate doXXX() method.
19. How the typical servlet code look like ? 19. How the typical servlet code look like ?
20. What is a servlet context object? 20. What is a servlet context object? A servlet context object contains the
A servlet context object contains the information about the Web application of which the information about the Web application of which the servletservlet is a part. It also provides access to the resources common to all the servlets in the application. is a part. It also provides access to the resources common to all the servlets in the application. Each W
Each Web application in a ceb application in a container has a single servlet context associated with it.ontainer has a single servlet context associated with it.
21. What are the differences between the ServletConfig interface and the ServletContext 21. What are the differences between the ServletConfig interface and the ServletContext interface?
interface?
S
SeerrvvlleettCCoonnffiigg SSeerrvvlleettCCoonntteexxtt
The ServletConfig interface is implemented by The ServletConfig interface is implemented by the servlet container in order to pass
the servlet container in order to pass
configuration information to a servlet. The configuration information to a servlet. The server passes an object that implements the server passes an object that implements the ServletConfig interface to the
ServletConfig interface to the servlet's init()servlet's init() method.
method.
A ServletContext defines a set of methods that a A ServletContext defines a set of methods that a servlet uses to communicate with its servlet servlet uses to communicate with its servlet container.
container.
There is one ServletConfig parameter per There is one ServletConfig parameter per servlet.
servlet.
There is one ServletContext for the entire There is one ServletContext for the entire
webapp and all the servlets in a webapp share it. webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object The param-value pairs for ServletConfig object are specified in the <init-param> within the are specified in the <init-param> within the <servlet> tags in the web.xml file
<servlet> tags in the web.xml file
The param-value pairs for ServletContext object The param-value pairs for ServletContext object are specified in the <context-param> tags in the are specified in the <context-param> tags in the web.xml file.
web.xml file.
22.What's the difference between forward() and sendRedirect() methods? 22.What's the difference between forward() and sendRedirect() methods?
ffoorrwwaarrdd(()) sseennddRReeddiirreecctt(())
A forward is performed internally by the servlet. A forward is performed internally by the servlet.
A redirect is a two step process, where the web A redirect is a two step process, where the web application instructs the browser to fetch a second application instructs the browser to fetch a second URL, which differs from the original.
URL, which differs from the original. The
The browser is browser is completely unaware that completely unaware that it hasit has taken place, so its original URL remains intact. taken place, so its original URL remains intact.
The browser, in this case, is doing the work and The browser, in this case, is doing the work and knows that it's making a new request.
knows that it's making a new request. Any browser reload of the resulting page will
Any browser reload of the resulting page will simple repeat the original request, with the original simple repeat the original request, with the original URL
URL
A browser reloads of the second
A browser reloads of the second URL ,will notURL ,will not repeat the original request, but will rather fetch the repeat the original request, but will rather fetch the second URL.
second URL. Both resources must be part of the
Both resources must be part of the same contextsame context (Some containers make provisions for cross-context (Some containers make provisions for cross-context communication but this tends not to be very
communication but this tends not to be very portable)
portable)
This method can be used to redirect users to This method can be used to redirect users to resources that are not part of the
resources that are not part of the current context, or current context, or even in the same domain.
even in the same domain.
Since both resources are part of same context, the Since both resources are part of same context, the original request context is retained
original request context is retained
Because this involves a new request, the previous Because this involves a new request, the previous request scope objects, with all of its parameters request scope objects, with all of its parameters and attributes are no longer available after a and attributes are no longer available after a redirect.
redirect. (V
(Variables will need to ariables will need to be passed bbe passed by via the sessiony via the session object).
object). Forward is marginally faster than redirect.
Forward is marginally faster than redirect. redirect is marginally slower than a forward, sinceredirect is marginally slower than a forward, since it requires two browser requests, not one.
it requires two browser requests, not one. 23. What is the difference between the include() and forward() methods?
23. What is the difference between the include() and forward() methods?
iinncclluuddee(()) ffoorrwwaarrdd(())
The
The RequestDispatcher include()RequestDispatcher include()methodmethod inserts the the contents of the specified resource inserts the the contents of the specified resource directly in the flow of the servlet response, as if directly in the flow of the servlet response, as if it were part of the calling servlet.
it were part of the calling servlet.
The
TheRequestDispatcher forward()RequestDispatcher forward()method ismethod is used to show a different resource in place of the used to show a different resource in place of the servlet that was originally called.
servlet that was originally called.
If you include a servlet or JSP document, the If you include a servlet or JSP document, the included resource must not attempt to change included resource must not attempt to change the response status code or HTTP headers, any the response status code or HTTP headers, any such request will be ignored.
such request will be ignored.
The forwarded resource may be another servlet, The forwarded resource may be another servlet, JSP or static HTML document, but the response JSP or static HTML document, but the response is issued under the same URL that was
is issued under the same URL that was
originally requested. In other words, it is not the originally requested. In other words, it is not the same as a redirection.
same as a redirection. The
The include()include() method is often used to includemethod is often used to include common "boilerplate" text or template markup common "boilerplate" text or template markup that may be included by many servlets.
that may be included by many servlets.
The
Theforward()forward() method is often used where amethod is often used where a servlet is taking a controller role; processing servlet is taking a controller role; processing some input and deciding the outcome by some input and deciding the outcome by
returning a particular response page. returning a particular response page.
24. What’s the use of the servlet
24. What’s the use of the servlet wrapper classes??wrapper classes?? The
The HttpServletRequestWrapperHttpServletRequestWrapperandand HttpServletResponseWrapperHttpServletResponseWrapperclasses are designed toclasses are designed to make it easy for developers to create c
make it easy for developers to create custom implementations of the servlet request and responseustom implementations of the servlet request and response types. The classes are constructed with the standard
types. The classes are constructed with the standardHttpServletRequestHttpServletRequestandand HttpServletResponse
HttpServletResponseinstances respectively and their default behaviour is to instances respectively and their default behaviour is to pass all methodpass all method calls directly to the underlying objects.
calls directly to the underlying objects. 25. What is
25. What is the directory structure the directory structure of a Wof a WAR file?AR file?
26. What is a deployment descriptor? 26. What is a deployment descriptor?
A deployment descriptor is an XML document with an .xml extension. It defines a component's A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a d
bean. The information provided by a deployment descriptor is declarative and therefore it can beeployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
modified without changing the source code of a bean.
The JavaEE server reads the deployment descriptor at run time and acts upon the component The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.
accordingly.
27. What is the difference between the getRequestDispatcher(String path) method of 27. What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface? javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
ServletRequest.getRequestDispatcher(String ServletRequest.getRequestDispatcher(String path) path) ServletContext.getRequestDispatcher(String ServletContext.getRequestDispatcher(String path) path) The
The getRequestDispatcher(String path)getRequestDispatcher(String path) method of
method of javax.servlet.ServletRequestjavax.servlet.ServletRequest interface accepts parameter the path to
interface accepts parameter the path to thethe resource to be included or forwarded to,
resource to be included or forwarded to, whichwhich can be relative to the reque
can be relative to the request of the callingst of the calling servlet. If the path begins with a “/” it is servlet. If the path begins with a “/” it is
interpreted as relative to the current context root. interpreted as relative to the current context root.
The
The getRequestDispatcher(String path)getRequestDispatcher(String path) method of
method of javax.servlet.ServletContextjavax.servlet.ServletContext interface cannot accept relative paths. All path interface cannot accept relative paths. All path must
must start start with with a “a “/” and /” and are are interpreted asinterpreted as relative to current context root.
28. What is preinitialization of a servlet? 28. What is preinitialization of a servlet?
A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it A container does not initialize the servlets as 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 receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can
defines the element, which can be specified in the deployment descriptor to make be specified in the deployment descriptor to make the servletthe servlet container load and initialize the servlet as
container load and initialize the servlet as soon as it starts up. The process of loading a soon as it starts up. The process of loading a servletservlet before any request comes in is called
before any request comes in is called preloading or preinitializing a servlet.preloading or preinitializing a servlet. 29. What is the <load-on-startup> element?
29. What is the <load-on-startup> element? The
The <load-on-startup><load-on-startup>element of a deployment descriptor is used to load a servlet file whenelement of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the
the server starts instead of waiting for the first request. It is also used to specify the order inorder in which the files are to be
which the files are to be loaded. The <load-on-startup> element is written in the deploymentloaded. The <load-on-startup> element is written in the deployment descriptor as follows: descriptor as follows: <servlet> <servlet> <servlet-name>ServletName</servlet-name> <servlet-name>ServletName</servlet-name> <servlet-class>ClassName</servlet-class> <servlet-class>ClassName</servlet-class> <load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup> </servlet> </servlet>
Note: The container loads the servlets in the order specified in the <load-on-startup> element. Note: The container loads the servlets in the order specified in the <load-on-startup> element.
30. What is session? 30. What is session? A sess
A session refers to all the requests that a ion refers to all the requests that a single client might make to asingle client might make to aserverserver in the course of in the course of viewing any pages associated with a given
viewing any pages associated with a givenapplicationapplication. Sessions are specific to both the. Sessions are specific to both the individual user and the application. As a result, every user of an app
individual user and the application. As a result, every user of an app lication has a separatelication has a separate session and has access to a
session and has access to a separate set of session variables.separate set of session variables.
31. What is
31. What is Session Tracking?Session Tracking?
Session tracking is a mechanism that servlets use to maintain state abou
Session tracking is a mechanism that servlets use to maintain state abou t a series of requests fromt a series of requests from the same user (that is, requests originating from the same browser) across some period
the same user (that is, requests originating from the same browser) across some period of time.of time. 32. What is the need of Session Tracking in web application?
32. What is the need of Session Tracking in web application?
HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information be more realistic they have to retain information across multiple requests. Such information
which is part of the application is reffered as "state". To keep track of this state we need session which is part of the application is reffered as "state". To keep track of this state we need session tracking.
T
Typical ypical example:example: Putting things one at a time into a shopping cart, then checking out--each pagePutting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.
request must somehow be associated with previous requests. 33. What are the types of Session Tracking ?
33. What are the types of Session Tracking ? Sessions need to work with all web browsers and
Sessions need to work with all web browsers and take into account the userstake into account the userssecuritysecurity preferences. Therefore there are a variety of ways to send
preferences. Therefore there are a variety of ways to send and receive the identifier:and receive the identifier:
•
• URL rewriting :URL rewriting : URL rewriting is a method of session tracking in which some extra daURL rewriting is a method of session tracking in which some extra da tata
(session ID) is appended at the end
(session ID) is appended at the end of each URL. This extra data identifies the session.of each URL. This extra data identifies the session. The server can associate this session identifier with the data it
The server can associate this session identifier with the data it has stored about thathas stored about that session. This method is used with browsers that do not support coo
session. This method is used with browsers that do not support coo kies or where the user kies or where the user has disabled the cookies.
has disabled the cookies.
•
• Hidden Form Fields :Hidden Form Fields :Similar to URL rewriting. The server embeds new hidden fields inSimilar to URL rewriting. The server embeds new hidden fields in
every dynamically generated form page for the
every dynamically generated form page for the client. When the client submits the formclient. When the client submits the form to the server the hidden fields identify the client.
to the server the hidden fields identify the client.
•
• Cookies :Cookies :Cookie is a Cookie is a small amount of information small amount of information sent by a servlet sent by a servlet to a Web browserto a Web browser..
Saved by the browser, and later sent back to the
Saved by the browser, and later sent back to the server in subsequent requests. A server in subsequent requests. A cookiecookie has a name, a
has a name, a single value, and optional attributes. A cookie's value can uniquely identifysingle value, and optional attributes. A cookie's value can uniquely identify a client.
a client.
•
• Secure Socket Layer (SSL) Sessions :Secure Socket Layer (SSL) Sessions :WWeb browsers that support eb browsers that support Secure Socket Layer Secure Socket Layer
communication can use SSL's support via HTTPS for generating
communication can use SSL's support via HTTPS for generating a unique session key asa unique session key as part of the encrypted conversation.
part of the encrypted conversation. 34. How do I use
34. How do I use cookies to store session state on the client?cookies to store session state on the client?
In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can
transmitted during client requests. JSPs can also use cookies, also use cookies, in scriptlet code or, preferably,in scriptlet code or, preferably, from within custom tag code.
from within custom tag code.
•
• TTo set a cookie on o set a cookie on the client, use the addCookie() method the client, use the addCookie() method in class HttpServletResponse.in class HttpServletResponse.
Multiple cookies may be set for the same
Multiple cookies may be set for the same request, and a single cookie request, and a single cookie name may havename may have multiple values.
multiple values.
•
• To get all of the cookies associated with a single HTTP request, use the getCookies()To get all of the cookies associated with a single HTTP request, use the getCookies()
method of class HttpServletRequest method of class HttpServletRequest
35. What are some advantages of storing session state in
35. What are some advantages of storing session state in cookies?cookies?
•
• Cookies are usually persistent, so for low-security sites, user data that needs to be Cookies are usually persistent, so for low-security sites, user data that needs to be storedstored
long-term (such as a user ID, historical information, etc.) can
long-term (such as a user ID, historical information, etc.) can be maintained easily withbe maintained easily with no server interaction.
no server interaction.
•
• For small- and medium-sized session data, the entire session data (instead of For small- and medium-sized session data, the entire session data (instead of just thejust the
session ID) can be kept in the cookie. session ID) can be kept in the cookie.
36.What are some disadvantages of storing session state in co
36.What are some disadvantages of storing session state in co okies?okies?
•
• Cookies are controlled Cookies are controlled by programming a low-level API, which is more by programming a low-level API, which is more difficult todifficult to
implement than some other approaches. implement than some other approaches.
•
• All data for a session are kept oAll data for a session are kept on the client. Corruption, expiration or purging of coon the client. Corruption, expiration or purging of coo kiekie
files can all result in incomplete, inconsistent, or missing information. files can all result in incomplete, inconsistent, or missing information.
•
• Cookies may not be available Cookies may not be available for many reasons: the user may have disabled them, for many reasons: the user may have disabled them, thethe
browser version may not support them, the browser ma
browser version may not support them, the browser ma y be behind ay be behind afirewallfirewallthat filtersthat filters cookies, and so on.
cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-sideServlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and
session state will not operate properly for all clients. Using cookies, and then switching tothen switching to an alternate client-side session state strategy in cases where cookies aren't ava
an alternate client-side session state strategy in cases where cookies aren't ava ilable,ilable, complicates development and maintenance.
complicates development and maintenance.
•
• Browser instances share cookies, so users cannot have Browser instances share cookies, so users cannot have multiple simultaneous sessions.multiple simultaneous sessions.
•
• Cookie-based solutions work only for HTTP clients. This is because cookies are a featureCookie-based solutions work only for HTTP clients. This is because cookies are a feature
of the HTTP protocol. Notice that the while package
of the HTTP protocol. Notice that the while packagejavax.servlet.httpjavax.servlet.httpsupportssupports session management (via class
session management (via classHttpSessionHttpSession), package), packagejavax.servletjavax.servlethas no suchhas no such support.
support.
37. What is URL rewriting? 37. What is URL rewriting?
URL rewriting is a method of session tracking in which some extra data
URL rewriting is a method of session tracking in which some extra data is appended at the enis appended at the end of d of each URL. This extra data identifies the session. The server can associate this session identifier each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about
with the data it has stored about that session.that session.
Every URL on the page must be encoded using method
Every URL on the page must be encoded using methodHttpServletResponseHttpServletResponse.encodeURL()..encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which
Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes sessionencodes session ID in the URL if the browser isn't accepting cookies, or if the
ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.session tracking is turned off. E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages Advantages •
• URL rewriting works just about everywhere, especially when cookies are turned off.URL rewriting works just about everywhere, especially when cookies are turned off. •
• Multiple simultaneous sessions are possible for Multiple simultaneous sessions are possible for a single user. Session information is locala single user. Session information is local
to each browser instance, since it's stored in
to each browser instance, since it's stored in URLs in each page being URLs in each page being displayed. Thisdisplayed. This scheme isn't foolproof, though, since users can
scheme isn't foolproof, though, since users can start a new browser instance using a URLstart a new browser instance using a URL for an active session, and con
for an active session, and confuse the server by interacting with the same session throughfuse the server by interacting with the same session through two instances.
two instances.
•
• Entirely static pages cannot be used with Entirely static pages cannot be used with URL rewriting, since every link must beURL rewriting, since every link must be
dynamically written with the session state. It is possible to combine static and d
dynamically written with the session state. It is possible to combine static and d ynamicynamic content, using (for example) templating or server-side includes. This limitation is also a 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.
barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages DisAdvantages •
• Every URL on a page which needs Every URL on a page which needs the session information must be rewritten each time athe session information must be rewritten each time a
page is served. Not only is this expen
page is served. Not only is this expensive computationallysive computationally, but it can g, but it can greatly increasereatly increase communication overhead.
communication overhead.
•
• URL rewriting limits the client's interaction with the URL rewriting limits the client's interaction with the server to HTTP GETserver to HTTP GETs, which cans, which can
result in awkward restrictions on the page. result in awkward restrictions on the page.
•
•
• If a client workstation crashes, all of the URLs (and If a client workstation crashes, all of the URLs (and therefore all of the data for thattherefore all of the data for that
session) are lost. session) are lost. 38. How can an
38. How can an existing session be invalidated? An existing session can be invalidated in theexisting session be invalidated? An existing session can be invalidated in the following two ways:
following two ways:
•
• Setting timeout in the deployment descriptor: This can be done by specifying timeoutSetting timeout in the deployment descriptor: This can be done by specifying timeout
between the
between the<session-timeout><session-timeout>tags as follows:tags as follows: <session-config> <session-config> < <session-timeout>10</session-timeout> session-timeout>10</session-timeout> </session-config> </session-config>
This will set the time for session timeout to be ten
This will set the time for session timeout to be ten minutes.minutes.
•
• Setting timeout programmatically: This will set the timeout Setting timeout programmatically: This will set the timeout for a specific session. Thefor a specific session. The
syntax for setting the timeout programmatically is as follows: syntax for setting the timeout programmatically is as follows: public void setMaxInactiveInterval(int interval) public void setMaxInactiveInterval(int interval) The
ThesetMaxInactiveInterval()setMaxInactiveInterval() method sets the maximum time in seconds before amethod sets the maximum time in seconds before a session becomes invalid.
session becomes invalid.
Note :Setting the inactive period a
Note :Setting the inactive period a s negative(-1), makes the container stop tracking s negative(-1), makes the container stop tracking session, i.e, session never expires.
session, i.e, session never expires. 39. How can the
39. How can the session in Servlet can be destroyed?session in Servlet can be destroyed?
An existing session can be destroyed in the following two ways: An existing session can be destroyed in the following two ways:
•
• Programatically : UsingProgramatically : Usingsession.invalidate()session.invalidate()method, which makes the container method, which makes the container
abonden the session on which the method is called. abonden the session on which the method is called.
•
• When the server itself is shutdown.When the server itself is shutdown.
40. A
40. A client sends requests to two different web components. Both of the client sends requests to two different web components. Both of the components access thecomponents access the session. Wi
session. Will they end ll they end up using the up using the same session object or same session object or different session ?different session ? Creates only one session i.e., they end
Creates only one session i.e., they end up with using same session .up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a
between client and a session.session. 41. What is servlet lazy loading? 41. What is servlet lazy loading?
•
• A container doesnot initialize the servlets ass soon as it starts up, it initializes a servletA 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. 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 The servlet specification defines the <load-on-startup> element, which can be specifiedbe specified
in the deployment descriptor to make the servlet container load and initialize the servlet in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
as soon as it starts up.
•
• The process of loading a The process of loading a servlet before any request comes in is called preloading servlet before any request comes in is called preloading or or
preinitializing a servlet. preinitializing a servlet. 42. What is Servlet Chaining? 42. What is Servlet Chaining?
Servlet Chaining is a method where the
Servlet Chaining is a method where the output of one servlet is piped output of one servlet is piped into a second servlet. Theinto a second servlet. The output of the second servlet could
output of the second servlet could be piped into a third be piped into a third servlet, and so on. The last servlet in theservlet, and so on. The last servlet in the chain returns the
chain returns the output to output to the Wthe Web browser.eb browser. 43. How are filters?
43. How are filters?
Filters are Java components that are used to
Filters are Java components that are used to intercept an incoming request to a Web resource andintercept an incoming request to a Web resource and a response sent back from the
a response sent back from the resource. It is used to abstract any useful information contained inresource. It is used to abstract any useful information contained in the request or response. Some of the
the request or response. Some of the important functions performed by filters are as follows:important functions performed by filters are as follows:
•
• Security checksSecurity checks •
• Modifying the request or responseModifying the request or response •
• Data compressionData compression •
• Logging and auditingLogging and auditing •
• Response compressionResponse compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change
required to recompile anything to change the input or output of the Web application.the input or output of the Web application. 44. What are the functions of an intercepting filter?
44. What are the functions of an intercepting filter? The functions of an intercepting filter are as follows: The functions of an intercepting filter are as follows:
•
• It intercepts the request from a client before it reacheIt intercepts the request from a client before it reache s the servlet and modifies thes the servlet and modifies the
request if required. request if required.
•
• It intercepts the response from the servlet back to It intercepts the response from the servlet back to the client and modifies the request if the client and modifies the request if
required. required.
•
• There can be many filters forming a chain, in which case the output of one filter becomesThere can be many filters forming a chain, in which case the output of one filter becomes
an input to the nex
an input to the next filtert filter. Hence, various modifications can be . Hence, various modifications can be performed on a singleperformed on a single request and response.
request and response.
45. What are the functions of the Servlet container? 45. What are the functions of the Servlet container? The functions of the Servlet container are as follows: The functions of the Servlet container are as follows:
•
• Lifecycle managementLifecycle management : It manages the life and death : It manages the life and death of a servlet, such as class loading,of a servlet, such as class loading,
instantiation, initialization, service, and making servlet instances eligible for garbage instantiation, initialization, service, and making servlet instances eligible for garbage collection.
collection.
•
• Communication supportCommunication support: It handles the communication between : It handles the communication between the servlet and thethe servlet and the
W
Web eb server.server.
•
• Multithreading supportMultithreading support: It automatically creates a new thread for every servlet request: It automatically creates a new thread for every servlet request
received. When the Servlet service() method completes, the thread dies. received. When the Servlet service() method completes, the thread dies.
•
• Declarative securityDeclarative security: It manages the security inside the XML deployment descriptor : It manages the security inside the XML deployment descriptor
file. file.
•
• JSP supportJSP support: The container is responsible for converting JSPs to servlets and for : The container is responsible for converting JSPs to servlets and for
intaining them. intaining them.