Part4 - Servlet JSP Q and A
Q : What is servlet?
A: A servlet is a Java prog ramming lang uage class that is used to extend the capabilities of servers that host applications accessed by means of a request- response prog ramming model. Before the servlet, CGI scripting language was used as server side prog ramming language.
Q : What is the use of servlet?
A: Uses of servlet includes:
Processing and storing data submitted by an HT ML form.
Providing dynamic content.
A Servlet can handle multiple request concurrently and be used to develop hig h performance system
Manag ing state information on top of the stateless HT T P.
Q : What is the life c yc le of servlet?
A: Life cycle of Servlet:
Servlet class loading
Servlet instantiation
Initialization (call the init method)
Request handling (call the service method)
Removal from service (call the destroy method)
Q : Why do we need c onstruc tor in servlet if we use the init ()?
A: Even thoug h there is an init method in a servlet which g ets called to initialize it, a constructor is still required to
instantiate the servlet. Even thoug h you as the developer would never need to explicitly call the servlet's
constructor, it is still being used by the container.
Q : How servlet is loaded?
A: T he servlet is loaded by:
First request is made.
Server starts up (auto-load).
T here is only a sing le instance which answers all requests concurrently. T his saves memory and allows a
Servlet to easily manag e persistent data.
Administrator manually loads.
Q : When the servlet is unloaded?
A: Servlet g ets unloaded when:Server shuts down.
Administrator manually unloads.
Q : What is servlet interfac e?
A: T he central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either
directly or more commonly by extending a class that implements it.
Q : What is the g eneric servlet c lass?
A: GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In
addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle
methods init () and destroy (), and implements the log method declared in the ServletContext interface.
Q : What is the differenc e between Generic Servlet and HttpServlet?
A: T he difference is:
T he GenericServlet is an abstract class that is extended by HttpServlet to provide HT T P protocol-
specific methods. But HttpServlet extends the GenericServlet base class and provides a framework for
handling the HT T P protocol.
T he GenericServlet does not include protocol-specific methods for handling request parameters,
cookies, sessions and setting response headers. T he HttpServlet subclass passes g eneric service
method requests to the relevant doGet () or doPost () method.
GenericServlet is not specific to any protocol. HttpServlet only supports HT T P and HT T PS protocol.
Q : Why HttpServlet c lass is dec lared abstrac t?
A: T he HttpServlet class is declared abstract because the default implementations of the main service methods
do nothing and must be overridden. T his is a convenience implementation of the Servlet interface, which means
that developers do not need to implement all service methods.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method
too.
Q : Can servlet have a c onstruc tor?
A: Yes
Q : What are the type of protoc ols supported by the HttpServlet?
A: It extends the GenericServlet base class and provides a framework for handling the HT T P protocol. So,
HttpServlet only supports HT T P and HT T PS protocol.
Q : What is the differenc e between the doGet () and doPost ()?
A: T he difference is:
In doGet() the parameters are appended to the URL and sent along with header information. In doPost
(),send the information throug h a socket back to the webserver and it won't show up in the URL bar.
T he amount of information you can send back using a GET is restricted as URLs can only be 1024
characters. You can send much more information to the server by using post and it's not restricted to
textual data either. It is possible to send files and even binary data such as serialized Java objects!
DoGet() is a request for information.It does not chang e anything on the server. (doGet () should be
idempotent). doPost () provides information (such as placing an order for merchandise) that the server is
expected to remember.
Q : When to use doGet() and when doPost()?
A:Always prefer to use GET (As because GET is faster than POST ), except mentioned in the following reason:
If data is sensitive.Data is g reater than 1024 characters.
If your application don't need bookmarks.
Q : How do I support both doGet() and doPost() from same servlet?
A:T he easy way is, just support POST , then have your doGet method call your doPost method.
Q : Should I override the servic e() method?
A: We never override the service method, since the HT T P Servlets have already taken care of it. T he default
service function invokes the doXXX() method corresponding to the method of the HT T P request. For example,
if the HT T P request method is GET , doGet () method is called by default.
A servlet should override the doXXX() method for the HT T P methods that servlet supports. Because HT T P
service method checks 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.
Q : What is the ServletContext?
A: A servlet context object contains the information about the Web application of which the servlet is a part. It
also provides access to the resources common to all the servlets in the application. Each Web application in a
container has a sing le servlet context associated with it.
Q : What is the differenc e between the ServletConfig and ServletContext interfac e?
A: T he ServletConfig interface is implemented by the servlet container in order to pass config uration information
to a servlet. T he server passes an object that implements the ServletConfig interface to the servlet's init ()
method. A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
Q : What is the differenc e between forward () and sendRedirec t ()?
A: T he difference is:
A forward is performed internally by the servlet. A redirect is a two step process, where the web
application instructs the browser to fetch a second URL, which differs from the orig inal.
T he browser is completely unaware that it has taken place, so its orig inal URL remains intact. But in
sendRedirect, the browser, in this case, is doing the work and knows that it's making a new request.
Q : What is the differenc e between forward() and inc lude()?
A: T he RequestDispatcher include() method inserts the contents of the specified resource directly in the flow of
the servlet response, as if it were part of the calling servlet. T he RequestDispatcher forward() method is used to
show a different resource in place of the servlet that was orig inally called.
Q : What is the use of servlet wrapper c lasses?
A: T he HttpServletRequestWrapper and HttpServletResponseWrapper classes are desig ned to make it easy
for developers to create custom implementations of the servlet request and response types.
T he classes are constructed with the standard HttpServletRequest and HttpServletResponse instances
respectively and their default behaviour is to pass all method calls directly to the underlying objects.
Q : What is a deployment desc riptor?
A: A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment
setting s. It declares transaction attributes and security authorization for an enterprise bean.
T he information provided by a deployment descriptor is declarative and therefore it can be modified without
chang ing the source code of a bean.
Q : What is the preinitialization of servlet?
A: 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. T his is called lazy loading .
T he servlet specification defines the 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. T he process of loading a servlet before any
request comes in is called preloading or preinitializing a servlet.Q : What is the <load-on-startup> element?
A: T he <load-on-startup> element 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 order in which the files are to be loaded.
Q : What is session?
A: A session refers to all the requests that a sing le client mig ht make to a server in the course of viewing any
pag es associated with a g iven application. Sessions are specific to both the individual user and the application.
Q : What is the session trac king ?
A: Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same
user (requests orig inating from the same browser) across some period of time.
Q : What is the need of session trac king in web applic ation?
A: HT T P is a stateless protocol. Every request is treated as new request. For web applications to be more
realistic they have to retain information across multiple requests. Such information which is part of the application
is referred as "state". T o keep track of this state we need session tracking .
Q : What are the different types of session trac king ?
A: Different types are:
URL rewriting
Hidden Form Fields
Cookies
Secure Socket Layer (SSL) Sessions
Q : How do I use c ookies to store session state on c lient?
A: 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 transmitted during client
requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
T o set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies
may be set for the same request, and a sing le cookie name may have multiple values.
T o g et all of the cookies associated with a sing le HT T P request, use the g etCookies() method of class
HttpServletRequest
Q : What are the advantag es of storing session state in c ookies?
A: 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.
Q : What is URL rewriting ?
A: URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL.
T his extra data identifies the session. T he server can associate this session identifier with the data it has stored
about that session.
Q : How c an destroyed session in servlet?
A: Using session.invalidate() method.
Q : What is servlet lazy loading ?
A: 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. T his is called lazy loading .Q : What is servlet c haining ?
A: Servlet Chaining is a method where the output of one servlet is piped into a second servlet. T he output of the
second servlet could be piped into a third servlet, and so on. T he last servlet in the chain returns the output to the
Web browser
Q : What is filter?
A: Filters are Java components that are used to intercept an incoming request to a Web resource and a
response sent back from the resource. It is used to abstract any useful information contained in the request or
response.
Q : What are the advantag es of jsp over servlet?
A: T he advantag e of JSP is that they are document-centric. Servlets, on the other hand, look and act like
prog rams. A Java Server Pag e can contain Java prog ram frag ments that instantiate and execute Java classes,
but these occur inside an HT ML template file and are primarily used to g enerate dynamic content.
Some of the JSP functionality can be achieved on the client, using JavaScript. T he power of JSP is that it is
server-based and provides a framework for Web application development.
Q : What is the life c yc le of jsp?
A: Life cyle of jsp:
T ranslation
Compilation
Loading the class
Instantiating the class
jspInit()
_jspService()
jspDestroy()
Q : What is the jspInit() method?
A: T he jspInit() method of the javax.servlet.jsp.JspPag e interface is similar to the init() method of servlets. T his
method is invoked by the container only once when a JSP pag e is initialized. It can be overridden by a pag e
author to initialize resources such as database and network connections, and to allow a JSP pag e to read
persistent config uration data.
Q : What is the _jspServic e ()?
A: T he _jspService() method of the javax.servlet.jsp.HttpJspPag e interface is invoked every time a new
request comes to a JSP pag e. T his method takes the HttpServletRequest and HttpServletResponse objects as
its arg uments. A pag e author cannot override this method, as its implementation is provided by the container.
Q : What is the jspDestroy ()?
A: T he jspDestroy() method of the javax.servlet.jsp.JspPag e interface is invoked by the container when a JSP
pag e is about to be destroyed. T his method is similar to destroy() method of servlets. It can be overridden by a
pag e author to perform any cleanup operation such as closing a database connection.
Q : What jsp life c yc le method c an I override?
A: You cannot override the _jspService() method within a JSP pag e. You can however, override the jspInit()
and jspDestroy() methods within a JSP pag e. JspInit() can be useful for allocating resources like database
connections, network connections, and so forth for the JSP pag e. It is g ood prog ramming practice to free any
allocated resources within jspDestroy().
Q : What are implic it objec ts in jsp?A: Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each
pag e. T hese objects need not be declared or instantiated by the JSP author. T hey are automatically instantiated
by the container and are accessed using standard variables; hence, they are called implicit objects.
Q : How many implic it objec ts are available in jsp?
A: T hese implicit objects are available in jsp:
Request
Response
Pag eContext
session
application
Out
config
pag e
exception
Q : What are jsp direc tives?
A: JSP directives are messag es for the JSP eng ine. i.e., JSP directives serve as a messag e from a JSP pag e to
the JSP container and control the processing of the entire pag e.
T hey are used to set g lobal values such as a class declaration, method implementation, output content type, etc.
T hey do not produce any output to the client.
Q : What is pag e direc tive?
A: Pag e Directive is:
A pag e directive is to inform the JSP eng ine about the headers or facilities that pag e should g et from the
environment.
T he pag e directive is found at the top of almost all of our JSP pag es.
T here can be any number of pag e directives within a JSP pag e (althoug h the attribute – value pair must be
unique).
T he syntax of the include directive is: <%@ pag e attribute="value">
Q : What are the attributes of pag e direc tive?
A: T here are thirteen attributes defined for a pag e directive of which the important attributes are as follows:
Import: It specifies the packag es that are to be imported.
Session: It specifies whether a session data is available to the JSP pag e.
ContentT ype: It allows a user to set the content-type for a pag e.
IsELIg nored: It specifies whether the EL expressions are ig nored when a JSP is translated to a
servlet.
Q : What is the inc lude direc tive?
A: Include directive is used to statically insert the contents of a resource into the current JSP. T his enables a
user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
Q : What are the jsp standard ac tions?A: T he JSP standard actions affect the overall runtime behaviour of a JSP pag e and also the response sent back
to the client. T hey can be used to include a file at the request time, to find or instantiate a Java Bean, to forward a
request to a new pag e, to g enerate a browser-specific code, etc.
Q : What are the standards ac tions available in jsp?
A: T he standards actions include:
<jsp:include>
<jsp:forward>
<jsp:useBean>
<jsp:setProperty>
<jsp:g etProperty>
<jsp:param>
<jsp:plug in>
Q : What is the <jsp: useBean> standard ac tion?
A: T he <jsp: useBean> standard action is used to locate an existing Java Bean or to create a Java Bean if it does
not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully
qualified class path and type.
Q : What is the sc ope available in <jsp: useBean>?
A: Scope includes:
Pag e scope
Request scope
application scope
session scope
Q : What is the <jsp:forward> standard ac tion?
A: T he <jsp:forward> standard action forwards a response from a servlet or a JSP pag e to another pag e. T he
execution of the current pag e is stopped and control is transferred to the forwarded pag e.
Q : What is the <jsp: inc lude> standard ac tion?
A: T he <jsp: include> standard action enables the current JSP pag e to include a static or a dynamic resource at
runtime. In contrast to the include directive, include action is used for resources that chang e frequently. T he
resource to be included must be in the same context.
Q : What is the differenc e between inc lude direc tive and inc lude ac tion?
A: T he difference is:
Include directive, includes the content of the specified file during the translation phase–when the pag e is
converted to a servlet. Include action, includes the response g enerated by executing the specified pag e
(a JSP pag e or a servlet) during the request processing phase–when the pag e is requested by a user.
Include directive is used to statically insert the contents of a resource into the current JSP. Include
standard action enables the current JSP pag e to include a static or a dynamic resource at runtime.
Q : What is the differenc e between pag eContext.inc lude () and <jsp: inc lude>?
A: T he <jsp: include> standard action and the pag eContext.include() method are both used to include resources
at runtime. However, the pag eContext.include () method always flushes the output of the current pag e before
including the other components, whereas <jsp: include> flushes the output of the current pag e only if the value offlush is explicitly set to true.
Q : What is the <jsp: setProperty> ac tion?
A: You use jsp: setProperty to g ive values to properties of beans that have been referenced earlier.
Q : What is the <jsp: g etProperty> ac tion?
A: T he <jsp: g etProperty> action is used to access the properties of a bean that was set using the action. T he
container converts the property to a String as follows:
If it is an object, it uses the toString () method to convert it to a String . If it is a primitive, it converts it directly to a
String using the valueOf() method of the corresponding Wrapper class.
T he syntax of the <jsp: g etProperty> method is: <jsp: g etProperty name="Name" property="Property" />
Q : What is the <jsp: param> standard ac tion?
A: T he <jsp: param> standard action is used with <jsp: include> or <jsp: forward> to pass parameter names
and values to the targ et resource.
Q : What is the <jsp: plug in> ac tion?
A: T his action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the
browser run an applet using the Java plug in.
Q : What is the sc ripting element?
A: JSP scripting elements let you insert Java code into the servlet that will be g enerated from the current JSP
pag e.
Expressions
Scriptlet
Declarations
comment
Q : What is the sc riptlet?
A: A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a
servlet, the scriptlet code g oes into the service() method.
Hence, methods and variables written in scriptlet are local to the service() method. A scriptlet is written between
the <% and %>tag s and is executed by the container at request processing time.
Q : What is the jsp dec laration?
A: JSP declarations are used to declare class variables and methods in a JSP pag e. T hey are initialized when the
class is initialized. Anything defined in a declaration is available for the whole JSP pag e. A declaration block is
enclosed between the <%! and %>tag s. A declaration is not included in the service() method when a JSP is
translated to a servlet.
Q : What is the jsp expression?
A: A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand
representation for scriptlet. An expression is written between the <%= and %> tag s. It is not required to end the
expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tag s.
Q : How is sc ripting disabled?
A: Scripting is disabled by setting the scripting -invalid element of the deployment descriptor to true. It is a
subelement of jsp-property-g roup. Its valid values are true and false.
Q : Why is _jspServic e () start with ‘_’?
A: _jspService() method will be written by the container hence any methods which are not to be overridden bythe end user are typically written starting with a '_'. T his is the reason why we don't override _jspService()
method in any JSP pag e.
Q : How to pre-c ompile jsp?
A: Add jsp_precompile as a request parameter and send a request to the JSP file. T his will make the jsp pre-
compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.
Q : What is the benefit of pre-c ompile jsp pag e?
A: It removes the start-up lag that occurs when a container must translate a JSP pag e upon receipt of the first
request.
Q : What is the differenc e between variable dec lared inside the dec laration tag and variable
dec lared in sc riptlet?
A: Variable declared inside declaration part is treated as a instance variable and will be placed directly at class
level in the g enerated servlet. Variable declared in a scriptlet will be placed inside _jspService () method of
g enerated servlet. It acts as local variable.
Q : What are the three kind of c omment in jsp?
A: T hese are the three types of commenst in jsp:
JSP Comment: <%-- this is jsp comment -- %>
HT ML Comment: <!-- this is HT Ml comment -- >
Java Comments: <% // sing le line java comment /* this is multiline comment */ %>
Q : What is the output c omment?
A: T he comment which is visible in the source of the response is called output comment. <!-- this is HT Ml
comment -- >
Q : What is a hidden comment?
A: T his is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible. <%-- this is jsp comment -- %>
Q : How does jsp handle the run time exception?
A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
Q : How can I implement the thread safe jsp page?
A: You can make your JSPs thread-safe by having them implement the Sing leT hreadModel interface. This is done by adding the directive in the JSP.
<%@ page isThreadSafe="false" %>
Q : Is there a way to reference the “this” variable within the jsp?
A: Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet.
Q : Can you make the use of servletOutputStream object within jsp?
A: Yes. By using getOutputStream () method on response implicit object we can g et it.
Q : What is autoflush?
A: T his command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the pag e at the time of conversion of a JSP into servlet will result in error.
Q : What is the different scope available in jsp?
A:The different scopes are:
Page: Within the same page.
Request: After forward or include also you will g et the request scope data.
Session: After sendRedirect also you will g et the session scope data. All data stored in session is available to end user till session closed or browser closed.
Application: Data will be available throug hout the application. One user can store data in application scope and other can g et the data from application scope.
Q : When to use application scope?
A: If we want to make our data available to the entire application then we have to use application scope.
Q : Can a jsp page instantiate a serialized bean?
A: No problem! T he use Bean action specifies the bean Name attribute, which can be used for indicating a serialized bean.
Q : In which situation we c an use the static include and dynamic include?
A: If the target resource won’t change frequently, then it is recommended to use include directives. If the target resource will change frequently, then it is recommended to use include action.
A: A servlet is a Java prog ramming lang uage class that is used to extend the capabilities of servers that host applications accessed by means of a request- response prog ramming model. Before the servlet, CGI scripting language was used as server side prog ramming language.
Q : What is the use of servlet?
A: Uses of servlet includes:
Processing and storing data submitted by an HT ML form.
Providing dynamic content.
A Servlet can handle multiple request concurrently and be used to develop hig h performance system
Manag ing state information on top of the stateless HT T P.
Q : What is the life c yc le of servlet?
A: Life cycle of Servlet:
Servlet class loading
Servlet instantiation
Initialization (call the init method)
Request handling (call the service method)
Removal from service (call the destroy method)
Q : Why do we need c onstruc tor in servlet if we use the init ()?
A: Even thoug h there is an init method in a servlet which g ets called to initialize it, a constructor is still required to
instantiate the servlet. Even thoug h you as the developer would never need to explicitly call the servlet's
constructor, it is still being used by the container.
Q : How servlet is loaded?
A: T he servlet is loaded by:
First request is made.
Server starts up (auto-load).
T here is only a sing le instance which answers all requests concurrently. T his saves memory and allows a
Servlet to easily manag e persistent data.
Administrator manually loads.
Q : When the servlet is unloaded?
A: Servlet g ets unloaded when:Server shuts down.
Administrator manually unloads.
Q : What is servlet interfac e?
A: T he central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either
directly or more commonly by extending a class that implements it.
Q : What is the g eneric servlet c lass?
A: GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In
addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle
methods init () and destroy (), and implements the log method declared in the ServletContext interface.
Q : What is the differenc e between Generic Servlet and HttpServlet?
A: T he difference is:
T he GenericServlet is an abstract class that is extended by HttpServlet to provide HT T P protocol-
specific methods. But HttpServlet extends the GenericServlet base class and provides a framework for
handling the HT T P protocol.
T he GenericServlet does not include protocol-specific methods for handling request parameters,
cookies, sessions and setting response headers. T he HttpServlet subclass passes g eneric service
method requests to the relevant doGet () or doPost () method.
GenericServlet is not specific to any protocol. HttpServlet only supports HT T P and HT T PS protocol.
Q : Why HttpServlet c lass is dec lared abstrac t?
A: T he HttpServlet class is declared abstract because the default implementations of the main service methods
do nothing and must be overridden. T his is a convenience implementation of the Servlet interface, which means
that developers do not need to implement all service methods.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method
too.
Q : Can servlet have a c onstruc tor?
A: Yes
Q : What are the type of protoc ols supported by the HttpServlet?
A: It extends the GenericServlet base class and provides a framework for handling the HT T P protocol. So,
HttpServlet only supports HT T P and HT T PS protocol.
Q : What is the differenc e between the doGet () and doPost ()?
A: T he difference is:
In doGet() the parameters are appended to the URL and sent along with header information. In doPost
(),send the information throug h a socket back to the webserver and it won't show up in the URL bar.
T he amount of information you can send back using a GET is restricted as URLs can only be 1024
characters. You can send much more information to the server by using post and it's not restricted to
textual data either. It is possible to send files and even binary data such as serialized Java objects!
DoGet() is a request for information.It does not chang e anything on the server. (doGet () should be
idempotent). doPost () provides information (such as placing an order for merchandise) that the server is
expected to remember.
Q : When to use doGet() and when doPost()?
A:Always prefer to use GET (As because GET is faster than POST ), except mentioned in the following reason:
If data is sensitive.Data is g reater than 1024 characters.
If your application don't need bookmarks.
Q : How do I support both doGet() and doPost() from same servlet?
A:T he easy way is, just support POST , then have your doGet method call your doPost method.
Q : Should I override the servic e() method?
A: We never override the service method, since the HT T P Servlets have already taken care of it. T he default
service function invokes the doXXX() method corresponding to the method of the HT T P request. For example,
if the HT T P request method is GET , doGet () method is called by default.
A servlet should override the doXXX() method for the HT T P methods that servlet supports. Because HT T P
service method checks 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.
Q : What is the ServletContext?
A: A servlet context object contains the information about the Web application of which the servlet is a part. It
also provides access to the resources common to all the servlets in the application. Each Web application in a
container has a sing le servlet context associated with it.
Q : What is the differenc e between the ServletConfig and ServletContext interfac e?
A: T he ServletConfig interface is implemented by the servlet container in order to pass config uration information
to a servlet. T he server passes an object that implements the ServletConfig interface to the servlet's init ()
method. A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
Q : What is the differenc e between forward () and sendRedirec t ()?
A: T he difference is:
A forward is performed internally by the servlet. A redirect is a two step process, where the web
application instructs the browser to fetch a second URL, which differs from the orig inal.
T he browser is completely unaware that it has taken place, so its orig inal URL remains intact. But in
sendRedirect, the browser, in this case, is doing the work and knows that it's making a new request.
Q : What is the differenc e between forward() and inc lude()?
A: T he RequestDispatcher include() method inserts the contents of the specified resource directly in the flow of
the servlet response, as if it were part of the calling servlet. T he RequestDispatcher forward() method is used to
show a different resource in place of the servlet that was orig inally called.
Q : What is the use of servlet wrapper c lasses?
A: T he HttpServletRequestWrapper and HttpServletResponseWrapper classes are desig ned to make it easy
for developers to create custom implementations of the servlet request and response types.
T he classes are constructed with the standard HttpServletRequest and HttpServletResponse instances
respectively and their default behaviour is to pass all method calls directly to the underlying objects.
Q : What is a deployment desc riptor?
A: A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment
setting s. It declares transaction attributes and security authorization for an enterprise bean.
T he information provided by a deployment descriptor is declarative and therefore it can be modified without
chang ing the source code of a bean.
Q : What is the preinitialization of servlet?
A: 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. T his is called lazy loading .
T he servlet specification defines the 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. T he process of loading a servlet before any
request comes in is called preloading or preinitializing a servlet.Q : What is the <load-on-startup> element?
A: T he <load-on-startup> element 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 order in which the files are to be loaded.
Q : What is session?
A: A session refers to all the requests that a sing le client mig ht make to a server in the course of viewing any
pag es associated with a g iven application. Sessions are specific to both the individual user and the application.
Q : What is the session trac king ?
A: Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same
user (requests orig inating from the same browser) across some period of time.
Q : What is the need of session trac king in web applic ation?
A: HT T P is a stateless protocol. Every request is treated as new request. For web applications to be more
realistic they have to retain information across multiple requests. Such information which is part of the application
is referred as "state". T o keep track of this state we need session tracking .
Q : What are the different types of session trac king ?
A: Different types are:
URL rewriting
Hidden Form Fields
Cookies
Secure Socket Layer (SSL) Sessions
Q : How do I use c ookies to store session state on c lient?
A: 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 transmitted during client
requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
T o set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies
may be set for the same request, and a sing le cookie name may have multiple values.
T o g et all of the cookies associated with a sing le HT T P request, use the g etCookies() method of class
HttpServletRequest
Q : What are the advantag es of storing session state in c ookies?
A: 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.
Q : What is URL rewriting ?
A: URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL.
T his extra data identifies the session. T he server can associate this session identifier with the data it has stored
about that session.
Q : How c an destroyed session in servlet?
A: Using session.invalidate() method.
Q : What is servlet lazy loading ?
A: 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. T his is called lazy loading .Q : What is servlet c haining ?
A: Servlet Chaining is a method where the output of one servlet is piped into a second servlet. T he output of the
second servlet could be piped into a third servlet, and so on. T he last servlet in the chain returns the output to the
Web browser
Q : What is filter?
A: Filters are Java components that are used to intercept an incoming request to a Web resource and a
response sent back from the resource. It is used to abstract any useful information contained in the request or
response.
Q : What are the advantag es of jsp over servlet?
A: T he advantag e of JSP is that they are document-centric. Servlets, on the other hand, look and act like
prog rams. A Java Server Pag e can contain Java prog ram frag ments that instantiate and execute Java classes,
but these occur inside an HT ML template file and are primarily used to g enerate dynamic content.
Some of the JSP functionality can be achieved on the client, using JavaScript. T he power of JSP is that it is
server-based and provides a framework for Web application development.
Q : What is the life c yc le of jsp?
A: Life cyle of jsp:
T ranslation
Compilation
Loading the class
Instantiating the class
jspInit()
_jspService()
jspDestroy()
Q : What is the jspInit() method?
A: T he jspInit() method of the javax.servlet.jsp.JspPag e interface is similar to the init() method of servlets. T his
method is invoked by the container only once when a JSP pag e is initialized. It can be overridden by a pag e
author to initialize resources such as database and network connections, and to allow a JSP pag e to read
persistent config uration data.
Q : What is the _jspServic e ()?
A: T he _jspService() method of the javax.servlet.jsp.HttpJspPag e interface is invoked every time a new
request comes to a JSP pag e. T his method takes the HttpServletRequest and HttpServletResponse objects as
its arg uments. A pag e author cannot override this method, as its implementation is provided by the container.
Q : What is the jspDestroy ()?
A: T he jspDestroy() method of the javax.servlet.jsp.JspPag e interface is invoked by the container when a JSP
pag e is about to be destroyed. T his method is similar to destroy() method of servlets. It can be overridden by a
pag e author to perform any cleanup operation such as closing a database connection.
Q : What jsp life c yc le method c an I override?
A: You cannot override the _jspService() method within a JSP pag e. You can however, override the jspInit()
and jspDestroy() methods within a JSP pag e. JspInit() can be useful for allocating resources like database
connections, network connections, and so forth for the JSP pag e. It is g ood prog ramming practice to free any
allocated resources within jspDestroy().
Q : What are implic it objec ts in jsp?A: Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each
pag e. T hese objects need not be declared or instantiated by the JSP author. T hey are automatically instantiated
by the container and are accessed using standard variables; hence, they are called implicit objects.
Q : How many implic it objec ts are available in jsp?
A: T hese implicit objects are available in jsp:
Request
Response
Pag eContext
session
application
Out
config
pag e
exception
Q : What are jsp direc tives?
A: JSP directives are messag es for the JSP eng ine. i.e., JSP directives serve as a messag e from a JSP pag e to
the JSP container and control the processing of the entire pag e.
T hey are used to set g lobal values such as a class declaration, method implementation, output content type, etc.
T hey do not produce any output to the client.
Q : What is pag e direc tive?
A: Pag e Directive is:
A pag e directive is to inform the JSP eng ine about the headers or facilities that pag e should g et from the
environment.
T he pag e directive is found at the top of almost all of our JSP pag es.
T here can be any number of pag e directives within a JSP pag e (althoug h the attribute – value pair must be
unique).
T he syntax of the include directive is: <%@ pag e attribute="value">
Q : What are the attributes of pag e direc tive?
A: T here are thirteen attributes defined for a pag e directive of which the important attributes are as follows:
Import: It specifies the packag es that are to be imported.
Session: It specifies whether a session data is available to the JSP pag e.
ContentT ype: It allows a user to set the content-type for a pag e.
IsELIg nored: It specifies whether the EL expressions are ig nored when a JSP is translated to a
servlet.
Q : What is the inc lude direc tive?
A: Include directive is used to statically insert the contents of a resource into the current JSP. T his enables a
user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
Q : What are the jsp standard ac tions?A: T he JSP standard actions affect the overall runtime behaviour of a JSP pag e and also the response sent back
to the client. T hey can be used to include a file at the request time, to find or instantiate a Java Bean, to forward a
request to a new pag e, to g enerate a browser-specific code, etc.
Q : What are the standards ac tions available in jsp?
A: T he standards actions include:
<jsp:include>
<jsp:forward>
<jsp:useBean>
<jsp:setProperty>
<jsp:g etProperty>
<jsp:param>
<jsp:plug in>
Q : What is the <jsp: useBean> standard ac tion?
A: T he <jsp: useBean> standard action is used to locate an existing Java Bean or to create a Java Bean if it does
not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully
qualified class path and type.
Q : What is the sc ope available in <jsp: useBean>?
A: Scope includes:
Pag e scope
Request scope
application scope
session scope
Q : What is the <jsp:forward> standard ac tion?
A: T he <jsp:forward> standard action forwards a response from a servlet or a JSP pag e to another pag e. T he
execution of the current pag e is stopped and control is transferred to the forwarded pag e.
Q : What is the <jsp: inc lude> standard ac tion?
A: T he <jsp: include> standard action enables the current JSP pag e to include a static or a dynamic resource at
runtime. In contrast to the include directive, include action is used for resources that chang e frequently. T he
resource to be included must be in the same context.
Q : What is the differenc e between inc lude direc tive and inc lude ac tion?
A: T he difference is:
Include directive, includes the content of the specified file during the translation phase–when the pag e is
converted to a servlet. Include action, includes the response g enerated by executing the specified pag e
(a JSP pag e or a servlet) during the request processing phase–when the pag e is requested by a user.
Include directive is used to statically insert the contents of a resource into the current JSP. Include
standard action enables the current JSP pag e to include a static or a dynamic resource at runtime.
Q : What is the differenc e between pag eContext.inc lude () and <jsp: inc lude>?
A: T he <jsp: include> standard action and the pag eContext.include() method are both used to include resources
at runtime. However, the pag eContext.include () method always flushes the output of the current pag e before
including the other components, whereas <jsp: include> flushes the output of the current pag e only if the value offlush is explicitly set to true.
Q : What is the <jsp: setProperty> ac tion?
A: You use jsp: setProperty to g ive values to properties of beans that have been referenced earlier.
Q : What is the <jsp: g etProperty> ac tion?
A: T he <jsp: g etProperty> action is used to access the properties of a bean that was set using the action. T he
container converts the property to a String as follows:
If it is an object, it uses the toString () method to convert it to a String . If it is a primitive, it converts it directly to a
String using the valueOf() method of the corresponding Wrapper class.
T he syntax of the <jsp: g etProperty> method is: <jsp: g etProperty name="Name" property="Property" />
Q : What is the <jsp: param> standard ac tion?
A: T he <jsp: param> standard action is used with <jsp: include> or <jsp: forward> to pass parameter names
and values to the targ et resource.
Q : What is the <jsp: plug in> ac tion?
A: T his action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the
browser run an applet using the Java plug in.
Q : What is the sc ripting element?
A: JSP scripting elements let you insert Java code into the servlet that will be g enerated from the current JSP
pag e.
Expressions
Scriptlet
Declarations
comment
Q : What is the sc riptlet?
A: A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a
servlet, the scriptlet code g oes into the service() method.
Hence, methods and variables written in scriptlet are local to the service() method. A scriptlet is written between
the <% and %>tag s and is executed by the container at request processing time.
Q : What is the jsp dec laration?
A: JSP declarations are used to declare class variables and methods in a JSP pag e. T hey are initialized when the
class is initialized. Anything defined in a declaration is available for the whole JSP pag e. A declaration block is
enclosed between the <%! and %>tag s. A declaration is not included in the service() method when a JSP is
translated to a servlet.
Q : What is the jsp expression?
A: A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand
representation for scriptlet. An expression is written between the <%= and %> tag s. It is not required to end the
expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tag s.
Q : How is sc ripting disabled?
A: Scripting is disabled by setting the scripting -invalid element of the deployment descriptor to true. It is a
subelement of jsp-property-g roup. Its valid values are true and false.
Q : Why is _jspServic e () start with ‘_’?
A: _jspService() method will be written by the container hence any methods which are not to be overridden bythe end user are typically written starting with a '_'. T his is the reason why we don't override _jspService()
method in any JSP pag e.
Q : How to pre-c ompile jsp?
A: Add jsp_precompile as a request parameter and send a request to the JSP file. T his will make the jsp pre-
compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.
Q : What is the benefit of pre-c ompile jsp pag e?
A: It removes the start-up lag that occurs when a container must translate a JSP pag e upon receipt of the first
request.
Q : What is the differenc e between variable dec lared inside the dec laration tag and variable
dec lared in sc riptlet?
A: Variable declared inside declaration part is treated as a instance variable and will be placed directly at class
level in the g enerated servlet. Variable declared in a scriptlet will be placed inside _jspService () method of
g enerated servlet. It acts as local variable.
Q : What are the three kind of c omment in jsp?
A: T hese are the three types of commenst in jsp:
JSP Comment: <%-- this is jsp comment -- %>
HT ML Comment: <!-- this is HT Ml comment -- >
Java Comments: <% // sing le line java comment /* this is multiline comment */ %>
Q : What is the output c omment?
A: T he comment which is visible in the source of the response is called output comment. <!-- this is HT Ml
comment -- >
Q : What is a hidden comment?
A: T his is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible. <%-- this is jsp comment -- %>
Q : How does jsp handle the run time exception?
A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
Q : How can I implement the thread safe jsp page?
A: You can make your JSPs thread-safe by having them implement the Sing leT hreadModel interface. This is done by adding the directive in the JSP.
<%@ page isThreadSafe="false" %>
Q : Is there a way to reference the “this” variable within the jsp?
A: Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet.
Q : Can you make the use of servletOutputStream object within jsp?
A: Yes. By using getOutputStream () method on response implicit object we can g et it.
Q : What is autoflush?
A: T his command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the pag e at the time of conversion of a JSP into servlet will result in error.
Q : What is the different scope available in jsp?
A:The different scopes are:
Page: Within the same page.
Request: After forward or include also you will g et the request scope data.
Session: After sendRedirect also you will g et the session scope data. All data stored in session is available to end user till session closed or browser closed.
Application: Data will be available throug hout the application. One user can store data in application scope and other can g et the data from application scope.
Q : When to use application scope?
A: If we want to make our data available to the entire application then we have to use application scope.
Q : Can a jsp page instantiate a serialized bean?
A: No problem! T he use Bean action specifies the bean Name attribute, which can be used for indicating a serialized bean.
Q : In which situation we c an use the static include and dynamic include?
A: If the target resource won’t change frequently, then it is recommended to use include directives. If the target resource will change frequently, then it is recommended to use include action.