You are on page 1of 152

1

J2ee QUESTIONS
QUESTION NO : 1
QUESTION STATEMENT : Consider the following HTML form and corresponding servlet
//PostTest.html
<html>
<body>
<form method="POST" action="/servlet/PostTest">
val1=<input type="text" name="value1"><br>
val2=<input type="text" name="value2">
<input type="submit" name="AddButton">
</form>
</body>
</html>
//PostTest.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostTest extends HttpServlet
{
int sum = 0;
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
BufferedReader inReader = req.getReader();
PrintWriter out = res.getWriter();
String val1Str = inReader.readLine();
String val2Str = inReader.readLine();
out.println("value obtained manually = "+val1Str);
out.println("value obtained again manually is = "+val2Str);
out.println("val1 obtained again is = "+req.getParameter("value1"));
out.println("val2 obtained again is = "+req.getParameter("value2"));
}
}
The form PostTest.html is accessed in a browser, and the values entered are value1 = 500 and value2 = 600. What will
be displayed in the browser on clicking the 'submit' button?
CHOICES :
a)
Compile time error
b) value obtained manually = null

2
value obtained again manually is = null
val1 obtained again is = 500
val2 obtained again is = 600
c) value obtained manually = value1=500&value2=600&AddButton=Submit+Query
value obtained again manually is = null
val1 obtained again is = 500
val2 obtained again is = 600
d) value obtained manually = value1=500&value2=600&AddButton=Submit+Query
value obtained again manually is = null
val1 obtained again is = null
val2 obtained again is = null
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. If the parameter information sent to a servlet as encoded POST data has been read manually
using the Reader or InputStream obtained using the getReader() or getInputStream() method of the ServletRequest,
then, it cannot be read again. POST data can only be read once.

--------------------------------------------------------------------

QUESTION NO : 2
QUESTION STATEMENT : What will be the output of the following Servlet. For example, it can be invoked through a
Web Browser with the URL
http://<server-name>:8080/servlet/HelloServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>The Standard Hello World Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<b>doGet Hello World!!</b>");
out.println("</body>");
out.println("</html>");
out.close();

3
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>The Standard Hello World Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<b>doPost Hello World!!</b>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
CHOICES :
a)
b)
c)
d)

An HTML page displaying doGet Hello World!!


A blank HTML page
An HTML page displaying doPost Hello World!!
An error message

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. A blank HTML page will be displayed. The class javax.servlet.HttpServlet implements the
service() method, so that it calls the doGet or doPost method according to the HTTP Request (GET or POST
respectively) used to invoke the servlet. If we override the service() method in our Servlet class(which extends the
HttpServlet class), then, the default functionality of the service() method is lost, and the doGet() or doPost() method is
not invoked. Thus in the above case service() method will be called which does nothing.
--------------------------------------------------------------------

QUESTION NO : 3
QUESTION STATEMENT : Consider the following code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

<html>
<body>
<h1> This is My Counter </h1>

<% i++; %>


<%= "The value of i is:" + i %>
</body>

4
13:

</html>

Which of the following line of code should be placed at line 6 to make this JSP work (prints "The value of i:1")?
CHOICES :
a)
b)
c)
d)

<%@ int i = 0; %>


<% int i; %>
<%! int i = 0; %>
< int i = 0; />

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. To make the above JSP work, we need to declare variable i. The syntax
for declaring and intializing a variable in JSP is as follows:
<%! variable=variable_value ; %>
Thus C is the correct choice. The <%@ ... %> tag is used to declare directives like include directive. Thus choice A is
incorrect. The <% ... %> code is used to insert scriptlets (lines of code in java) like the one at line 8. The code written
inside the scriptlet becomes part of the service() method of the generated servlet. Thus 'i' becomes the local variable of
the service method. And for this JSP to compile properly, the variable 'i' should have been initialized. If "<% int i; %>"
is replaced by "<% int i=0; %>" , the choice B would also be correct. In the present scenario, the choice B will give
compilation error saying "Variable i may not have been initialized". Choice D is incorrect as it's not a valid tag.
--------------------------------------------------------------------

QUESTION NO : 4
QUESTION STATEMENT : JSP Custom tags can be nested within one another and can also communicate with each
other. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Custom tags can be nested within one another, allowing for complex interactions within a page. Here is an example
<tt:outerTag>
<tt:innerTag />
</tt:outerTag>
Also JSP custom tags can communicate with each other. You can create and initialize a JavaBeans component, create a
variable that refers to that bean in one tag, and then use the bean in another tag. In the example given below, tag1
creates an object named "myObj", which is then reused by tag2.
<tt:tag1 id="myObj" attr="value" />

5
<tt:tag2 name="myObj" />
--------------------------------------------------------------------

QUESTION NO : 5
QUESTION STATEMENT : Consider the following scenario:
Enterprise applications need to support multiple types of users with multiple types of interfaces. For example, an online
store may require an HTML front for Web customers, a WML front for wireless customers, a JFC/Swing interface for
administrators, and an XML-based Web service for suppliers.
Which of the following design patterns best meets the above requirements?
CHOICES :
a)
b)
c)
d)
e)

Value Objects
MVC
Data Access Object
Business Delegate
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. By applying the Model-View-Controller (MVC) architecture to a J2EE application, you separate
core data access functionality from the presentation and control logic that uses this functionality. Such separation allows
multiple views to share the same enterprise data model, which makes supporting multiple clients easier to implement,
test, and maintain. In this way the same controller can create multiple views of the same data.
--------------------------------------------------------------------

QUESTION NO : 6
QUESTION STATEMENT : The jsp:useBean element declares that the page will use a bean that is stored within and
accessible from the specified scope. Which of the following are valid scopes?
CHOICES :
a)
b)
c)
d)
e)
f)

application
session
state
request
response
page

CORRECT ANSWER : abdf


EXPLANATION :
A, B, D and F are correct. The "state" and "response" are invalid.

Here is the syntax used to declare that a page will use a java bean stored within and accessible from the specified scope:
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="page|request|session|application" />

--------------------------------------------------------------------

QUESTION NO : 7
QUESTION STATEMENT : Which of the following authentication type uses public-key encryption as a security
mechanism for a web application?
CHOICES :
a)
b)
c)
d)
e)

BASIC
DIGEST
FORM
CLIENT-CERT
None of these

CORRECT ANSWER : d
EXPLANATION :
D is the correct answer.
HTTP Basic Authentication, which is based on a username and password, is the authentication mechanism defined in
the HTTP/1.0 specification. It is not a secure authentication mechanism; the user information is send in simple base64
encoding.
Like BASIC authentication type, HTTP Digest Authentication authenticates a user based on a username and password.
It is more secure form; the user information is encrypted before its send to the server.
In FORM based authentication, the developer creates custom logic/error screens the display of which is managed by
web server.
End user authentication (CLIENT-CERT) using HTTPS (HTTP over SSL) is a strong authentication mechanism. This
mechanism requires the user to possess a Public Key Certificate (PKC).

--------------------------------------------------------------------

QUESTION NO : 8
QUESTION STATEMENT : To which of the following class or interface does the methods sendError() and setStatus()
belongs?
CHOICES :
a) HttpServletRequest
b) HttpServletResponse

7
c) ServletRequest
d) ServletResponse
e) None of the above
CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. The above methods belong to the HttpServletResponse interface. The sendError() methods
(there are two overloaded methods) return an error message to the client according to the status code. The setStatus()
methods are similar to the sendError methods. They set the HTTP status code to be included in the response. Please note
that the above methods also belong to the HttpServletResponseWrapper class (in javax.servlet.http package). This class
provides a convenient implementation of the HttpServletResponse interface that can be subclassed by developers
wishing to adapt the response from a Servlet.
--------------------------------------------------------------------

QUESTION NO : 9
QUESTION STATEMENT :
Implementations of ___ interface receive notifications about changes to the servlet context of the web application they
are part of. (Write only the interface name)
CHOICES :
a) ""
CORRECT ANSWER :
ServletContextListener
EXPLANATION :
Application event listeners are Java classes following the Java bean design that implement one or more of the event
listener interfaces in the Servlet API v 2.3. They are instantiated and registered in the web container at the time of the
deployment of the web application.
Servlet event listeners support event notifications for state changes in the ServletContext and HttpSession objects. The
objects implementing the ServletContextListener interface receive notification - when the servlet context has just been
created and is available to service its first request, or the servlet context is about to be shut down.
--------------------------------------------------------------------

QUESTION NO : 10
QUESTION STATEMENT : Rewritten URLs is not an efficient metthod used for state management in case the client
submits an HTML form rather than clicking a hyperlink. True/False?
CHOICES :
a) True

8
b) False
CORRECT ANSWER : a
EXPLANATION :
Rewritten URLs pass state information between the client and server by embedding information in the URL of all
hyperlinks within an HTML document. The information is passed in the query string of a URL in the form of
name/value pairs. For e.g.
http://www.whizlabs.com/servlets/SampleServlet?bcolor=blue
This method is only effecient when the client follows a hyperlink. If a client needs to submit an HTML form by clicking
a button, the Hidden Variables method is used.
--------------------------------------------------------------------

QUESTION NO : 11
QUESTION STATEMENT :
The use of the ___ interface guarantees that only one thread at a time will execute in a given servlet instance's service()
method.
CHOICES :
a) ""
CORRECT ANSWER :
SingleThreadModel
EXPLANATION :
The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in a given servlet
instance's service method. This interface doesn't prevent synchronization problems that result from servlets accessing
shared resources such as static class variables or classes outside the scope of the servlet.
--------------------------------------------------------------------

QUESTION NO : 12
QUESTION STATEMENT : Which of the following is the root of the deployment descriptor for a web application?
CHOICES :
a)
b)
c)
d)

web-app
web-application
web-root
app-root

9
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. The web-app element is the root of the deployment descriptor for a web application. Other
options are invalid elements and thus incorrect. Following is the DTD definition for web-app element:
<!ELEMENT web-app (icon?, display-name?, description?, distributable?,
context-param*, filter*, filter-mapping*, listener*, servlet*, servlet-mapping*,
session-config?, mime-mapping*, welcome-file-list?, error-page*,
taglib*, resource-env-ref*, resource-ref*, security-constraint*, login-config?,
security-role*, env-entry*, ejb-ref*, ejb-local-ref*)>
--------------------------------------------------------------------

QUESTION NO : 13
QUESTION STATEMENT : Once an object is added to an HttpSession, it can't be removed. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
An object bound to an HttpSession can be removed using the following method of the HttpSession interface:
removeAttribute(String) : public void removeAttribute(java.lang.String name)
Removes the object bound with the specified name from this session. If the session does not have an object bound with
the specified name, this method does nothing. After this method executes, and if the object implements
HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. The container then notifies
any HttpSessionAttributeListeners in the web application.
Parameters:
name - the name of the object to remove from this session
--------------------------------------------------------------------

QUESTION NO : 14
QUESTION STATEMENT : Which of the following elements is used to send a request from one JSP page to another
and also includes the response in the response from the calling page?
CHOICES :
a)
b)
c)
d)

jsp:useBean
jsp:setProperty
jsp:forward
jsp:include

10
e) None of the above
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The jsp:include action allows a static or dynamic resource to be included in the current JSP at
request time. The resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />
The jsp:include action may have jsp:param sub elements that can provide values for some parameters in the request to
be used for inclusion. Request processing resumes in the calling JSP page, once the inclusion is completed.
Here is an example of jsp:include action used to include copyright statement in the web page:
<jsp:include page="/mypages/copyright.html" />

--------------------------------------------------------------------

QUESTION NO : 15
QUESTION STATEMENT : Which of the statements below is true for a web application using session management?
a.) The session object is invalidated, when the session times out.
b.) The session object is invalidated, when sessionInvalidate() method of HttpSession is invoked.
CHOICES :
a)
b)
c)
d)

Both of the above statements are true.


Only statement a.) is true.
Only statement b.) is true.
None of the above statements is true.

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. The session object will become invalid in either of the following scenarios:
a.) When the session times out.
b.) When invalidate() method of the HttpSession interface is invoked.
Please note that invalidate() and not sessionInvalidate() is the method of HttpSession interface. Thus choice B is correct.
--------------------------------------------------------------------

QUESTION NO : 16
QUESTION STATEMENT : In most Web server implementations, a new servlet object is not instantiated for each new
client request. Rather, a single servlet object usually services all requests.

11

CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. In most web server implementation, a single servlet instance services all requests. The server
spawns a new thread for each call to the service() method. The multithreaded nature of servlets allows many service()
methods to execute simultaneously. Conversely, if the server creates a pool of servlet instances, it may not spawn a new
thread for each call to the service() method. Rather, it may simply select a new instance from the pool of available
instances.

--------------------------------------------------------------------

QUESTION NO : 17
QUESTION STATEMENT : You add web components to a J2EE application in a package called WAR (web application
archive). A WAR has a specific hierarchical directory structure. Which of the following directory stores the deployment
descriptor for a Web application located in the myapp directory?
CHOICES :
a)
b)
c)
d)

myapp/WEB-INF/public_html
myapp/WEB-INF/classes
myapp/WEB-INF
myapp/WEB-INF/lib

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. An application located in the myapp directory will have its deployment descriptor in the
myapp/WEB-INF directory. A is incorrect as public_html is not applicable for storing deployment descriptor of a web
application. B is incorrect as the "classes" subdirectory contains server side classes: servlet, utility classes, and
JavaBean components. D is incorrect as the "lib" subdirectory contains JAR archives of libraries (tag libraries and any
utility libraries called by server side classes).
--------------------------------------------------------------------

QUESTION NO : 18
QUESTION STATEMENT : In the context of Servlets, State Management and Session Management have no
difference. True/False?
CHOICES :

12
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
State management is the ability to maintain client's current state by passing client-specific information between the
client and the server. In contrast, session management provides an association between the client and the server that
allows server to uniquely identify each client. This association persists across the requests for a specified period of time.
Allowing clients to select their background color of an their html page is an example of state management. With state
management, the client identity can't be maintained. For e.g., two clients select red as their background color. With only
state management, the server can determine the preferred background color for each of these clients but it cannot
distinguish one client from the other. The solution to this is the session management, which is the superset of state
management and maintains both state as well as identity.

--------------------------------------------------------------------

QUESTION NO : 19
QUESTION STATEMENT : Which of the following statements regarding event listeners of a web application are true?
CHOICES :
a) Application event listeners are Java classes following the Java bean design that implement one or more of the event
listener interfaces.
b) The web container creates an instance of each listener and registers it for even notification after the processing of the
first request by the application.
c) During web application execution listeners are invoked in the order of their registration.
d) On application shutdown, listeners are notified in the reverse order to their declarations in the deployment descriptor.
CORRECT ANSWER : acd
EXPLANATION :
Choices A, C and D are correct. Application event listeners are Java classes following the Java bean design that
implement one or more of the event listener interfaces. The web container creates an instance of each listener and
registers it for even notifications "prior" to the processing of the first request by the application. Thus choice B is
incorrect. There may be multiple listener classes listening to each event type and the web container registers the listener
instances according to the interfaces they implement and the order in which they appear in the deployment descriptor.
During web application execution listeners are invoked in the order of their registration. On application shutdown,
listeners are notified in the reverse order to their declarations with notifications to sessions listeners preceding
notifications to context listeners: Session listeners must be notified of session invalidations prior to context listeners
being notified of application shutdown.
--------------------------------------------------------------------

QUESTION NO : 20
QUESTION STATEMENT : Following is the Deployment Descriptor entry for a web application using Servlet Context
initialization parameters:

13

<web-app>
...
<context-param>
<param-name>Bill Gates</param-name>
// xxx
</context-param>
...
</web-app>
Which of the following elements to be placed at "// xxx" is valid?
CHOICES :
a)
b)
c)
d)

<param-size>
<param-type>
<param-value>
<param-class>

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The "context-param" element contains the declaration of a web application's servlet context
initialization parameters. The param-name element contains the name of a parameter. Each parameter name must be
unique in the web application. The param-value element contains the value of a parameter.
Here is the DTD for "context-param" element:
<!ELEMENT context-param (param-name, param-value, description?)>
The <param-size>, <param-type> and <param-class> are invalid elements. Thus choice C is correct and others are
incorrect.
--------------------------------------------------------------------

QUESTION NO : 21
QUESTION STATEMENT :
The ____ element is used to declare scripting language constructs that are available to all other scripting elements. (e.g.
format for writing the element name - jsp:scriptlet, no braces <>)
CHOICES :
a) ""
CORRECT ANSWER :
jsp:declaration
EXPLANATION :

14
Declarations are used to declare variables and methods in the scripting language used in a JSP page. A declaration
should be a complete declarative statement, or sequence thereof, according to the syntax of the scripting language
specified. Declarations do not produce any output into the current out stream. Declarations are initialized when the JSP
page is initialized and are made available to other declarations, scriptlets, and expressions.
Examples
For example, the first declaration below declares an integer, and initializes it to zero. The second declaration declares a
method.
<%!int i =0;%>
<%!public String f(int i){if (i<3)return("...");...}%>
Syntax
<%! declaration(s) %>
The jsp:declaration element is used to declare scripting language constructs that are available to all other scripting
elements. A jsp:declaration element has no attributes and its body is the declaration itself.
Its syntax is:<jsp:declaration>declaration goes here </jsp:declaration>

--------------------------------------------------------------------

QUESTION NO : 22
QUESTION STATEMENT : Which of the following statements are true regarding the include() and forward() methods
of RequestDispatcher class?
CHOICES :
a) The forward() method allows you to programatically forward a request to another servlet (or other server resource)
known as delegate.
b) The include() method allows you to programatically include content generated by another servlet (or other server
resource) within the body of the calling servlet's response.
c) In case of forward(), the control is returned to the calling servlet once the delegate servlet completes its processing.
d) In case of include(), the control is returned to the calling servlet once the delegate servlet completes its processing.
CORRECT ANSWER : abd
EXPLANATION :
A, B and D are correct choices. With 2.1 version of Servlet API, the RequestDispatcher object allows to programatically
forward requests to and include context from other server resource. This is the only purpose of RequestDispactcher
object, which includes two methods - forward() and include(). Unlike the include() method, control will never return to
the servlet that forwards the request. The forward() method passes all control to the delegate servlet which will generate
the response.

--------------------------------------------------------------------

15

QUESTION NO : 23
QUESTION STATEMENT : Which of the following declarations used for including a Web Component into the JSP
page are correct syntactically?
CHOICES :
a)
b)
c)
d)

<jsp:include page="url" flush="true" />


<jsp:include file="Filename" flush="true" />
<%@ include page="url" %>
<%@ include file="Filename" %>

CORRECT ANSWER : ad
EXPLANATION :
Choice A and D are correct. The include directive notifies the web container/server to include the content of the
resource in the current JSP, inline, at the specified place. Here is the syntax for that:
<%@ include file="Filename" %>
The jsp:include action allows a static or dynamic resource to be included in the current JSP at request time. The
resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />

--------------------------------------------------------------------

QUESTION NO : 24
QUESTION STATEMENT : In case of the nested tags, which of the following methods can be used for accessing the
parent handler of the enclosing tag?
CHOICES :
a)
b)
c)
d)

getParent()
getAncestor()
findParentWithClass()
findAncestorWithClass()

CORRECT ANSWER : ad
EXPLANATION :
A and D are correct choices. To access an object created by an enclosing tag, a tag handler must first obtain its
enclosing tag with either of the following static method invocations:
TagSupport.getParent()
TagSupport.findAncestorWithClass(from, class)
The parent handler's statically and dynamically created objects can be obtained once the parent object is retrieved.

16

--------------------------------------------------------------------

QUESTION NO : 25
QUESTION STATEMENT :
The setHeader() method of the ____ interface is used to set headers of an HTTP response.
CHOICES :
a) ""
CORRECT ANSWER :
HttpServletResponse
EXPLANATION :
A servlet can set headers of an HTTP response via the following methods of theHttpServletResponse interface:
- setHeader
- addHeader
The setHeader method sets a header with a given name and value. A previous header is replaced by the new header.
Where a set of header values exist for the name, the values are cleared and replaced with the new value. The addHeader
method adds a header value to the set with a given name. If there are no headers already associated with the name, a
new set is created. Headers may contain data that represents an int or a Date object. The following convenience methods
of the HttpServletResponse interface allow a servlet to set a header using the correct formatting for the appropriate data
type:
-setIntHeader
-setDateHeader
-addIntHeader
-addDateHeader
To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set
after the response is committed will be ignored by the servlet container. Servlet programmers are responsible for
ensuring that the Content-Type header is appropriately set in the response object for the content the servlet is generating. The HTTP 1.1 specification does not require that this header be set in an HTTP response. Servlet containers
must not set a default content type when the servlet programmer does not set the type.
Please note that the above methods also belong to the HttpServletResponseWrapper class (in javax.servlet.http
package). It provides a convenient implementation of the HttpServletResponse interface that can be subclassed by
developers wishing to adapt the response from a Servlet.
--------------------------------------------------------------------

QUESTION NO : 26
QUESTION STATEMENT : Which of the following is not a standard method of the JSP life cycle?

17

CHOICES :
a)
b)
c)
d)

jspService()
_jspService()
jspInit()
jspDestroy()

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. The standard life cycle methods of JSP are : jspInit(), _jspService() and jspDestroy().
The JSP specification defines the contract between the JSP container and the JSP page author. This contract defines the
assumptions an author can make for the actions described in the JSP page. The main portion of this contract is the
_jspService() method that is generated automatically by the JSP container from the JSP page.
When the first request is delivered to a JSP page, a jspInit()method, if present, will be called to prepare the page.
Similarly, a JSP container may invoke a JSP's jspDestroy()method to reclaim the resources used by the JSP page at any
time when a request is not being serviced. This is the same life-cycle as for servlets.
--------------------------------------------------------------------

QUESTION NO : 27
QUESTION STATEMENT : Consider the JSP (MyJSP.jsp) and JavaBean (MyBean.java) shown below. Which of the
following lines of code should be placed at //xxx position in JSP to print "My name is : James Gosling" ?
//MyJSP.jsp...
<jsp:useBean id="mybean" class="MyBean" />
<html>
<body bgcolor="#FFFFFF">
My name is : //xxx
</body>
</html>
//MyBean.java ...
public class MyBean
{
private String myName;
public MyBean()
{
myName = "James Gosling";
}
public String getName()
{
return myName;

18
}
public void setName(String name)
{
myName = name;
}
}
CHOICES :
a)
b)
c)
d)
e)
f)

<% mybean.getName() %>


<% mybean.getName(); %>
<%= mybean.getName() %>
<%= mybean.getName(); %>
<%@ mybean.getName() %>
<%@ mybean.getName(); %>

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. In the above code, we need to call the getName() method of MyBean class. To do that, JSP
expression is needed the syntax of which is as follows:
<%= Java expression %>
Also please note that the expressions (<%= ... %>) in JSP doesn't ends with semicolons. Thus choice D will give
compilation error.
The <%@ ... %> syntax is used for JSP directives like include etc. Thus the code in choice E and F will compilation
error.
The <% ... %> is used for inserting scriplets (lines of Java code) into a JSP page. JSP on compilation gets converted into
Servlet, the code inside <% %> gets put into the service method of the resulting servlet. A scriplet statement like any
java statement ends with ';'. Thus the code in choice A will give compilation error. Although choice B will compile fine
but nothing will be printed out on execution of getName() method.
--------------------------------------------------------------------

QUESTION NO : 28
QUESTION STATEMENT : Custom Tags in JSP cooperate by sharing objects. Which of the following styles of object
sharing are correct?
CHOICES :
a) A shared object be named and stored in the page context. To access objects created and named by another tag, a tag
handler uses the pageContext.getAtrribute(name, scope) method.
b) A shared object be named and stored in the page context. To access objects created and named by another tag, a tag
handler uses the pageContext.getObject(name, scope) method.
c) An object created by the enclosing tag handler of a group of nested tags is available to all inner tag handlers.
d) An object created by the enclosed tag handler of a group of nested tags is available to all outer tag handlers.

19
CORRECT ANSWER : ac
EXPLANATION :
A and C are correct choices. JSP technology supports two styles of object sharing:
a.) The first style requires that a shared object be named and stored in the page context (one of the implicit objects
accessible to both JSP pages and tag handlers). To access objects created and named by another tag, a tag handler uses
the pageContext.getAtrribute(name, scope) method.
b.) In the second style of object sharing, an object created by the enclosing tag handler of a group of nested tags is
available to all inner tag handlers. This form of object sharing has the advantage that it uses a private namespace for the
objects, thus reducing the potential for naming conflicts.
Thus choice A and C are correct and others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 29
QUESTION STATEMENT : Which of the following are possible ways for a servlet to send an HTTP redirect?
CHOICES :
a)
b)
c)
d)

Manually set the HTTP status code and add the Location header to the response.
Use the sendRedirect() method of the HttpServletResponse interface.
Use the sendRedirect() method of the HttpServletRequest interface.
By implementing the ServletRedirect interface.

CORRECT ANSWER : ab
EXPLANATION :
A and B are correct choices. The following code inside the service() method of a servlet demonstrates how can a servlet
send an HTTP redirect as stated in choice A :
String myString ="http://www.whizlabs.com/jwhiz.html";
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", myString);
The following code of service() method uses the sendRedirect() method of HttpServletResponse interface for HTTP
redirect :
response.sendRedirect("http://www.whizlabs.com/jwhiz.html");
Choice C is incorrect as sendRedirect() method belongs to HttpServletResponse interface. Choice D is incorrect as there
is no ServletRedirect interface in servlet API.
--------------------------------------------------------------------

QUESTION NO : 30

20
QUESTION STATEMENT : All JSP pages, by default take part in an HTTP session. Which of the following is true
regarding the values which can be put into a session?
CHOICES :
a)
b)
c)
d)

Only JavaBeans component can be put into a session.


Any Java object can be placed into a session.
Only String objects can be placed into a session.
Any Java variable (primitives, objects) can be placed into a session.

CORRECT ANSWER : b
EXPLANATION :
B is correct. Any valid Java object can be stored in a session. A session object is identified by a session ID which is a
unique key. Primitives can't be placed into a session. You need to wrap a primitive first (using a wrapper class, e,g. for
int Integer is used to wrap the int variable) to store it into a session. Here is an example which stores an object of type
MyObject (user defined object) into a session. The object is identified with the key "obj".
<%
MyObject myObject = new MyObject();
session.putValue("obj", myObject");
%>
To retrieve an instance of this object, following code is used:
<% MyObject myObj = (MyObject)session.getValue("obj"); %>
--------------------------------------------------------------------

QUESTION NO : 31
QUESTION STATEMENT : How does one acquire the object implementing RequestDispatcher interface?
CHOICES :
a)
b)
c)
d)

Using getRequestDispatcher() method of RequestDispatcher interface.


Using getRequestDispatcher() method of ServletContext interface.
Using getDispatcher() method of RequestDispatcher interface.
Using getDispatcher() method of ServletContext interface.

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. An object that implements RequestDispatcher interface can be acquired using the
getRequestDispatcher() method of the ServletContext interface. First you need to obtain the reference to Servlet
Context using the getServletContext() method and using which you create a new RequestDispatcher object as shown
below:
ServletContext context = getServletContext();
RequestDispatcher rd = context.getRequestDispatcher(URL);

21
In some applications you might want to have one web component do preliminary processing of a request and another
component generate the response. For example, you might want to partially process a request and then transfer to
another component depending on the nature of the request. To transfer control to another web component, you invoke
the forward method of a RequestDispatcher. When a request is forwarded, the request URL is set to the path of the
forward page.
--------------------------------------------------------------------

QUESTION NO : 32
QUESTION STATEMENT : Which of the following are valid sub elements of the <web-resource-collection> element
used in the deployment descriptor of a web application?
CHOICES :
a)
b)
c)
d)
e)
f)

<auth-constraint>
<login-config>
<role-name>
<http-method>
<url-pattern>
<web-resource-name>

CORRECT ANSWER : def


EXPLANATION :
Choices D, E and F are correct. The <web-resource-collection> element is used to identify a subset of the resources and
HTTP methods on those resources within a web application to which a security constraint applies. The <web-resourcename>, the subelement of <web-resource-collection> contains the name of this web resource collection. The <httpmethod>, another subelement of <web-resource-collection> contains an HTTP method (GET | POST |...). The <urlpattern> element, another subelement of <web-resource-collection> is used to define the resources (files, directories) to
be protected.
The <auth-constraint> element indicates the user roles that should be permitted access to this resource collection.
To specify which roles a user must be in before he is allowed to access a resource, the <role-name> element is used.
The login-config element is used to configure the authentication method that should be used, the realm name that
should be used for this application, and the attributes that are needed by the form login mechanism.
Following is an example of a DD of a web application:
<web-app>
....
<security-constraint>
<web-resource-collection>
<web-resource-name> MyResource </web-resource-name>
<url-pattern> myservlets/* </url-pattern>
<http-method> GET </http-method>
<http-method> POST </http-method>
</web-resource-collection>
<auth-constraint>
<role-name> manager </role-name>

22
</auth-constraint>
</security-constraint>
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> Example Basic Authentication Area </realm-name>
</login-config>
...
</web-app>
Thus choice D, E and F are correct whiles others are not.
--------------------------------------------------------------------

QUESTION NO : 33
QUESTION STATEMENT : Using java servlets api, one can write a message to the web application log file and one
can even write a stack trace of a given throwable exception. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, ServletContext interface provides methods to write a message to the WebApp log and even a stack trace for a given
exception to the servlet log file.
Following are the log methods of the ServletContext interface for the above purpose:
a.) log(Exception, String) : public void log(java.lang.Exception exception, java.lang.String msg)
Deprecated. As of Java Servlet API 2.1, use log(String, Throwable) instead. This method was originally
defined to write an exception's stack trace and an explanatory error message to the servlet log file.
b.) log(String) : public void log(java.lang.String msg)
Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log file is
specific to the servlet container.
Parameters:
msg - a String specifying the message to be written to the log file
c.) log(String, Throwable) : public void log(java.lang.String message, java.lang.Throwable throwable)
Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. The name and
type of the servlet log file is specific to the servlet container, usually an event log.
Parameters:
message - a String that describes the error or exception

23
throwable - the Throwable error or exception
Also please note that GenericServlet class (in javax.servlet package) also implements the log method, declared in the
ServletContext interface.
--------------------------------------------------------------------

QUESTION NO : 34
QUESTION STATEMENT : Which of the following HTTP methods makes it possible to check whether a file was last
modified or to check the length of the file without actually having to download it?
CHOICES :
a)
b)
c)
d)

GET
POST
HEAD
PUT

CORRECT ANSWER : c
EXPLANATION :
Choice C is the correct answer. The HEAD method is identical to the GET method except that it only returns the HTTP
header - the body content is excluded. The HEAD method only returns the HTTP header, which should be identical to
the header that would have been returned in response to a GET. It is used for debugging, verifying hypertext links, or
checking the status of the file before attempting to retrieve it. Thus choice C is the correct. POST is an HTTP method
used for passing user input to the server. GET is the most common HTTP method to request a resource from the server.
PUT requests are used to upload data from the client to the server. Thus other choices are incorrect.
--------------------------------------------------------------------

QUESTION NO : 35
QUESTION STATEMENT :
The tag handler uses ___ object to retrieve all the other implicit objects (request, session, out and application) accessible
from a JSP page.
CHOICES :
a) ""
CORRECT ANSWER :
PageContext
EXPLANATION :
The tag handler needs to communicate with the JSP page. To do that PageContext is an entry point through which it (tag
handler) retrieves all the other implicit objects (request, session, out and application) accessible from a JSP page. Also
the PageContext is the first property to be set in the new tag instance, followed by the parent of the tag.

24

--------------------------------------------------------------------

QUESTION NO : 36
QUESTION STATEMENT : The errorPage is an optional attribute of which of the following JSP directives?
CHOICES :
a)
b)
c)
d)

include
page
taglib
None of the above.

CORRECT ANSWER : b
EXPLANATION :
The page directive defines a number of important attributes that affect the whole page. The errorPage is one of the
optional attributes of the page directive. It defines a URL to another JSP that is invoked if an unchecked runtime
exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error
page processing. Here is an example:
<%@ page errorPage="MyError.jsp" %>
<html>
<body>
<h1> This page refers to MyError.jsp! </h1>
</body>
</html>
--------------------------------------------------------------------

QUESTION NO : 37
QUESTION STATEMENT : In the case of a web application marked "distributed" in its deployment descriptor, the
ServletContext can be used as a location to share global information. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The ServletContext defines a set of methods that a servlet uses to communicate with its servlet container, for example,
to get the MIME type of a file, dispatch requests, or write to a log file.

25
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets
and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a
.war file.)
In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for
each virtual machine. In this situation, the context cannot be used as a location to share global information (because the
information won't be truly global). Use an external resource like a database instead. Thus the above statement is not
true.
--------------------------------------------------------------------

QUESTION NO : 38
QUESTION STATEMENT : You declare that a JSP page will use tags defined in a tag library by including a "taglib"
directive in the page before any custom tag is used. Here is the syntax for taglib directive:
<%@ taglib uri="URI" prefix="PREFIX" %>
The uri attribute refers to a URI that uniquely identifies the TLD (Tag Library Descriptor).
On a J2EE server, the URI can be direct or indirect (i.e. a logical name is used to refer the TLD). True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, the URI can be direct or indirect. In case of direct URI, the complete URI path referring a TLD is used. In case of
indirect URI, a short logical name is used to refer the TLD. The logical name is mapped to an absolute location in the
web application deployment descriptor. Here are the examples of directives using direct and indirect uri:
a.) Direct URI
<%@ taglib uri="/WEB-INF/myTag.tld" prefix="tt" %>
b.) Indirect URI
<%@ taglib uri="/myTag.tld" prefix="tt" %>
Here (case b) the logical name (/myTag.tld) is mapped to the absolute location (/WEB-INF/myTag.tld) in the
deployment descriptor.

--------------------------------------------------------------------

QUESTION NO : 39

26
QUESTION STATEMENT : JSP provides certain implicit objects accessible within the JSP. These objects do not need
to be declared or instantiated by the JSP author, but are provided by the web container/server. Each of these objects can
be associated with a scope attribute which defines where there is a reference to the object and when that reference is
removed. Which of the following are true combinations of an object and corresponding scope?
CHOICES :
a)
b)
c)
d)
e)
f)

request (object) - request (scope)


response (object) - response (scope)
session (object) - session (scope)
application (object) - application (scope)
page (object) - page (scope)
out (object) - out (scope)

CORRECT ANSWER : acde


EXPLANATION :
A, C, D and E are correct choices. The request object has request scope. An object inside a request scope is accessible
from all the pages processing the request where the object was created. Thus A is correct. B is incorrect as response is
not a valid scope. The valid scopes are: application, session, request and page. The response object has page scope. An
object inside a page is accessible only from the page in which it was created. The session object has session scope. An
object inside session scope is visible from all the pages belonging to the session in which it was created. Thus C is also
correct. The application object has application scope. An object inside an application scope is accessible from all the
pages that belong to the particular application. Thus D is also correct. E is correct as page object has page scope. An
object inside a page is accessible only from the page in which it was created. F is incorrect as out is not a valid scope.
The out object like response also has page scope.
--------------------------------------------------------------------

QUESTION NO : 40
QUESTION STATEMENT : In case of Data Access Object design pattern, which of the following entities represent the
client part?
CHOICES :
a)
b)
c)
d)

BO (Business Object)
DAO (Data Access Object)
DS (Data Source)
None of the above

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. When we talk of Data Access Object design pattern, the DAO is the primary object. It provides
the encapsulation and delegation features to the BO (Business Object), which represents the client. The Business Object
represents the client and is the object that requires access to the data source to obtain and store data. It may be
implemented as a session bean, entity bean, a servlet or any other java object. Data Source represents a data source
implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system,
and so forth. A data source can also be another system (legacy/mainframe), or service (B2B service or credit card
bureau), or some kind of repository (LDAP).

27

--------------------------------------------------------------------

QUESTION NO : 41
QUESTION STATEMENT : Which of the following are valid DD (Deployment Descriptor) declarations for a web
application. (The ... indicates there are other elements as well, which can be assumed to be correctly defined)
CHOICES :
a) <web-app>
...
<security-role> MySecuirtyRole </security-role>
...
<security-constraint>
<web-resource-collection>
<web-resource-name> MyResource </web-resource-name>
...
</web-resource-collection>
</security-constraint>
...
</web-app>
b)
<web-app>
...
<security-constraint>
<web-resource-collection>
...
<url-pattern>/myjsps/*</url-pattern>
<http-method> PUT </http-method>
</web-resource-collection>
</security-constraint>
...
</web-app>
c) <web-app>
...
<security-constraint>
...
<auth-constraint>
<role-name> role1 </role-name>
</auth-constraint>
...
</security-constraint>
...
</web-app>
d) <web-app>
...
<security-constraint>
<web-resource-collection>
<web-resource-name> MyResource </web-resource-name>
<auth-constraint> MyConstraint </auth-constraint>
....
</web-resource-collection>
</security-constraint>

28
...
</web-app>
CORRECT ANSWER : bc
EXPLANATION :
B and C are correct choices. Choice A is incorrect as <security-role> element should consist of <role-name> subelement as given below :
<security-role>
<role-name> manager </role-name>
</security-role>
Choice B and C are correct; all elements/sub elements are declared correctly.
Choice D is incorrect as <auth-constraint> element is not the subelement of <web-resource-collection>; instead it is the
subelement of <security-constraint-element>. An e.g. is given below:
<web-app>
...
<security-constraint>
<web-resource-collection>
<web-resource-name>SalesInfo</web-resource-name>
<url-pattern>/salesinfo/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
</web-app>
--------------------------------------------------------------------

QUESTION NO : 42
QUESTION STATEMENT : A simple tag's (tag without body and attributes) doStartTag() method will return which of
the following constants?
CHOICES :
a) SKIP_BODY
b) EVAL_BODY_INCLUDE
c) SKIP_PAGE

29
d) EVAL_PAGE
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. When a tag has no body (i.e. a simple tag), the doStartTag() method returns SKIP_BODY.
EVAL_BODY_INCLUDE indicates that the tag body should be evaluated into the existing output stream.
SKIP_PAGE indicates that the rest of the page should be skipped.
EVAL_PAGE indicates that page evaluation should continue.
--------------------------------------------------------------------

QUESTION NO : 43
QUESTION STATEMENT : Which of the following are correct page directive syntaxes?
CHOICES :
a)
b)
c)
d)

<%@ page language="java" import="java.util.*, java.rmi.*" %>


<%@ page language="java", import="java.util.* , java.rmi.*" %>
<%@ page language="java"; import="java.util.* ; java.rmi.*" %>
<%@ page language="java" import="java.util.* java.rmi.*" %>

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. Directives are messages to the JSP container.
Directives have this syntax:
<%@directive {attr="value"}*%>
There may be optional white space after the "<%@" and before "%>".
The syntax for page directive is as follows:
Syntax
<%@page page_directive_attr_list %>
page_directive_attr_list ::=
{language="scriptingLanguage"}
{extends="className"}
{import="importList"}
{session="true|false"}
{buffer="none|size kb"}
{autoFlush="true|false"}
{isThreadSafe="true|false"}
{info="info_text"}

30
{errorPage="error_url"}
{isErrorPage="true|false"}
{contentType="ctinfo"}
{pageEncoding="peinfo"}
If there are two or more attributes they are separated by white space and not by comma. Thus choice B and C are
incorrect.
An import attribute describes the types that are available to the scripting environment. The value is as in an import
decla-ration in the Java programming language, i.e. a (comma sep-arated) list of either a fully qualified Java
programming language type name denoting that type, or of a package name followed by the ".*" string, denoting all the
public types declared in that package. The import list shall be imported by the translated JSP page implementation and
is thus available to the scripting environment. The default import list is java.lang.*, javax.servlet.*,
javax.servlet.jsp.*and javax.servlet.http.*. This value is currently only defined when the value of the language directive
is "java". Thus only choice A is correct.
--------------------------------------------------------------------

QUESTION NO : 44
QUESTION STATEMENT : Consider a web application where the client tier needs to exchange data with enterprise
beans. All access to an enterprise bean is performed via remote interfaces to the bean. Every call to an enterprise bean is
potentially a remote method call with network overhead.
In a normal scenario, for reading every attribute value of an enterprise bean, the client will make a remote method call.
The number of calls made by the client to the enterprise bean impacts network performance.
Which of the following design patterns is most suited to solve the above problem?
CHOICES :
a)
b)
c)
d)

Data Access Object


Model View Controller
Value Object
Business Delegate

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. In the scenario explained above, use a Value Object to encapsulate the business data. A single
method call is used to send and retrieve the Value Object. When the client requests the enterprise bean for the business
data, the enterprise bean can construct the Value Object, populate it with its attribute values, and pass it by value to the
client.
When an enterprise bean uses a value object, the client makes a single remote method invocation to the enterprise bean
to request the value object instead of numerous remote method calls to get individual bean attribute values.
--------------------------------------------------------------------

QUESTION NO : 45

31
QUESTION STATEMENT : When the servlet is first loaded, which of the following methods is executed by the Web
server, for each servlet instance before handling the first request?
CHOICES :
a)
b)
c)
d)

start()
load()
init()
service()

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The init() method is called a single time when the servlet is first loaded. It is similar to a class
constructor in that it provides a method wherein initialization is done.
--------------------------------------------------------------------

QUESTION NO : 46
QUESTION STATEMENT :
If the <rtexprvalue> sub-element of the attribute element is true or yes, then the __ element defines the return type
expected from any expression specified as the value of the attribute. (Just type the name, don't put < and > braces)
CHOICES :
a) ""
CORRECT ANSWER :
type
EXPLANATION :
It is the "type" element, which defines the return type expected from any expression specified as the value of the
attribute.
Here is the syntax:
<attribute>
<name> attribute_name </name>
<required> true|false|yes|no </required>
<rtexprvalue> true|false|yes|no </rtexprvalue>
<type> fully_qualified_type </type>
</attribute>
--------------------------------------------------------------------

QUESTION NO : 47

32
QUESTION STATEMENT : The following servlet (using the HTML form shown below) has no thread safety problems.
True/False?
import javax.servlet.*;
import javax.servlet.http.*:
import java.io.*;
1. public class WelcomeServlet extends HttpServlet
2. {
3.
String name;
4.
5.
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
6.
{
7.
response.setContentType("text/plain");
8.
PrintWriter out = res.getWriter();
9.
name = req.getParameter("name");
10.
welcome(out);
11.
out.close();
12.
}
13.
14.
public void welcome(PrintWriter out)
15.
{
16.
out.println("Welcome " + myName + "!");
17.
}
18. }
<HTML>
<HEAD> <TITLE > WELCOME </TITLE> </HEAD>
<BODY>
<FORM METHOD="POST" ACTION="/servlet/WelcomeServlet">
<P> Enter your name: <INPUT TYPE ="TEXT" NAME="name" SIZE="40"> </P>
<P> <INPUT TYPE="SIBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
In a single user environment, the above servlet will have no thread safety problem. However, there is a thread safety
concern when concurrent threads are received. This problem arises when the user's name is assigned to the shared
(instance) variable, name at line number 9. Because this variable is declared outside the service() method, it is shared
between all requests.
Before the first request is completed (i.e. welcome method is called), the second request may be received causing thread
safety problem.
--------------------------------------------------------------------

33

QUESTION NO : 48
QUESTION STATEMENT : What will be the output to the client on execution of the following code? (Assuming all
other elements are written well)
<% for (int i=1; i<=2; i++) { %>
<H<%=i%>> Hello </H><%=i%>
<% } %>
CHOICES :
a)
b)
c)
d)

The above code will compilation error.


It will print : H1HelloH1 followed by H2HelloH2
It will print : Hello within H1 and H2 Heading tags
The code will compile but will will run time error.

CORRECT ANSWER : c
EXPLANATION :
C is the correct answer. The above code will compile properly and will not give any run time error. The expression
<%=i%> will be evaluated to the value of i which starts from 1 and ends at 2. Thus Hello will be printed first as <H1>
Hello </H1> and then <H2> Hello </H2>. Thus C is the correct answer.
--------------------------------------------------------------------

QUESTION NO : 49
QUESTION STATEMENT :
The method used by Custom Tag Handler to access the JSP page's attribute by specified name and scope is ____. (Write
only the method name, without braces. e.g. myMethod and not myMethod())
CHOICES :
a) ""
CORRECT ANSWER :
getAttribute
EXPLANATION :
The PageContext class defines following methods to obtain attributes:
a.) public abstract java.lang.Object findAttribute (java.lang.String name)
Searches for the named attribute in page, request, session (if valid), and application scope(s) in order and returns the
value associated or null.
Returns: the value associated or null
b.) public abstract java.lang.Object getAttribute (java.lang.String name)

34

Return the object associated with the name in the page scope or null if not found.
Parameters:
name - the name of the attribute to get
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
c.) public abstract java.lang.Object getAttribute (java.lang.String name,int scope)
Return the object associated with the name in the specified scope or null if not found.
Parameters:
name - the name of the attribute to set
scope - the scope with which to associate the name/object
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
d.) public abstract java.util.Enumeration getAttributeNamesInScope (int scope)
Enumerate all the attributes in a given scope
Returns: an enumeration of names (java.lang.String) of all the attributes the specified scope
To obtain the attribute specified by name and scope the method b.) is used.

--------------------------------------------------------------------

QUESTION NO : 50
QUESTION STATEMENT : When a web application is marked as distributable, the HttpSession is scoped to the web
container's VM while the ServletContext is scoped to the particular VM servicing session requests. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
In a distributable web application, the HttpSession instances are scoped to the particular VM servicing session requests,
and the context exists locally in the VM in which it was created and placed - preventing the ServletContext from being
used as a distributed shared memory store. Thus the above statement is not true.
--------------------------------------------------------------------

35

QUESTION NO : 51
QUESTION STATEMENT : The following DTD for the web application deployment descriptor element used for
initialization parameters of a servlet is correct. True/False?
<!ELEMENT initialize-param (param-name, param-value, description?)>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The above definition is incorrect. The correct definition is as follows:
<!ELEMENT init-param (param-name, param-value, description?)>
The init-param element contains a name-value pair as an initialization param of the servlet. The description element is
optional.
--------------------------------------------------------------------

QUESTION NO : 52
QUESTION STATEMENT :
The session management implementation in the servlet API revolves around the _____ interface.
CHOICES :
a) ""
CORRECT ANSWER :
HttpSession
EXPLANATION :
The session management mechanism in the Servlet API resides in the HttpSession interface. An HttpSession object
encapsulates the essential information of an HTTP session, such as a unique session ID and other client-specific
information. In this way, it provides a way to identify a user across more than one page request or visit to a website and
to store information about that user. The servlet container uses this interface to create a session between an HTTP client
and an HTTP server.
--------------------------------------------------------------------

QUESTION NO : 53

36
QUESTION STATEMENT : Which of the following are valid methods of HttpSessionAttributeListener interface?
CHOICES :
a)
b)
c)
d)
e)
f)

attributeInitiated()
attributeAdded()
attributeReplaced()
attributeRemoved()
attributeDeleted()
attributeDestroyed()

CORRECT ANSWER : bcd


EXPLANATION :
Choices B, C and D are correct. The object implementing the HttpSessionAttributeListener interface is notified when an
Attrbute is added, removed or replaced on an HttpSession. Following are the methods of HttpSessionAttributeListener
interface with their functions:
a.) public void attributeAdded(HttpSessionBindingEvent se)
Notification that an attribute has been added to a session. Called after the attribute is added.
b.) public void attributeRemoved(HttpSessionBindingEvent se)
Notification that an attribute has been removed from a session. Called after the attribute is removed.
c.) public void attributeReplaced(HttpSessionBindingEvent se)
Notification that an attribute has been replaced in a session. Called after the attribute is replaced.
--------------------------------------------------------------------

QUESTION NO : 54
QUESTION STATEMENT : The RequestDispatcher object can be used for error handling in a web application.
True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, the RequestDispatcher object can be used for error handling in a web application. The RequestDispatcher object
allows to programmatically forward requests to other server resources using it forward() method. Thus in case of error
conditions ReuqestDispatcher can be used to forward a request to an error page. Following is the code, which describes
how it can be done:
ServletContext context = getServletContext();
RequestDispatcher rd = context.getRequestDispatcher(URL);

37
rd.forward(request,response);
The "URL" refers to the error page.
--------------------------------------------------------------------

QUESTION NO : 55
QUESTION STATEMENT : Which of the following terms completes the statement below?
" ___ is the process we perform to verify that a user is who they say they are."
CHOICES :
a)
b)
c)
d)

User Authentication
User Authorization
Auditing
Data Integrity

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. User Authentication is the process we perform to verify that a user is who they say they are.
Authentication is the process by which you determine a user's identity; authorization is the process by which you
determine what actions a particular user can perform.
Authorization may or may not require user authentication. For e.g. a website may authorize all users to browse their
content. However, it probably only allow particular users (e.g. the webmaster) to update the site's content. Whether or
not a user plays a particular role (i.e. it is a webmaster) is determined by his user authentication.
Auditing is the process of recording a log of user activities within an application.
Data Integrity is the means used to prove that information has not been modified by a third party while in a transit.
Thus choice A is correct and others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 56
QUESTION STATEMENT : Which of the following statements is true regarding the two syntax shown below for using
a JavaBean component in JSP page?
a.) <jsp:useBean id="beanName" class="fully_qualified_classname" scope="page|request|session|application" />
b.) <jsp:useBean id="beanName" class="fully_qualified_classname" scope="page|request|session|application">
<jsp:setProperty .../>
</jsp:useBean>
CHOICES :

38
a)
b)
c)
d)

Both a and b are valid.


Only a is valid.
Only b is valid.
None of a and b is valid.

CORRECT ANSWER : a
EXPLANATION :
A is correct. Both of the above syntax are valid for using a JavaBean component in a JSP page. The second format is
used when there is a need to include jsp:setProperty statements, for initializing java bean properties. In both the above
formats, the value of the id attribute determines the unique identifier used to refer the bean. The value of the class
attribute is the complete path (including package structure) and the bean class name. A JavaBean like any other object in
a JSP page has an associated scope attribute, defined by the scope variable, which determines where there is a reference
to the object and when that reference is removed. Here is an example which uses MyBean JavaBean class in mypackage
package having an application scope, identified by "myBean".
<jsp:useBean id="myBean" class="mypackage.MyBean" scope="application" />
--------------------------------------------------------------------

QUESTION NO : 57
QUESTION STATEMENT : The benefits listed below are provided by which of the design patterns?
1.) Makes it easier for an application to migrate to a different persistent storage implementation.
2.) Business Objects can transparently use the data source.
CHOICES :
a)
b)
c)
d)

Data Access Object


Model View Controller
Value Object
Business Delegate

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. Many web applications need to access data sources. This data source may be a legacy system, an
RDBMS, a flat file or some other form. Due to presence of disparate data sources, normally there occurs a tight
coupling between the components and the data source implementation. Thus DAO (Data Access Object) is used to
abstract and encapsulate all access to the data source. The Data Access Object (DAO) manages the connection with the
data source to obtain and store data. The web component that relies on the DAO object uses the simple interface
exposed by the DAO for its clients. Effectively, the DAO acts as an adapter between the component and the data source.
In this way DAO enables transparency; the business objects can use the data source without knowing the specific details
of data source's implementation. Access is transparent because the implementation details are hidden inside the Data
Access Object.
Also a layer of Data Access Objects makes it easier for an application to migrate to a different database implementation.
The business objects have no knowledge of the underlying data implementation. Thus, the migration involves changes
only to the data access object layer.

39

--------------------------------------------------------------------

QUESTION NO : 58
QUESTION STATEMENT : A JSP custom tag can have attributes to customize its behaviour. They are listed in the start
tag and have the syntax attribute_name="attribute_value".
Which of the following are the optional sub elements of the <attribute> element defined in the TLD (Tag Library
Descriptor)?
CHOICES :
a)
b)
c)
d)

<name>
<required>
<rtexprvalue>
<type>

CORRECT ANSWER : bcd


EXPLANATION :
B, C and D are the correct choices. For each tag attribute you must specify its name; the other sub elements are
optional. The <required> subelement defines if the attribute is required or optional. If not present, the default is "false";
i.e. the attribute is optional. The <rtexprvalue> defines if the attribute can have scriptlet expressions as a value, i.e. the
value of the attribute may be dynamically calculated at request time, as opposed to a static value determined at
translation time. If not present then the default is "false", i.e. the attribute has a static value. The <type> subelement
defines the Java type of the attribute's value. For static values (those determined at translation time) the type is always
java.lang.String. In case a runtime expression is used to set the value of the attribute (i.e. rtexprvalue is "yes" or "true"),
then the type element defines the return type expected from any expression specified as the value of the attribute. Thus
B, C and D are the correct choices.
Here is the DTD for the attribute element:
<!ELEMENT attribute (name, required? , rtexprvalue?, type?, description?) >
--------------------------------------------------------------------

QUESTION NO : 59
QUESTION STATEMENT : A JSP expression is used to insert the value of a scripting language expression into the data
stream and returned to the client. To insert more than one JSP expression, semicolon is used. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b

40
EXPLANATION :
Please note that semicolon is not allowed within a JSP expression. A JSP scriptlet is used in case an expression has a
semicolon. The following code will not compile:
<%= System.currentTimeMillis(); new java.sql.Date(System.currentTimeMillis()) %>
The following code will compile, although it will not print out anything:
<% System.currentTimeMillis(); new java.sql.Date(System.currentTimeMillis()); %>
--------------------------------------------------------------------

QUESTION NO : 60
QUESTION STATEMENT : What will be the output of the following Servlet? For example, it can be invoked through a
Web Browser with the URL
http://<server-name>:8080/servlet/MyServlet
The source for the JSP (MyJSP.jsp) is also given below. Assume that the location of Servlet and JSP in the web
container is appropriate.
//MyServlet.java ....
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
String url = "/MyJSP.jsp";
ServletContext context = getServletContext();
RequestDispatcher rd = context.getRequestDispatcher(url);
rd.forward(req, res);
}
}
// MyJSP.jsp ...
<html>
<body bgcolor="#FFFFFF">
You can do it!!
</body>
</html>
CHOICES :

41
a)
b)
c)
d)

It will print : "You can do it!!"


It will give compile time error.
It will give run time error.
It will give blank page as an output.

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. With the servlet API 2.1, the RequestDispatcher object allows you to forward requests to or
include output from other server resources (e.g JSP). The RequestDispatcher object has only two methods : include()
and forward(). The forward() method of the RequestDispatcher object allows you to programatically forward a request
to another web resource known as a delegate. Thus in the above code, the service() method of MyServlet will invoke
MyJSP. As a result "You can do it!!" will be printed out. There will be no compile time or runtime error. Thus choice A
is correct and other choices are incorrect.
--------------------------------------------------------------------

QUESTION NO : 61
QUESTION STATEMENT : Consider the following HTML form. It accepts the users name in a text input field, and has
a submit button.
//HelloByName.html
<html>
<body>
<form action="/servlet/HelloByName">
What's your name?<input type="text" name="name">
<p><input type="SUBMIT">
</form>
</body>
</html>
The following is the code of the servlet invoked when the submit button of the form is clicked //HelloByName.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloByName extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException
{
res.setContentType("text/html");
String name = req.getParameter("name");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<body>");
out.println("Hello "+name+", I am the doGet method!!");

42
out.println("</body>");
out.println("</HTML>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException
{
res.setContentType("text/html");
String name = req.getParameter("name");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<body>");
out.println("I am the doPost method! I don't feel the need to say hello to you. "+name+" is a funny name in any
case!");
out.println("</body>");
out.println("</HTML>");
}
}
What will be displayed in the browser when a name, say 'Alfred' is entered in the text field on the form, and the submit
button is clicked?
CHOICES :
a) An HTML page displaying - Hello Alfred, I am the doGet method!!
b) An HTML page displaying - I am the doPost method! I don't feel the need to say hello to you. Alfred is a funny
name in any case!
c) Compile time error
d) A blank HTML page
CORRECT ANSWER : a
EXPLANATION :
An HTML page displaying - Hello Alfred, I am the doGet method!! This is because GET is the default HTTP method
for accessing a URL. If the name 'Alfred' is entered and the submit button clicked, the following URL will be seen in
the browser address bar - http://localhost:port/servlet/HelloByName?name=Alfred. Thus it can be seen that the servlet
is invoked with the parameter name=Alfred encoded within the URL string, using the GET method. If the <form> tag is
changed to <form method="post" action="/servlet/HelloByName">, then, the message in option 2, above, will be
displayed in response, and the URL seen in the browser address bar will be http://localhost/servlet/HelloByName. In
POST request, the parameters are passed to the servlet as a part of the HTTP request, and not in the URL string.
--------------------------------------------------------------------

QUESTION NO : 62
QUESTION STATEMENT : Consider the following code.
1:
2:
3:
4:
5:
6:

<html>
<body>
<h1> What is the result of adding two numbers? </h1>
<%! int x = 3; %>

43
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

<%! int y = 2; %>


<%! int z = 0; %>

<%= "The sum of x and y is " + z %>


</body>
</html>

Which of the following line of code should be placed at line 12 to make this JSP work (prints the result of sum of x and
y)?
CHOICES :
a)
b)
c)
d)

<%@ z = x + y ; %>
<%! z = x + y; %>
< z = x + y; />
<% z = x + y; %>

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. A is incorrect as the <%@ ... %> tag is used to declare directives like include directive. Choice
B is incorrect as <%! ... %> tag is used to declare/intialize a variable/method. Choice C is incorrect as < ... /> is not a
valid tag. The <% ... %> tag is used to insert scriptlet (a block of java code) into a JSP. We needed to assign the value of
sum of x and y to z and the choice D do it correctly. The choice A and B will give compilation errror while the choice C
will print : "< z = x + y; /> The sum of x and y is 0 ".
--------------------------------------------------------------------

QUESTION NO : 63
QUESTION STATEMENT : Which of the following statements are true regarding the following JSP custom tags?
a.) <tt:t1 att="myTag" />
b.) <tt:t2 att="myTag"> </tt:t2>
c.) <tt:t3 att="myTag" >
BODY
</tt:t3>
CHOICES :
a)
b)
c)
d)
e)
f)

The Tag defined in a.) is empty tag.


The Tag defined in a.) is non-empty tag.
The Tag defined in b.) is empty tag.
The Tag defined in b.) is non-empty tag.
The Tag defined in c.) is empty tag.
The Tag defined in c.) is non-empty tag.

44
CORRECT ANSWER : acf
EXPLANATION :
Choice A, C and F are correct. A non-empty tag has a start tag, a body, and an end tag. An empty tag has no body. There
are two equivalent syntaxes, one with separate start and end tag, and one where the start and end tags are combined.
Thus tags a.) and b.) are empty tags while c.) is a non-empty tag. Thus choice A, C and F are true while others are
incorrect.
--------------------------------------------------------------------

QUESTION NO : 64
QUESTION STATEMENT : In case of Model View Controller (MVC) design pattern, which component (M/V/C) plays
the following roles?
Renders the models
Requests updates from models
Sends user gestures to controller
Allows controller to select view
CHOICES :
a)
b)
c)
d)

Model
View
Controller
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. The "model" represents enterprise data and the business rules that govern access to and updates
of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling
techniques apply when defining the model.
A "view" renders the contents of a model. It accesses enterprise data through the model and specifies how that data
should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes.
This can be achieved by using a push model, where the view registers itself with the model for change notifications, or
a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.
A "controller" translates interactions with the view into actions to be performed by the model. In a stand-alone GUI
client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET
and POST HTTP requests. The actions performed by the model include activating business processes or changing the
state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by
selecting an appropriate view.
Thus B is the correct choice.
--------------------------------------------------------------------

QUESTION NO : 65

45
QUESTION STATEMENT : JavaBeans component design conventions govern the properties (i.e. variables) of a java
bean and the methods that give access to these properties. A property can be read-only, write-only or both read and
write. Which of the following best describes a read only property?
CHOICES :
a)
b)
c)
d)

A property which has corresponding get and set methods.


A property which has corresponding get method only.
A property which has corresponding set method only.
A property which has none of the corresponding methods.

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. Read-only property means, the java bean class has a property (or variable) which can only be
read (i.e. which can only be get or accessed). It can't be set. Thus to provide only read access there will be
corresponding get method only, also called accessor method. It should not have a set method or mutator method.
Here is an example:
public class MyJavaBean
{
private int myNumber;
public MyJavaBean()
{
myNumber = 0;
}
public int getMyNumber()
{
return myNumber;
}
}
--------------------------------------------------------------------

QUESTION NO : 66
QUESTION STATEMENT : Which of the following are valid authentication mechanisms provided by Servlet Engine
as part of JSP 1.2 specification?
CHOICES :
a)
b)
c)
d)

HTTP BASIC Authentication


Digest Authentication
Frame Based Authentication
HTTPS Client Authentication

CORRECT ANSWER : abd


EXPLANATION :

46
A, B and D are correct. As part of the JSP 1.2 specification, the servlet engine is required to provide four basic methods
of authentication that are used to control access to servlets/JSPs.
The four methods of authentications are:
HTTP BASIC Authentication
Digest Authentication
Form Based Authentication
HTTPS Client Authentication
Please note that it is "Form" Based Authentication and not Frame Based Authentication. Thus choice C is incorrect
while others are correct.

--------------------------------------------------------------------

QUESTION NO : 67
QUESTION STATEMENT : Which of the following statements is true regarding the below deployment descriptor
definitions for an error-page element?
a.) <web-app>
...
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
...
</web-app>
b.) <web-app>
...
<error-page>
<exception-type>java.sun.com.MyException</exception-type>
<location>/404.html</location>
</error-page>
...
</web-app>
CHOICES :
a)
b)
c)
d)

Both of the above declarations are correct.


None of the above declarations are correct.
Only a.) is correct.
Only b.) is correct.

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. The error-page element contains a mapping between an error code or exception type to the path
of a resource in the web application. Here is the DTD definition for the error-page element:
<!ELEMENT error-page ((error-code | exception-type), location)>

47
The error-code contains an HTTP error code, ex: 404. The exception type contains a fully qualified class name of a Java
exception type. The location element contains the location of the resource in the web application.
According to the above DTD definition, the error-page tag must contain either of the error-code or exception-type and
location. Thus both of the declarations in the question are true.
--------------------------------------------------------------------

QUESTION NO : 68
QUESTION STATEMENT :
The ___ constant variable of the Tag interface indicates that page evaluation should continue.
CHOICES :
a) ""
CORRECT ANSWER :
EVAL_PAGE
EXPLANATION :
The Tag interface defines various constants, which are as follows:
SKIP_BODY indicates that body evaluation should be skipped.
EVAL_BODY_INCLUDE indicates that the tag body should be evaluated into the existing output stream.
SKIP_PAGE indicates that the rest of the page should be skipped.
EVAL_PAGE indicates that page evaluation should continue.
--------------------------------------------------------------------

QUESTION NO : 69
QUESTION STATEMENT :
The objects implementing the ___ interface are notified of changes to the list of active sessions in a web application.
(Write only the interface name)
CHOICES :
a) ""
CORRECT ANSWER :
HttpSessionListener
EXPLANATION :
Servlet event listeners support event notifications for state changes in the ServletContext and HttpSession objects. Http
session listeners are used to manage state or resources associated with a series of requests made into a web application

48
from the same client or user. The HttpSession listener (object implementing the HttpSessionListener interface) are
notified when an HttpSession has been created, invalidate or timed out.
--------------------------------------------------------------------

QUESTION NO : 70
QUESTION STATEMENT : By default, which of the following is the session management mechanism used by the
servlet container.
CHOICES :
a)
b)
c)
d)

Rewritten URLS
Cookies
Hidden Variables
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. By default, the session management in the Servlet API is achieved using Cookies. Cookies are
used because of the increased overhead required to implement rewritten URLs. However, the Servlet API provide
methods to determine if the client lacks cookie support, in which case rewritten URLs can be used instead.

--------------------------------------------------------------------

QUESTION NO : 71
QUESTION STATEMENT : The variables local to the methods like service(), doPost() and doGet() are thread safe.
True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
A Java Servlet spawns a new thread for each client request within the same process space. Because every call to
service(), doGet(), doPost() is executed in its own thread, variables local to these methods are not shared between
requests and are automatically thread safe. In that case there is no need for the servlet to implement SingleThreadModel
interface.
--------------------------------------------------------------------

49
QUESTION NO : 72
QUESTION STATEMENT : You add web components to a J2EE application in a package called WAR (web application
archive). A WAR has a specific hierarchical directory structure. Which of the following directory stores the Java
ARchive files (like tag libraries)?
CHOICES :
a)
b)
c)
d)

WEB-INF/public_html
WEB-INF/classes
WEB-INF
WEB-INF/lib

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The top-level directory of a WAR is the document root of the application. The document root
contains a subdirectory called WEB-INF, which contains the following files and directories:
/WEB-INF/web.xml deployment descriptor.
/WEB-INF/classes/* directory for servlet and utility classes. The classes in this directory are available to the application
class loader.
WEB-INF/lib/*.jar area for Java ARchive files. These files contain servlets, beans, and other utility classes like tag
libraries.
There is no predefined directory with the name WEB-INF/public_html. Thus D is the correct choice and others are
incorrect.
--------------------------------------------------------------------

QUESTION NO : 73
QUESTION STATEMENT : Which of the following is true regarding HTTP GET and HTTP POST requests and the
corresponding methods in the servlet API?
CHOICES :
a)
b)
c)
d)

The doGet() method is more secure than doPost().


The doPost() method is more secure than doGet().
A limited amount of data can be passed as part of the URL in a GET request.
GET is an HTTP method commonly used for passing user input to the server.

CORRECT ANSWER : bc
EXPLANATION :
B and C are correct choices. In case of a GET request, the information entered by the user is appended to the URL and
displayed in plain text by the browser. In case of POST request, the information submitted by the user is passed and is
stored in the body of the request rather than in the URL. Thus doPost() method called in response to HTTP POST
request is more secure than doGet() method. Thus choice B is correct and choice A is incorrect. Another disadvantage in
case of GET request is that since the information is passed through the URL, there is a limited amount of data that can
be passed. It varies from browser to browser. For e.g. earlier versions of Microsoft Internet Explorer could pass no more

50
than 255 characters in the URL. Thus choice C is also correct. Choice D is incorrect as its the POST and not GET which
is commonly used for passing user input to the server. An e.g. - user fills and submit and HTML form.
--------------------------------------------------------------------

QUESTION NO : 74
QUESTION STATEMENT :
A protocol is said to be ____ if it has no memory of prior of prior connections and cannot distinguish one client's
request from that of another.
CHOICES :
a) ""
CORRECT ANSWER :
Stateless
EXPLANATION :
In a stateless protocol like HTTP, once a user issues a request and receives a response, the connection is closed. When
the same user issues a new request, the server has no memory of previous request.
--------------------------------------------------------------------

QUESTION NO : 75
QUESTION STATEMENT : Which of the following mechanisms for including content from another source in a JSP
page are valid?
CHOICES :
a)
b)
c)
d)

include directive
jsp:include action
Both of the above
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. Both include directive and jsp:include action are mechanisms for including content in a JSP
page from another resource.
The include directive notifies the web container/server to include the content of the resource in the current JSP, inline, at
the specified place. Here is the syntax for that:
<%@ include file="Filename" %>

51
The jsp:include action allows a static or dynamic resource to be included in the current JSP at request time. The
resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />
Please note the difference between the above two mechanisms. In the first case, the content of the included file is parsed
by the JSP at translation time (or compilation time). While the jsp:include action is used to include resources at runtime,
at the time of processing the request. When using include directive, the included file should not be another dynamic
page. In case of jsp:include action, the included resource can be either static or dynamic.
--------------------------------------------------------------------

QUESTION NO : 76
QUESTION STATEMENT : The doStartTag() and doEndTag() methods belong to which of the following
interface/class?
CHOICES :
a)
b)
c)
d)

Tag
TagLib
TagHandler
TagInfo

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. The doStartTag() and doEndTag() methods belong to the Tag interface of the
javax.servlet.jsp.tagext package. The Tag interface provides methods that connect a tag handler (a tag handler is an
object invoked by a web container/server to evaluate a custom tag during the execution of the JSP page that references
the tag.) with a JSP implementation class, including the life cycle methods and methods that are invoked at the start and
end tag. The method doStartTag() processes the start tag associated with a JSP while the doEndTag() method processes
the end tag associated with a JSP. Choice B and C are not valid interface/class. The TagInfo object contains information
associated with a Tag. Thus choice D is also incorrect.
--------------------------------------------------------------------

QUESTION NO : 77
QUESTION STATEMENT :
The shared resources created by the init() method should be declared ____, in case the server implementation uses
multiple instances of a single servlet class.
CHOICES :
a) ""
CORRECT ANSWER :
static

52

EXPLANATION :
Depending on the server implementation, the server may create a single instance to service all client requests or it may
create a pool of instances. In case, the server creates a pool of instances, the instance variables will not be shared by all
requests, as each instance will have the copy of its variables. Thus for shared resources to be shared across all requests,
they should be declared static as static variables (or class variables) are global variables; there will be only variable for
all instances.
For e.g. a database connection object is declared as static to be shared across all instances.
--------------------------------------------------------------------

QUESTION NO : 78
QUESTION STATEMENT : Which of the following statements regarding a web application deployed on J2EE server
are true?
CHOICES :
a)
b)
c)
d)
e)

The configuration information is maintained in an XML file called web application deployment descriptor.
The web components are packaged in a file with war as an extension.
The web components are packaged in a file with jar as an extension.
The web application packages can be created using the war utility.
The web application packages can be created using the jar utility.

CORRECT ANSWER : abe


EXPLANATION :
A, B and E are correct. The configuration information for a web application to be deployed on J2EE server is
maintained in an XML file called the Deployment Descriptor. Web components to a J2EE application are added in a
package called WAR (Web Application Archive), which can be created either using "deploytool" facility of J2EE server
or manually with the JAR tool distributed with the J2SE. For e.g. to create myApplication war file for a web
application, following command can be used:
jar cvf myApplication.war
--------------------------------------------------------------------

QUESTION NO : 79
QUESTION STATEMENT : A JSP custom tag can have attributes to customize its behaviour. They are listed in the start
tag and have the syntax attribute_name="attribute_value". For each tag attribute, you must define a property and get &
and set methods.
If the attribute is named "id" and the tag handler inherits from the TagSupport class, you do not need to define the
property and set & get methods. True/False?
CHOICES :
a) True

53
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, If the attribute is named "id" and the tag handler inherits from the TagSupport class, you do not need to define the
property and set & get methods as these are already defined by TagSupport class. The TagSupport class has the
following ID methods:
public String getTagId()
public void setTagId(String id)
--------------------------------------------------------------------

QUESTION NO : 80
QUESTION STATEMENT : Which of the following statements regarding Servlets are true?
CHOICES :
a) A servlet is a server-side component, written in java, that dynamically extends the functionality of a server.
b) Beginning with Java 3 (JDK1.3), servlets are considered java standard extensions.
c) CGI offers advantages over Servlets in the areas of performance, portability and security.
d)
Servlets run on HTTP server.
e) Servlets are Cross-Platform.
f) Servlets are Crash Resistant.
CORRECT ANSWER : adef
EXPLANATION :
Choices A, D, E and F are true. Servlet is a server side software component, written in java and dynamically extends the
functionality of the web server similar to the way an applet extends the functionality of the web browser. Thus A is
correct. B is incorrect as with Java 2 (JDK1.2), servlets are considered java standard extensions (servlet libraries are
stored in javax.servlet.*, javax.servlet.http.* packages of JDk1.2). C is incorrect as it is the Servlet which offers
advantages over the CGI in the said areas. D is correct as servlets run on HTTP server, also known as Web server. Being
written in Java, servlets provides cross-platform support. Thus E is correct. Servlets being written in java and executed
by a JVM (Java Virtual Machine) are crash resistant as JVM doesn't allow servlets direct access to memory locations
and it (JVM) also verifies that compiled Java class files are valid and do not perform illegal operations like forged
pointers and illegal object casting. Thus choice F is also correct.
--------------------------------------------------------------------

QUESTION NO : 81
QUESTION STATEMENT : If an HTML page of a web application has a hyperlink (to a servlet) with the following
URL, which of the mechanisms would have been used (as suggested by the URL below) for session management?
http://www.myserver.com/myservlet/index.html?jsessionid=1234

54
CHOICES :
a)
b)
c)
d)

Rewritten URLs
Cookies
Http Redirect
None of the above

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. When a client will not accept a cookie, URL rewriting may be used by the server as the basis for
session tracking. URL rewriting involves adding data, a session id, to the URL path that is interpreted by the container
to associate the request with a session. The session id must be encoded as a path parameter in the URL string. The name
of the parameter must be jsessionid.
An HTTP redirect allows the server to respond to a client request with instructions to load a resource at a different
location. It is not a mechanism for state/session management. Thus choice A is correct.
--------------------------------------------------------------------

QUESTION NO : 82
QUESTION STATEMENT :
The ___ element is used to configure the authentication method that should be used, the realm name that should be used
for this application, and the attributes that are needed by the form login mechanism. (Write the element name without
<> braces, e.g. init-param)
CHOICES :
a) ""
CORRECT ANSWER :
login-config
EXPLANATION :
The login-config element is used to configure the authentication method that should be used, the realm name that
should be used for an application, and the attributes that are needed by the form logging mechanism. Here is the DTD
definition for the login-config element:
<!ELEMENT login-config (auth-method?, realm-name?, form-login-config?)>
Here is an example of DD file of a web application using HTTP BASIC Authentication Mechanism:
<web-app>
....
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> Example Basic Authentication Area </realm-name>
</login-config>
...

55
</web-app>
--------------------------------------------------------------------

QUESTION NO : 83
QUESTION STATEMENT : The Java objects used by a JSP page can be associated with a scope attribute which defines
the accessibility of the corresponding object. Following are the various scopes that and object can be associated with:
session
request
page
application
Which of the following statements are true regarding tha above scope objects?
CHOICES :
a)
b)
c)
d)
e)
f)

The object is most visible inside the session scope.


The object is most visible inside the request scope.
The object is most visible inside the application scope.
The object is least visible inside the page scope.
The object is least visible inside the request scope.
The object is least visible inside the session scope.

CORRECT ANSWER : cd
EXPLANATION :
C and D are correct. The visibility of the object increases from page scope to the application scope in the following
order page->request->session->application. If an object is inside an application scope, it is accessible from all the pages
belonging to the application. In case of page scope, the object is accessible only within pages where it was created.
Inside the request scope, an object is accessible from pages processing the request where the object was created. Inside
the session scope, an object is accessible from all the pages belonging to the session in which the object was created.
Thus choices C and D are correct while others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 84
QUESTION STATEMENT : The listener classes belonging to a web application can be packaged into which of the
following directories into the WAR?
CHOICES :
a)
b)
c)
d)

WEB-INF
WEB-INF/classes
WEB-INF/lib
WEB-INF/listener

CORRECT ANSWER : bc

56

EXPLANATION :
Choices B and C are correct. The listener classes are packaged into the WAR, either under the WEB-INF/classes archive
entry, or inside a JAR in the WEB-INF/lib directory. Thus choice B and C are correct. There is no predefined WEBINF/listener directory.
--------------------------------------------------------------------

QUESTION NO : 85
QUESTION STATEMENT : The HEAD method is identical to the GET method except that it only returns the HTTP
header - the body content is excluded. True/False ?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, the HEAD method only returns the HTTP header, which should be identical to the header that would have been
returned in response to a GET. It is used for debugging, verifying hypertext links, or checking the status of the file
before attempting to retrieve it.
--------------------------------------------------------------------

QUESTION NO : 86
QUESTION STATEMENT :
The ___ method of the RequestDispatcher object allows to include context generated by another servlet (or other server
resource) within the body of the calling servlet's response. (Write only the method name without any braces e.g.
myMethod and not myMethod())
CHOICES :
a) " "
CORRECT ANSWER :
include
EXPLANATION :
The RequestDispatcher interface has two methods : include() and forward(). The include() method allows you to
include content generated by another servler or other server resource within the body of the calling servlet. The
forward() method allows to forward a request to another servlet (or other server resource).
--------------------------------------------------------------------

57

QUESTION NO : 87
QUESTION STATEMENT :
For a tag handler, which needs to interact with the body of the tag, the doInitBody and ___ methods are used. (Write
only the method name without any braces e.g. myMethod and not myMethod())

CHOICES :
a) ""
CORRECT ANSWER :
doAfterBody
EXPLANATION :
A tag handler for a tag with a body is implemented differently depending on whether the tag handler needs to interact
with the body (i.e. the tag handler reads or modifies the contents of the body) or not. If the tag handler needs to interact
with the body, the tag handler should implement the BodyTag interface (or be derived from BodyTagSupport class).
Such handlers typically implement the doInitBody and the doAfterBody methods. These methods interact with the body
content passed to the tag handler by the JSP page's servlet.
--------------------------------------------------------------------

QUESTION NO : 88
QUESTION STATEMENT : Considering the following JSP pages, which of the statements below are true?
//include1.jsp
<html>
<body>
<%@ include file="date.jsp" %>
</body>
</html>
//include2.jsp
<html>
<body>
<jsp:include page="date.jsp" flush="true" />
</body>
</html>
// date.jsp

58
<html>
<body>
<%@ page import="java.util.Date" %>
<%= "The current date is" + new Date() %>
</body>
</html>
CHOICES :
a)
b)
c)
d)

The output will be identical in two JSPs (include1.jsp and include2.jsp).


The output will be different in two JSPs (include1.jsp and include2.jsp).
The loading time for both JSPs (include1.jsp and include2.jsp) will be same.
The loading time for both JSPs (include1.jsp and include2.jsp) will be different.

CORRECT ANSWER : ad
EXPLANATION :
Choice A and D are correct. The include directive notifies the web container/server to include the content of the
resource in the current JSP, inline, at the specified place. Here is the syntax for that:
<%@ include file="Filename" %>
The jsp:include action allows a static or dynamic resource to be included in the current JSP at request time. The
resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />
Please note the difference between the above two mechanisms. In the first case, the content of the included file is parsed
by the JSP at translation time (or compilation time). While the jsp:include action is used to include resources at runtime,
at the time of processing the request.
Thus the output will be identical. Since the include action includes the content at request time, the loading of JSP
(include2.jsp) will takes a fraction of second longer.
--------------------------------------------------------------------

QUESTION NO : 89
QUESTION STATEMENT :
The ___ class is an abstract class, designed to be extended to provide implementation dependent implementations
thereof, by conformant JSP engine runtime environments.
CHOICES :
a) ""
CORRECT ANSWER :
PageContext

59

EXPLANATION :
The PageContext class is an abstract class, designed to be extended to provide implementation dependent
implementations thereof, by conformant JSP engine runtime environments. A PageContext instance is obtained by a JSP
implementation class by calling the JspFactory.getPageContext() method, and is released by calling
JspFactory.releasePageContext(). An example of how PageContext, JspFactory, and other classes can be used within a
JSP Page Implementation object is given elsewhere.
The PageContext provides a number of facilities to the page/component author and page implementor, including:
-a single API to manage the various scoped namespaces
-a number of convenience APIs to access various public objects
-a mechanism to obtain the JspWriter for output
-a mechanism to manage session usage by the page
-a mechanism to expose page directive attributes to the scripting environment
-mechanisms to forward or include the current request to other active components in the application
-a mechanism to handle errorpage exception processing
--------------------------------------------------------------------

QUESTION NO : 90
QUESTION STATEMENT :
The ___ class describes, among other things, variables (variable name, variable class, whether the variable refers to a
new or existing object, the availability of the variable) that the tag sets for use within the tag or in the page.
CHOICES :
a) ""
CORRECT ANSWER :
TagExtraInfo
EXPLANATION :
When the JSP page containing the tag that defines scripting variables is translated, the web container generates code to
synchronize the scripting variable with the object referenced by the variable. In order to do the code generation, the web
container requires certain information about the scripting variable:
Variable name
Variable class
Whether the variable refers to a new or existing object.
The availability of the variable.
There are two ways to provide this information: by specifying the "variable" TLD sub element or by defining a tag extra
info class and including the tei-class element in the TLD. Using the "variable" element is simpler, but slightly less
flexible.
--------------------------------------------------------------------

60
QUESTION NO : 91
QUESTION STATEMENT : Is the following Web Application DD (Deployment Descriptor) declaration used for
defining the mechanism used for user authentication appropriate? True/False?
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> Example BASIC Authentication Area </realm-name>
<form-login-config>
<form-login-page> /mydir/jsp/login/login.jsp </form-login-page>
<form-error-page> /mydir/jsp/login/error.jsp </form-login-page>
</form-login-config>
</login-config>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The above declaration is incorrect. The <auth-method> tag says that the application will use HTTP BASIC
Authentication mechanism. The BASIC mechanism doesn't require any form for user authentication. The FORM Based
Authentication mechanism use forms. Thus the use of <form-login-config> element in case of BASIC Authentication
mechanism is inappropriate.
--------------------------------------------------------------------

QUESTION NO : 92
QUESTION STATEMENT : The sendRedirect() method of HttpServletResponse interface can take which of the
following types of URLs?
CHOICES :
a)
b)
c)
d)

Relative URLs
Absolute URLs
Both
None

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The sendRedirect() method sends a temporary redirect response to the client using the specified
redirect location URL. Apart from absolute URL's, this method can accept relative URLs; the servlet container must
convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without
a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/'
the container interprets it as relative to the servlet container root.

61
--------------------------------------------------------------------

QUESTION NO : 93
QUESTION STATEMENT : What will be output when the following JSP is compiled and executed?
<html>
<body bgcolor="#FFFFFF">
How are you?
out.println("I am fine");, Thankyou!
</body>
</html>
CHOICES :
a) The above code will give compilation error.
b) It will print: How are you?
I am fine, Thankyou!
c) It will print: How are you? out.println("I am fine");, Thankyou!
d) It will print: How are you? I am fine, Thankyou!
CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. Please note that "out" (The instance of PrintWriter class), an object implicity available to JSP is
accessible under JSP tags like <% .. %>. Whatever is written outside the tags will be printed out as it is. Thus the
statement "out.println("I am fine");, Thankyou!" will print itself. Also note that unless you use <br> (line break tag), the
content will be printed out on the same line. Thus the result on execution fo the above code will be - How are you?
out.println("I am fine");, Thankyou!. Thus C is the correct choice and other choices are incorrect.
--------------------------------------------------------------------

QUESTION NO : 94
QUESTION STATEMENT :
The ___ element is used to describe actions to be performed in response to some request. (e.g. format for writing the
element name - jsp:declaration, no braces <>)
CHOICES :
a) ""
CORRECT ANSWER :
jsp:scriptlet
EXPLANATION :

62
The jsp:scriptlet element is used to describe actions to be performed in response to some request. Scriptlets that are
program fragments. A jsp:scriptlet element has no attributes and its body is the program fragment that comprises the
scriptlet.
Its syntax is:
<jsp:scriptlet>code fragment goes here </jsp:scriptlet>
--------------------------------------------------------------------

QUESTION NO : 95
QUESTION STATEMENT :
___ request is used to upload data from the client to the server.
CHOICES :
a) ""
CORRECT ANSWER :
PUT
EXPLANATION :
The doPut() method is called in response to an HTTP PUT request which is used to upload data from client to server.
--------------------------------------------------------------------

QUESTION NO : 96
QUESTION STATEMENT : Consider the JSP (MyJSP.jsp) and JavaBean (MyBean.java) and HTML (MyHTML.html)
shown below. What will be the output if user enters 25 in the HTML form and press "Submit" button?
// MyHTML.html
<html>
<body bgcolor="#FFFFFF">
<form method="post" action="MyJSP.jsp">
<input type="text" name="number">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
//MyBean.java
public class MyBean
{
private String number;

63

public MyBean()
{
}
public String getNumber()
{
return number;
}
public void setNumber(String num)
{
number = num;
}
}
//MyJSP.jsp
<jsp:useBean id="myBean" scope="request" class="MyBean" >
<jsp:setProperty name="myBean" property="number" />
</jsp:useBean>
<html>
<body bgcolor="#FFFFFF">
<jsp:getProperty name="myBean" property="number" />
</body>
</html>
CHOICES :
a)
b)
c)
d)

25
Compile time error
Runtime error
None of the above

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. MyJSP page uses MyBean as specified by jsp:useBean action. On submitting the HTML form,
MyJSP is invoked. MyJSP also uses jsp:setProperty and jsp:getProperty actions. The jsp:setProperty action is used in
conjunction with the jsp:useBean action to set the value of bean properties used by JSP page. The property of the Java
Bean can also be set like below:
<jsp:setProperty name="myBean" property="name" value="<%=expression %>" />
In the question above MyBean's bean property "number" is matched with the "number" as the HTML form input
parameter which comes as a part of the request object. Thus when user inputs 25 and presses submit, the value of
number element of MyBean is set to 25. Finally jsp:getProperty action is used by MyJSP to print the number. Thus 25
will be printed as the output.
--------------------------------------------------------------------

64

QUESTION NO : 97
QUESTION STATEMENT :
If the tag handler needs to interact with the body, the tag handler must implement ___ interface (or be derived from
BodyTagSupport class).
CHOICES :
a) ""
CORRECT ANSWER :
BodyTag
EXPLANATION :
A tag handler for a tag with a body is implemented differently depending on whether the tag handler needs to interact
(the tag handler reads or modifies the contents of the body) with the body or not. If the tag handler needs to interact
with the body, it must implement BodyTag interface or be derived from BodyTagSupport class, which in turn
implements BodyTag interface. Such handlers typically implement the doInitBody() and the doAfterBody() methods.

--------------------------------------------------------------------

QUESTION NO : 98
QUESTION STATEMENT : Which of the following attributes of the page directive is used for a JSP page that wants to
use a format other than HTML for writing any static content?
CHOICES :
a)
b)
c)
d)
e)

content
contentType
text/html
nonHTML
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. Static content in JSP can be expressed in any text-based format such as HTML, WML, and
XML. The default format is HTML. To use any non-html format, one needs to include a page directive with the
contentType attribute to set the format type at the beginning of the JSP page. Here is an example which uses XML
format in a JSP page;
<%@ page contentType="text/test.xml" %>
All other attributes are invalid. Thus B is correct and others are incorrect.

--------------------------------------------------------------------

65

QUESTION NO : 99
QUESTION STATEMENT : Which of the following design patterns reduces the coupling between presentation-tier
clients and business services in a web application?
CHOICES :
a)
b)
c)
d)
e)

Value Objects
MVC
Data Access Object
Business Delegate
None of the above

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business
services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business
services: when the implementation of the business services change, the code in the presentation tier must change. The
goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the
business service API, thus hiding the underlying implementation details of the service. In this way we enhance the
manageability of the application. Using this design pattern, the client request is first handled by a Servlet that dispatches
to a JSP page for formatting and display. The JSP is responsible for delegating the processing of business functionality
to a "business delegate" via a JavaBean.

--------------------------------------------------------------------

QUESTION NO : 100
QUESTION STATEMENT : If a POST request is received and the doPost() method is not implemented, which of the
following status codes will be returned to the client?
CHOICES :
a)
b)
c)
d)

100
200
300
400

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. Like any other doXXX() method, if POST request is received (in case of other doXXX()
methods, XXX request is received) and doPost() method is not implemented, an HTTP 400 "Bad Request" message is
returned to the client.
--------------------------------------------------------------------

66

QUESTION NO : 101
QUESTION STATEMENT : The attributeAdded(), attributeRemoved() and attributeReplaced() methods of
HttpSessionAttributeListener takes HttpSessionAttributeEvent as an input. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
No, the above methods take HttpSessionBindngEvent as an input. That's for legacy reasons; the servlet API (prior to
v2.3) already had an HttpSessionBindingEvent class, so it was reused.

--------------------------------------------------------------------

QUESTION NO : 102
QUESTION STATEMENT :
If the isErrorPage attribute of page directive has "true" as its value then the implicit variable ___ is available to the
current JSP.
CHOICES :
a) ""
CORRECT ANSWER :
exception
EXPLANATION :
The isErrorPage attribute of the page directive indicates if the current JSP page is intended to be the URL target of
another JSP page's errorPage. Its default value is false. If "true", then the implicit variable "exception" is available, and
refers to the instance of the java.lang.Throwable thrown at runtime by the JSP causing the error.
--------------------------------------------------------------------

QUESTION NO : 103
QUESTION STATEMENT :
The ___ method (a non-deprecated method of servlet 2.3 api) of the HttpSession interface is used to retrieve the object
bound with the specified name to an HttpSession in a web application. (Write only the method name without any braces
e.g. myMethod and not myMethod())

67
CHOICES :
a) ""
CORRECT ANSWER :
getAttribute
EXPLANATION :
An Http session can have objects stored in it with a name. To retrieve an object(s), HttpSession (of servlet api 2.3)
provides following methods (non-deprecated methods):
a.) getAttribute(String): public java.lang.Object getAttribute(java.lang.String name)
Returns the object bound with the specified name in this session, or null if no object is bound under the name.
Parameters:
name - a string specifying the name of the object
b.) getAttributeNames(): public java.util.Enumeration getAttributeNames()
Returns an Enumeration of String objects containing the names of all the objects bound to this session.
--------------------------------------------------------------------

QUESTION NO : 104
QUESTION STATEMENT : Which of the following syntax is used to embed java scriptlet in a JSP page?
CHOICES :
a)
b)
c)
d)
e)

<%@ ... %>


<% ... %>
< ... >
<%! ... %>
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. Scriptlets can contain any code fragments that are valid for the scripting language specified in
the language directive. Scriptlets are executed at request-processing time. Whether or not they produce any output into
the out stream depends on the code in the scriptlet.
When all scriptlet fragments in a given translation unit are combined in the order they appear in the JSP page, they must
yield a valid statement, or sequence of statements, in the specified scripting language. If you want to use the
%>character sequence as literal characters in a scriptlet, rather than to end the scriptlet, you can escape them by typing
%\>.
Example
<%

68
for(int i=0; i<10; i++)
{
out.println("The value of i is:" + i);
}
%>
Syntax
<% scriptlet %>
--------------------------------------------------------------------

QUESTION NO : 105
QUESTION STATEMENT : Consider the following deployment descriptor entry of a web application:
<web-app>
...
<display-name>MyListener</display-name>
...
<listener>
<listener-class>whizlabs.com.SCWCDListner</listener-class>
</listener>
<listener>
<listener-class>whizlabs.com.SCJPListner</listener-class>
</listener>
<listener>
<listener-class>whizlabs.com.IBMXMLListner</listener-class>
</listener>
...
</web-app>
If all the listener classes (SCWCDListener, SCJPListener and IBMXMLListener) implements HttpSessionListener,
which of the following statements are true?
CHOICES :
a) The web container will register SCWCDListener first followed by SCJPListener and finally IBMXMLListener.
b) The web container will register IBMXMLListener first followed by SCJPListener and finally SCWCDListener.
c) The order in which web container will register the listeners can't be predicted.
d) On application shut down, the SCWCDListener will be the first listener to be notified by followed by SCJPListener
and then finally IBMXMLListener.
e) On application shut down, the IBMXMLListener will be the first listener to be notified by followed by SCJPListener
and then finally SCWCDListener.
f) On application shutdown, the order in which the above listeners are notified can't be predicted.
CORRECT ANSWER : ae
EXPLANATION :
Choices A and E are correct. The web container registers the listener instances according to the interfaces they
implement and the order in which they appear in the deployment descriptor. During web application execution listeners

69
are invoked in the order of their registration. On application shutdown, listeners are notified in the reverse order to their
declarations with notifications to sessions listeners preceding notifications to context listeners: Session listeners must be
notified of session invalidations prior to context listeners being notified of application shutdown. Since all the classes
implement HttpSessionListener interface, choice A and E are correct.
--------------------------------------------------------------------

QUESTION NO : 106
QUESTION STATEMENT : A tag library descriptor (TLD) is an XML document that describes a tag library. A TLD
contains information about a library as a whole and about each tag contained in the library. The root of a TLD is the
taglib element. One of the subelement of taglib element is the tag element. Which of the following are valid sub
elements of the tag element?
CHOICES :
a)
b)
c)
d)
e)

name
tag-class
body-content
description
tag-id

CORRECT ANSWER : abcd


EXPLANATION :
A, B, C and D are correct. The "name" refers to the name of the tag used in the JSP page. The "tag-class" maps the
name to the fully qualified java class, which implements the Tag interface. A "body-content" specifies the content type
of the tag, if any. The "description" element provides the optional information on the tag. There is no "tag-id" element,
instead name is used. Thus A, B, C and D are correct and E is incorrect. Here is an example of tag element with various
sub elements:
<taglib>
...
<tag>
<name> myTag </name>
<tag-class> java.whizlabs.com.scwcd.MyTag </tag-class>
<body-content> empty </body-content>
<description> This is My Tag </description>
</tag>
</taglib>
--------------------------------------------------------------------

QUESTION NO : 107
QUESTION STATEMENT :
The ___ interface Provides a way to identify a user across more than one page request or visit to a Website and to store
information about that user.
CHOICES :

70

a) ""
CORRECT ANSWER :
HttpSession
EXPLANATION :
The HttpSession interface provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session
persists for a specified time period, across more than one connection or page request from the user. A session usually
corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using
cookies or rewriting URLs.
This interface allows servlets to
-View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
-Bind objects to sessions, allowing user information to persist across multiple user connections
--------------------------------------------------------------------

QUESTION NO : 108
QUESTION STATEMENT : The system exposes the entire business service API to its clients, often across a network.
Which design pattern fits in the described context?
CHOICES :
a)
b)
c)
d)

Data Access Object


Business Delegate
Value Object
Model View Controller

CORRECT ANSWER : b
EXPLANATION :
In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business services. As a result, the
presentation-tier components are vulnerable to changes in the implementation of the business services: when the
implementation of the business services change, the code in the presentation tier must change. The goal of Business
Delegate object design pattern is to minimize the coupling between presentation-tier clients and the business service
API, thus hiding the underlying implementation details of the service. In this way we enhance the manageability of the
application. Using this design pattern, the client request is first handled by a Servlet that dispatches to a JSP page for
formatting and display. The JSP is responsible for delegating the processing of business functionality to a "business
delegate" via a JavaBean.
Another benefit is that the delegate may cache results. Caching results can significantly improve performance, because
it limits unnecessary and potentially costly round trips over the network.
--------------------------------------------------------------------

71

QUESTION NO : 109
QUESTION STATEMENT : Consider the following servlet implementing the SingleThreadModel interface
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SingleThread extends HttpServlet implements SingleThreadModel
{
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
int localCount = ++count;
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
out.println("number of accesses = "+localCount);
}
}
The above servlet is installed on Java Web Server, and then accessed simultaneously through 4 different browser
windows. What will be the outcome?
CHOICES :
a) The count will increase in a regular logical manner, i.e., if it returned a count of 5 in window 1, and after that, the
result is returned to window 2, the count 6 will be displayed, and so on
b) The count displayed in different windows will be unpredictable.
c) If we had synchronized the increment and display of the count, the count would have been incremented logically
throughout windows
d) It will give compilation error.
CORRECT ANSWER : b
EXPLANATION :
When a servlet implements SingleThreadModel, it is guaranteed by the servlet API that no two threads will execute
concurrently the service() method of the servlet. What many web servers do is to make a pool of instances of the servlet.
When a request for the servlet is received, one of the instances is assigned to servicing the request. If another request
comes before the instance is freed, then handling this request is assigned to a different instance from the instance pool.
Since each instance in the pool is a different object, these instances do not share their instance variables. In our
example, what count is displayed will depend upon which instance is assigned to handling the request - if an instance
who's count has advanced to 5 is assigned, then the incremented count 6 is displayed; on the other hand, if a brand new

72
instance is assigned, then the count 1 is displayed. This behaviour, however, is server implementation dependent and
thus unpredictable.

--------------------------------------------------------------------

QUESTION NO : 110
QUESTION STATEMENT : Is the following declaration for servlet-name element used in DD file correct?
<servlet-name>
<servlet-mapping> java.sun.com.MyServlet </servlet-mapping>
<url-pattern>myservlet/*</url-pattern>
</servlet-name>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The above declaration is incorrect as servlet-mapping is the parent element of servlet-name and not the other way
round. The DTD for servlet-mapping is follows:
<!ELEMENT servlet-mapping (servlet-name, url-pattern)>
The servlet-mapping element defines a mapping between a servlet and a url pattern. The servlet-name element contains
the canonical name of the servlet. Each servlet name is unique within the web application. The url-pattern element
contains the url pattern of the mapping.
--------------------------------------------------------------------

QUESTION NO : 111
QUESTION STATEMENT :
The ____ method defined by the HttpSession interfaces expires the current session. (Write only the method name
without any braces e.g. myMethod and not myMethod())
CHOICES :
a) ""
CORRECT ANSWER :
invalidate

73
EXPLANATION :
The invalidate() method of the HttpSession interface expires the current session. It causes the representation of the
session to be invalidated and removed from its context.
--------------------------------------------------------------------

QUESTION NO : 112
QUESTION STATEMENT :
The sessionCreated() and sessionDestroyed() are methods of ___ interface. (Write only the interface name)
CHOICES :
a) ""
CORRECT ANSWER :
HttpSessionListener
EXPLANATION :
The HttpSession listener (object implementing the HttpSessionListener interface) are notified when an HttpSession has
been created, invalidate or timed out. This functionality is provided by the following methods of the
HttpSessionListener interface:
a.) sessionCreated(HttpSessionEvent) - Notification that a session was created.
b.) sessionDestroyed(HttpSessionEvent) - Notification that a session was invalidate.
--------------------------------------------------------------------

QUESTION NO : 113
QUESTION STATEMENT : To write a message to a web application log, which of the following class/interface
provides the log methods()?
CHOICES :
a)
b)
c)
d)
e)

HttpServlet
HttpServletResponse
HttpServletRequest
ServletContext
PageContext

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The ServletContext interface defines a set of methods that a servlet uses to communicate with its
servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. Following are the
log methods of the ServletContext interface:

74
a.) log(Exception, String) : public void log(java.lang.Exception exception, java.lang.String msg)
Deprecated. As of Java Servlet API 2.1, use log(String, Throwable) instead. This method was originally
defined to write an exception's stack trace and an explanatory error message to the servlet log file.
b.) log(String) : public void log(java.lang.String msg)
Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log file is
specific to the servlet container.
Parameters:
msg - a String specifying the message to be written to the log file
c.) log(String, Throwable) : public void log(java.lang.String message, java.lang.Throwable throwable)
Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. The name and
type of the servlet log file is specific to the servlet container, usually an event log.
Parameters:
message - a String that describes the error or exception
throwable - the Throwable error or exception
Also please note that GenericServlet class (in javax.servlet package) also implements the log method, declared in the
ServletContext interface.
--------------------------------------------------------------------

QUESTION NO : 114
QUESTION STATEMENT : The statement below best describes which of the following security issues?
"The means used to prove that information has not been modified by a third party while in a transit"
CHOICES :
a)
b)
c)
d)
e)
f)

Authentication
Authorization
Data Integrity
Auditing
Malicious Code
Web site attacks

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. Following are the short definitions of the terms above:
Authentication - Authentication is the process we perform to verify that a user is who they say they are.
Authorization - Authorization is the process by which you determine what actions a particular user can perform.
Data Integrity - It is used to prove that information has not been modified by a third party while in a transit.

75
Auditing - The process of recording a log of user activities within an application.
Malicious Code - Code aimed at breaking the security rules of a web application.
Web site attacks - External attacks by the hackers to the web application.
--------------------------------------------------------------------

QUESTION NO : 115
QUESTION STATEMENT : The Java objects used by a JSP page can be associated with a scope attribute which defines
the accessibility of the corresponding object. Following are the scopes that an object can can be associated with :
page
session
request
application
Which of the following lines of code (regarding above scopes) are correct in the generated servlet for a JSP?
CHOICES :
a)
b)
c)
d)

ServletContext application = pageContext.getApplication();


HttpSession session = pageContext.getSession();
ServletContext application = pageContext.getServletContext();
HttpSession session = pageContext.getServletContext();

CORRECT ANSWER : bc
EXPLANATION :
Choice B and C are correct. The pageContext object is an instance of class javax.servlet.jsp.PageContext and it
encapsulates the page context for the particular JSP page.
Objects with session scope are accessible from pages processing requests that are in the same session as the one in
which they were created. The getSession() method returns the HttpSession object associated with the invoking
PageContext object.
Objects with application scope are accessible from pages processing requests that are in the same application as they
one in which they were created. The application object is the servlet context obtained from the servlet configuration
object. The getServletContext() method returns the ServletContext object associated with the invoking PageContext
object.
Thus choices B and C are correct while others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 116
QUESTION STATEMENT : The benefits listed below are provided by which of the design patterns?
1.) Improves performance using caching mechanism.

76
2.) Reduce coupling between the presentation tier and the Business tier.
CHOICES :
a)
b)
c)
d)

Business Delegate
Data Access Object
Model View Controller
Value Object

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business
services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business
services: when the implementation of the business services change, the code in the presentation tier must change. The
goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the
business service API, thus hiding the underlying implementation details of the service.
Another benefit is that the Business delegate may cache results. Caching results can significantly improve performance,
because it limits unnecessary and potentially costly round trips over the network.
--------------------------------------------------------------------

QUESTION NO : 117
QUESTION STATEMENT :
For a JSP Custom given below, ___ be written at the position //xxx to indicate that the count attribute is optional.
<tag>
...
<attribute>
<name> count </name>
<required> //xxx </required>
</attribute>
</tag>
CHOICES :
a) ""
CORRECT ANSWER :
false
EXPLANATION :
To indicate that an attribute is optional, "<required> false </required>" tag is used.
--------------------------------------------------------------------

77

QUESTION NO : 118
QUESTION STATEMENT :
During the ___ phase the container locates or creates the JSP page implementation class that corresponds to a given JSP
page.
CHOICES :
a) ""
CORRECT ANSWER :
translation
EXPLANATION :
JSP pages are textual components. They go through two phases: a translation phase, and a request phase (or execution
phase). Translation is done once per page. The request phase is done once per request.
The JSP page is translated to create a servlet class, the JSP page implementation class, that is instantiated at request
time. The instantiated JSP page object handles requests and creates responses. JSP pages may be translated prior to their
use, providing the web application, with a servlet class that can serve as the textual representation of the JSP page.
The translation may also be done by the JSP container at deployment time, or on-demand as the requests reach an
untranslated JSP page.
--------------------------------------------------------------------

QUESTION NO : 119
QUESTION STATEMENT : Which of the following class/interface has a method to locate the value of the named
attribute stored in page/request/session/application scope of a JSP?
CHOICES :
a)
b)
c)
d)
e)
f)

ServletContext
PageContext
HttpServletRequest
HttpServletResponse
HttpSession
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. A PageContext instance provides access to all the namespaces associated with a JSP page,
provides access to several page attributes, as well as a layer above the implementation details.
The PageContext class has the following method for the stated purpose:

78
public abstract java.lang.Object findAttribute(java.lang.String name): Searches for the named attribute in page, request,
session (if valid), and application scope(s) in order and returns the value associated or null.
Returns:
the value associated or null
Also note the following useful description about PageContext :
The PageContext class is an abstract class, designed to be extended to provide implementation dependent
implementations thereof, by conformant JSP engine runtime environments. A PageContext instance is obtained by a JSP
implementation class by calling the JspFactory.getPageContext() method, and is released by calling
JspFactory.releasePageContext().
The PageContext provides a number of facilities to the page/component author and page implementor, including:
a single API to manage the various scoped namespaces
a number of convenience API's to access various public objects
a mechanism to obtain the JspWriter for output
a mechanism to manage session usage by the page
a mechanism to expose page directive attributes to the scripting environment
mechanisms to forward or include the current request to other active components in the application
a mechanism to handle errorpage exception processing

--------------------------------------------------------------------

QUESTION NO : 120
QUESTION STATEMENT : Considering the following taglib definition, identify the correct tag usages.
<taglib>
...
<tag>
<name> myTag </name>
<tag-class> java.whizlabs.com.scwcd.MyTag </tag-class>
<body-content> JSP </body-content>
<attribute>
<name> myName </name>
<required> true </required>
</attribute>
<description> This is My Tag </description>
</tag>
</taglib>
CHOICES :
a)
b)
c)
d)

<tt:myTag myName="scwcd"> </tt:myTag>


<tt:myTag > </tt:myTag>
<tt:myTag myName="scwcd"> <% int i=0; %> </tt:myTag>
<tt:myTag > <% int i=0; %> </tt:myTag>

79
CORRECT ANSWER : c
EXPLANATION :
Choice A and C are the correct choices. The taglib definition says that the tag requires (<required> is true) an attribute
"myName". Thus choice B and D are incorrect. It also says that the body-content should be JSP. When "JSP" is
specified as the type of body-content then it is valid for the tag to be empty. But if the value is empty, then the body
must be empty. Thus both choice A and C are correct.
--------------------------------------------------------------------

QUESTION NO : 121
QUESTION STATEMENT : The web.xml file can include a map between URIs and TLD resource paths.The map is
described using the taglib element of the Web Application Deployment descriptor in WEB-INF/web.xml. Which of the
following statements are true regarding the "taglib" element?
CHOICES :
a) It can have "id" as its attribute.
b) The sub-elements of "taglib" element are:
taglib-uri
taglib-location
c) The sub-elements of "taglib" element are:
taglib-name
taglib-value
d) The sub-elements of "taglib" element are:
taglib-name
taglib-location
CORRECT ANSWER : ab
EXPLANATION :
Choice A and B are correct. The DTD for taglib element of DD in web.xml is as follows:
<!ELEMENT taglib (taglib-uri,taglib-location )>
<!ATTLIST taglib id ID #IMPLIED>
It tells that the 2 sub-elements of taglib element are: taglib-uri and taglib-location. Also it can have "id" as its attribute.
Here is an example:
<taglib>
<taglib-uri>/myPRlibrary</taglib-uri>
<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-uri>
</taglib>
--------------------------------------------------------------------

QUESTION NO : 122
QUESTION STATEMENT :
The getResource() and getResourceAsStream() methods belong to ___ interface.

80

CHOICES :
a) ""
CORRECT ANSWER :
ServletContext
EXPLANATION :
The ServletContext interface provides direct access to the hierarchy of static content documents that are part of the web
application, including HTML, GIF, and JPEG files, via the following methods of the ServletContext interface:
public java.net.URL getResource(java.lang.String path)
public java.io.InputStream getResourceAsStream(java.lang.String path)
The getResource and getResourceAsStream methods take a String with a leading "/" as argument which gives the path
of the resource relative to the root of the context.
--------------------------------------------------------------------

QUESTION NO : 123
QUESTION STATEMENT : "EVAL_BODY_INCLUDE" is one of the possible return types of doAfterBody().
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The doAfterBody() method process body (re)evaluation.This method is invoked by the JSP Page implementation object
after every evaluation of the body into the BodyEvaluation object. The method is not invoked if there is no body
evaluation. If doAfterBody returns EVAL_BODY_AGAIN, a new evaluation of the body will happen (followed by
another invocation of doAfterBody). If doAfterBody returns SKIP_BODY no more body evaluations will occur, the
value of out will be restored using the popBody method in pageContext, and then doEndTag will be invoked. The
"EVAL_BODY_INCLUDE" is not a valid return type for this method.
--------------------------------------------------------------------

QUESTION NO : 124
QUESTION STATEMENT : Which of the following is the simplest way for making a servlet "thread-safe"?
CHOICES :
a) Implement the SingleThreadModel interface.

81
b) Implement the ThreadSafeModel interface.
c) By maintaining a pool of servlet instances.
d) None of the above.
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. If a servlet implements the SingleThreadModel interface, the server guarantees that no more
than one thread can execute service(), doGet(), doPost() method at a time for a particular servlet instance. In case
SingleThreadModel interface is implemented, the service(), doPost(), doGet() methods cannot be executed concurrently.
This puts a performance penalty, in case there are many simultaneous client requests. The performance can be improved
by maintaining a pool of servlet instances. Maintaining a pool of servlet instances is not the way to ensure thread safety.
Since choice A is correct, choice D is incorrect.
--------------------------------------------------------------------

QUESTION NO : 125
QUESTION STATEMENT : Considering the DD file (Deployment Descriptor, web.xml) entry below, choose the
correct statements?
<session-config>
<session-timeout>1 </session-timeout>
</session-config>
CHOICES :
a)
b)
c)
d)

The default timeout interval for the session created will be 1 minute.
The default timeout interval for the session created will be 1 second.
The default timeout interval for the session created will be 1 hour.
The above syntax is incorrect.

CORRECT ANSWER : a
EXPLANATION :
Choice A is correct. There is nothing wrong in the above syntax. Thus choice D is incorrect. The <session-timeout>
element takes time in "minutes" for the session timeout interval. Thus choice A is correct. Also please note that, servlet
API also provides a mechanism for setting and retrieving session timeout interval as below:
The default timeout period for sessions is defined by the servlet container and can be obtained via the
getMaxInactiveInterval() method of the HttpSession interface. This timeout can be changed by the Developer using the
setMaxInactiveInterval() method of the HttpSession interface. The timeout periods used by these methods are defined in
seconds. By definition, if the timeout period for a session is set to -1, the session will never expire.
--------------------------------------------------------------------

QUESTION NO : 126
QUESTION STATEMENT :
In your web application you are facing the following problem:

82

Your presentation components are tightly bound to the business service implementation. As a result of which, whenever
there is a change in the business service API, the code in the presentation component needs to be changed. This also
causes loss in performance when the client (presentation component) makes too many invocations to use business
service API.
The ideal design pattern to solve the above problem is _____. (write only the design pattern name, e.g. Factory Method)
CHOICES :
a) ""
CORRECT ANSWER :
Business Delegate
EXPLANATION :
The goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and
the business service API, thus hiding the underlying implementation details of the service. In this way we enhance the
manageability of the application. Using this design pattern, the client request is first handled by a Servlet that dispatches
to a JSP page for formatting and display. The JSP is responsible for delegating the processing of business functionality
to a "business delegate" via a JavaBean.
--------------------------------------------------------------------

QUESTION NO : 127
QUESTION STATEMENT : Which of the following are valid JSP codes?
CHOICES :
a)
b)
c)
d)

<%!int i = 0; %>
<%! int i=0; %>
<% !int i =0; %>
<% int i = 0 %>

CORRECT ANSWER : ab
EXPLANATION :
Choice A and B are correct. Each scripting element in JSP has a "<%"-based syntax as follows:
<%! this is a declaration %>
<% this is a scriptlet %>
<%= this is an expression %>
White space is optional after "<%!", "<%", and "<%=", and before "%>". Thus choice A and B are correct.Choice C is
incorrect as it has space between <% and ! which is not valid. Choice D is incorrect as ';' is missing after "int i = 0".
--------------------------------------------------------------------

83

QUESTION NO : 128
QUESTION STATEMENT :
The ___ element defines the session parameters for a web application. (Just write the element name without any braces.
e.g. init-param)
Hint : DTD - <!ELEMENT "element_name" (session-timeout?)>
CHOICES :
a) ""
CORRECT ANSWER :
session-config
EXPLANATION :
The session-config element defines the session parameters for the current web application. The DTD for it is as follows:
<!ELEMENT session-config (session-timeout?)>
The session-timeout element defines the default session timeout interval for all sessions created in this web application.
The specified timeout must be expressed in a whole number of minutes.
--------------------------------------------------------------------

QUESTION NO : 129
QUESTION STATEMENT : In case of a distributable environment, a listener event on one machine/JVM will not
trigger the ServletContext listener on other machine/JVM.
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
In case of a distributable environment, each ServletContext instance will have its own instance of the listener object.
Therefore, if a ServletContext on one machine/JVM is initialized/destroyed, it will not trigger a listener on other
machine/JVM. Thus the above statement is true.
--------------------------------------------------------------------

QUESTION NO : 130
QUESTION STATEMENT :

84
Consider the following Tag Handler code, which implements doStartTag() method as follows:
public int doStartTag() throws JspException
{
try
{
pageContext.getOut().print("Hello World");
}
catch( Exception ex)
{
throw new JspException("IO problem");
}
return XXX;
}
To make sure that evaluation of the tag body should not take place, ____ should be placed at position XXX;
CHOICES :
a) ""
CORRECT ANSWER :
SKIP_BODY
EXPLANATION :
In the above code, the pageContext is set by the JSP container and is available to the Tag Handler. The SKIP_BODY
values makes sure that no evaluation of the tag body takes place.
Following are the details about the possible return types from doStartTag() method:
This method returns Tag.EVAL_BODY_INCLUDE or Body-Tag. EVAL_BODY_BUFFERED to indicate that the body
of the action should be evaluated or SKIP_BODY to indicate otherwise. When a Tag returns EVAL_BODY_INCLUDE
the result of evaluating the body (if any) is included into the current "out" JspWriter as it happens and then doEndTag()
is invoked.
BodyTag.EVAL_BODY_BUFFERED is only valid if the tag handler implements BodyTag.

--------------------------------------------------------------------

QUESTION NO : 131
QUESTION STATEMENT : Which of the following is the class corresponding to the "page" implicit scope object
available to a JSP?
CHOICES :
a)
b)
c)
d)

javax.servlet.jsp.PageContext
javax.servlet.ServletContext
javax.servlet.jsp.ServletContext
javax.servlet.PageContext

85
e) java.lang.Object
CORRECT ANSWER : e
EXPLANATION :
E is the correct choice. The implicit object "page" available to a JSP is of type java.lang.Object and is instance of this
page's implementation class processing the current request. When the scripting language is "java" then "page" is a
synonym for "this" in the body of the page.
Please note that it is "pageContext" and not "page" object which is an instance of javax.servlet.jsp.PageContext.

--------------------------------------------------------------------

QUESTION NO : 132
QUESTION STATEMENT : In a multi-tiered application, server-side components, such as enterprise beans,
encapsulate non-trivial business logic and business data. These components expose their interfaces and thus the
complexity of the distributed services clients.
The problems resulted by the above scenario are best solved by adopting which of the following design patterns.
CHOICES :
a)
b)
c)
d)
e)

Data Access Object


Model View Controller
Session Facade
Business Delegate
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The following problems are resulted from the scenario discussed above:
1.) Tight coupling which leads to direct dependence between clients and business objects.
2.) Too many method invocations between client and server leading to network performance problems.
3.) Lack of a uniform client access strategy exposing business objects to misuse.
The session faade abstracts the underlying business object interactions and provides a service layer that exposes only
the required interfaces. Thus, it hides from the client's view the complex interactions between the participants. The
session faade manages the interactions between the business data and service objects that participate in the workflow,
and it encapsulates the business logic associated with the requirements. Thus, the session bean (representing the session
faade) manages the relationships between business objects. The session bean also manages the lifecycle of these
participants by creating, locating (looking up), modifying, and deleting them as required by the workflow. In a complex
application, the session faade may delegate this lifecycle management to a separate object. For example, to manage the
lifecycle of participant session and entity beans, the session faade may delegate that work to a Service Locator object .
About Facade Design Pattern:
Intent

86
* To provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes
the subsystem easier to use.
Problem
* Need for a simplified interface to the overall functionality of a complex subsystem.
Motivation
* Structuring a system into subsystems helps reduce complexity. * Subsystems are groups of classes, or groups of
classes or other subsystems. * The interface exposed by the classes in a subsystem or a set of subsystems can become
quite complex. * One way to reduce the complexity is to introduce a facade object that provides a single, simplified
interface to a more general facilities of a subsystem.
--------------------------------------------------------------------

QUESTION NO : 133
QUESTION STATEMENT : Following implicit objects are accessible to a jsp page across multiple requests.
request
session
application
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The request object has 'request' scope. An object inside a request scope is accessible from all the pages processing the
request where the object was created. It is not accessible across multiple requests. The session object has 'session'
scope. An object inside session scope is visible from all the pages (across multiple requests) belonging to the session in
which it was created. The application object has 'application' scope. An object inside an application scope is accessible
from all the pages (across multiple requests) that belong to the particular application. Thus only session and application
objects fulfill the stated criteria. Thus the above statement is false.
--------------------------------------------------------------------

QUESTION NO : 134
QUESTION STATEMENT : Consider a shopping cart web application which uses session management, implemented
using Servlet API (HttpSession interface). Whenever a new user logins, his name (String type) is stored in a session
using the setAttribute() method of the HttpSession interface. The variable used to store the user name is "myName".
To retrieve the user name from the session, which of the following lines of code is correct? Assuming request and
response are arguments of type HttpServletRequest and HttpServletResponse respectively, to the service() method of
the servlet.
CHOICES :

87
a)
b)
c)
d)
e)

String userName = request.getSession().getAttribute("myName");


String userName = request.getSession().getAttribute(myName);
String userName = response.getSession().getAttribute("myName");
String userName = response.getSession().getAttribute(myName);
None of the above

CORRECT ANSWER : e
EXPLANATION :
E is the correct choice. Choice C and D are incorrect as getSession() is the method of HttpServletRequest interface.
Choice B is incorrect as the syntax used here is incorrect; the input argument to getAttribute() method is of String type
("myName" should be used instead of myName). Choice A is incorrect as the return type of getAttribute method is
Object and thus explicit casting is needed for assignment to string.
The correct code will be :
String userName = (String)request.getSession().getAttribute("myName");
--------------------------------------------------------------------

QUESTION NO : 135
QUESTION STATEMENT : In a web application, the user is given a form to login to his account. The user enters his
login id and and password. The password is sent to the server after being MD5 encrypted by the browser.
In the above scenario, which of the following security mechanisms would have been employed?
CHOICES :
a)
b)
c)
d)
e)

BASIC
DIGEST
FORM
CLIENT-CERT
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. In case of BASIC mechanism, data is encrypted with BASE64 encoding. The DIGEST
mechanism is the same as BASIC mechanism except that the password is encrypted using MD5 algorithm by the
browser before sending it over the wire.
Please note that none of the current browsers support DIGEST authentication mechanism. Also, it is still possible to
capture the digested password and reuse it later, so you should also encrypt any communications when using DIGEST
authentication.
--------------------------------------------------------------------

QUESTION NO : 136

88
QUESTION STATEMENT : While designing and developing servlets you need not worry about the thread safety of
class variables. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The class variables are not thread safe. Since there is only one class variable for each instance of a servlet, multiple or
concurrent servlet requests will share the class variable. Class variables will be shared between service() threads as well
as between different instances of the servlet class.
Even the SingleThreadModel interface does not prevent synchronization problems that result from servlets accessing
shared resources such as static class variables or classes outside of the scope of the servlet. Thus the above statement is
incorrect.
--------------------------------------------------------------------

QUESTION NO : 137
QUESTION STATEMENT : The taglib element is the document root and is used to describe a JSP tag library. Which of
the following sub-elements of taglib element are optional?
CHOICES :
a)
b)
c)
d)
e)

tlib-version
jsp-version
uri
short-name
description

CORRECT ANSWER : ce
EXPLANATION :
C and E are correct choices. A tag library descriptor (TLD) is an XML document that describes a tag library. A TLD
contains information about a library as a whole and about each tag contained in the library. The root of a TLD is the
taglib element.
Here is the DTD for taglib:
<!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?, display-name?,
small-icon?, large-icon?, description?, validator?, listener*, tag+) >
The elements with '?' prefix are optional. Thus C and E are correct.

--------------------------------------------------------------------

89

QUESTION NO : 138
QUESTION STATEMENT : Considering the following JSP code, which of the lines of code should be placed at "line
8" to print "1 2 3 4 5 6 7 8 9 10 "?
1: <html>
2: <head>
3: <title>Untitled Document</title>
4: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5: </head>
6: <body bgcolor="#FFFFFF">
7: <% for (int i=1; i<=10; i++) { %>
8:
9: <% } %>
10: </body>
11: </html>
CHOICES :
a)
b)
c)
d)
e)
f)

i
<% i %>
<%= i %>
<%= i; %>
<% i; %>
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. Following is the syntax for various scripting elements in JSP:
Declarations (e.g.<%! int i=4; %>)
Scriplets
(e.g. <% for (int count=0; count<10; i++) { out.println("The counter is:" + i); } %>)
Expressions (e.g.<%=myBean.getNumber() %>)
An expression is a shorthand notation for a scripltlet that outputs a value in the response stream back to the client.
When an expression is evaluated, the result is converted to a string and is displayed. As given above, an expression
doesn't ends with ';'.
We need to print the value of i in the above code for each iteration. Thus choice C is correct. Others will give
compilation error.
--------------------------------------------------------------------

QUESTION NO : 139
QUESTION STATEMENT : Which of the following elements are required to define the web resource collection for a
web application?
CHOICES :
a) <resource-name>
b) <http-method>

90
c) <url-location>
d) <description>
e) None of the above
CORRECT ANSWER : e
EXPLANATION :
E is the correct choice. The web-resource-collection element is used to identify a subset of the resources and HTTP
methods on those resources within a web application to which a security constraint applies. If no HTTP methods are
specified, then the security constraint applies to all HTTP methods.
Here is the DTD for <web-resource-collection> element:
<!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)>
It indicates that only web-resource-name element is mandatory and rest are optional ("?" indicates optional (none or one
occurrence) and "*" indicates none or more (any number) occurrences).
--------------------------------------------------------------------

QUESTION NO : 140
QUESTION STATEMENT : A web application is made for students to take test and get feedback report. Whenever a
students completes his/her test, the score for each and every question is stored in a database.
For implementing an effective feedback mechanism, the student should be able to view different kinds of reports. For
e.g. , there should be a graphical report for overall test. There should be topic-wise report and so on.
Which of the design patterns below will best fulfill the above requirement?
CHOICES :
a)
b)
c)
d)
e)

Data Access Object


Business Delegate
Model View Controller
Session Facade
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. By applying the Model-View-Controller (MVC) architecture to a J2EE application, you separate
core data access functionality from the presentation and control logic that uses this functionality. Such separation allows
multiple views to share the same enterprise data model, which makes supporting multiple clients easier to implement,
test, and maintain. In this way the same controller can create multiple views of the same data.
--------------------------------------------------------------------

QUESTION NO : 141

91
QUESTION STATEMENT :
The sub-elements of context-param element are param-name, param-value and ___.
CHOICES :
a) ""
CORRECT ANSWER :
description
EXPLANATION :
The context-param element contains the declaration of a web application's servlet context initialization parameters.
Here is the DTD for context-param:
<!ELEMENT context-param (param-name, param-value, description?)>
The param-name element contains the name of a parameter. The param-value element contains the value of a parameter.
The description element is used to provide descriptive text about the parent element.
--------------------------------------------------------------------

QUESTION NO : 142
QUESTION STATEMENT : Which of the following are valid sub-elements of the <servlet> element used in the
deployment descriptor of a web application?
CHOICES :
a)
b)
c)
d)
e)
f)

<servlet-name>
<servlet-mapping>
<servlet-version>
<servlet-value>
<servlet-class>
<jsp-file>

CORRECT ANSWER : aef


EXPLANATION :
A, E and F are correct choices. The servlet element contains the declarative data of a servlet. If a jsp-file is specified and
the load-on-startup element is present, then the JSP should be precompiled and loaded.
Here is the DTD for the servlet element.
<!ELEMENT servlet (icon?, servlet-name, display-name?, description?,
(servlet-class|jsp-file), init-param*, load-on-startup?, securityrole-ref*)>

92
The servlet-name element contains the canonical name of the servlet. The servlet-class element contains the fully
qualified class name of the servlet. The jsp-file element contains the full path to a JSP file within the web application.
Please note that either of servlet-class and jsp-file should be present as seem from the DTD.
--------------------------------------------------------------------

QUESTION NO : 143
QUESTION STATEMENT : In our web application we want to partially process a request and then transfer to another
component depending on the nature of the request. To transfer control to another web component, we can use either of
the following approaches:
<jsp:forward>
HttpServletResponse.sendRedirect()
The above two approaches behave identically without any difference.
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The two approaches are not identical. When you forward a request (using <jsp:forward>, the forwarding is done within
the server, and limited in scope to where you can forward. Redirections (using HttpServletResponse.sendRedirect())are
done on the client and thus don't have these limitations.
--------------------------------------------------------------------

QUESTION NO : 144
QUESTION STATEMENT : Which of the following are valid methods of the Tag interface?
CHOICES :
a)
b)
c)
d)
e)
f)

doInitBody()
doStartBody()
doAfterBody()
doInitTag()
doStartTag()
doEndTag()

CORRECT ANSWER : ef
EXPLANATION :
E and F are correct choices. Tag is an interface of a simple tag handler that does not want to manipulate its body. The
Tag interface defines the basic protocol between a Tag handler and JSP page implementation class. It defines the life
cycle and the methods to be invoked at start and end tag.

93

There are two main actions: doStartTag and doEndTag. Once all appropriate properties have been initialized, the
doStartTag and doEndTag methods can be invoked on the tag handler. Between these invocations, the tag handler is
assumed to hold a state that must be preserved. After the doEndTag invocation, the tag handler is available for further
invocations (and it is expected to have retained its properties).
The following methods of Tag interface are valid ones out of the choices shown above:
doStartTag()
Process the start tag for this instance.
doEndTag()
Process the end tag for this instance.
--------------------------------------------------------------------

QUESTION NO : 145
QUESTION STATEMENT : The getResource() method of ServletContext interface can be used to access dynamic
resource.
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The ServletContext interface provides direct access to the hierarchy of static content documents that are part of the web
application, including HTML, GIF, and JPEG files, via the following methods of the ServletContext interface:
getResource
getResourceAsStream
The getResource and getResourceAsStream methods take a String with a leading "/" as argument which gives the path
of the resource relative to the root of the context.
These methods are not used to obtain dynamic content. For example, in a container supporting the JavaServer Pages
specification 1, a method call of the form getResource("/index.jsp") would return the JSP source code and not the
processed output. To access dynamic content, RequestDispatcher is used.
--------------------------------------------------------------------

QUESTION NO : 146
QUESTION STATEMENT : Which of the following are valid return types of the doAfterBody() method of the Iteration
Tag interface?
CHOICES :

94
a)
b)
c)
d)
e)
f)

EVAL_BODY_AGAIN
EVAL_BODY_INCLUDE
SKIP_BODY
EVAL_PAGE
SKIP_PAGE
EVAL_BODY_BUFFERED

CORRECT ANSWER : ac
EXPLANATION :
A and C are correct choices. The IterationTag interface extends Tag by defining one additional method that controls the
reevaluation of its body.
A tag handler that implements IterationTag is treated as one that implements Tag regarding the doStartTag() and
doEndTag() methods. IterationTag provides a new method: doAfterBody().
The doAfterBody() method is invoked after every body evaluation to control whether the body will be reevaluated or
not. If doAfterBody() returns IterationTag.EVAL_BODY_AGAIN, then the body will be reevaluated. If doAfterBody()
returns Tag.SKIP_BODY, then the body will be skipped and doEndTag() will be evaluated instead.
--------------------------------------------------------------------

QUESTION NO : 147
QUESTION STATEMENT : Which of the following JSP directives can be used to make the service() method
implementation of a JSP threadsafe?
CHOICES :
a)
b)
c)
d)

<%@ page isThreadSafe="false" %>


<%@ page isThreadSafe="true" %>
<%@ page isSingleThread = "true" %>
<%@ page isSingleThread = "false" %>

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. By default, the service() method of the JSP page implementation class that services the client
request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is
effectively synchronized. There are a couple of different ways to ensure that the service methods are thread-safe. The
easy approach is to include the JSP page directive:
<%@ page isThreadSafe="false" %>
This causes the JSP page implementation class to implement the SingleThreadModel interface, resulting in the
synchronization of the service method, and having multiple instances of the servlet to be loaded in memory.
--------------------------------------------------------------------

95
QUESTION NO : 148
QUESTION STATEMENT :
The three types of JSP directive types are page, include and ___.
CHOICES :
a) ""
CORRECT ANSWER :
taglib
EXPLANATION :
JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class
declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All
directives have scope of the entire JSP file. In other words, a directive affects the whole JSP file, and only that JSP file.
Directives are characterized by the @ character within the tag, and the general syntax is:
<%@ directivename attribute="value" attribute="value" %>
The three directives are as follows:
The page directive
(e.g.<%@ page import="java.net.*" buffer="10k" %>)
The include directive (e.g. <%@ include file="myFile.html" %>)
The taglib directive (e.g. <%@ taglib uri="http://www.whizlabs.com/mytags" prefix="tt" %>)
--------------------------------------------------------------------

QUESTION NO : 149
QUESTION STATEMENT : Using which of the design patterns you ensure a class has only once instance.
CHOICES :
a)
b)
c)
d)
e)

Session Facade
Data Access Object
Value Object
Singleton
Factory

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. Sometimes it is necessary, and it is often sufficient, to create a single instance of a given class.
This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of
instances may be necessary or desirable for technological or business reasons-for example, we may only want a single
instance of a pool of database connections.
A simple approach to this situation is to use static members and methods for the "singleton" functionality. For these
elements, no instance is required. The class can be made final with a private constructor in order to prevent any instance
of the class from being created.

96

None of the other ensures single class instance.


Here is a skeleton code for the Singleton implementation in java:
/**
* A utility class of which at most one instance
* can exist per VM.
*
* Use Singleton.instance() to access this
* instance.
*/
public class Singleton
{
/**
* The constructor could be made private
* to prevent others from instantiating this class.
* But this would also make it impossible to
* create instances of Singleton subclasses.
*/
protected Singleton()
{
// ...
}
/**
* A handle to the unique Singleton instance.
*/
static private Singleton _instance = null;
/**
* @return The unique instance of this class.
*/
static public Singleton instance()
{
if(null == _instance)
{
_instance = new Singleton();
}
return _instance;
}
// ...additional methods omitted...
}
--------------------------------------------------------------------

QUESTION NO : 150
QUESTION STATEMENT : What will be the output on compiling and executing the following JSP?
<HTML>
<BODY>

97
<%! int x; %>
<% int y = 0; %>
<% int z = x+y+1; %>
<%= x+y+z %>
</BODY>
</HTML>
CHOICES :
a)
b)
c)
d)
e)

The code will not compile


Prints : 0
Prints : 1
No output
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice.
The <%! .. %> refers to variable declaration in the above code. Here x is declared and being the instance variable it is
initialized to '0'. The <% .. %> statement is JSP scriptlet, the code written here becomes part of the service() method of
the generated servlet. Thus y becomes the local variable of the service() method with its initial value '0'. Similar to y, z
becomes part of the service() method with its initial value '0+0+1', i.e. 1. The <%= %> refers to the expression. It prints
out the sum of x, y and z. Thus the output of the above code will be printing of "1". Thus C is the correct choice.
--------------------------------------------------------------------

QUESTION NO : 151
QUESTION STATEMENT : A JSP is compiled to a servlet. The scope of the variable i as declared below in a JSP will
be the service() method of the resulted servlet. True/False?
<% int i=0 %>
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
The <% ... %> code is used to insert scriptlets (lines of code in java). The code written inside the scriptlet becomes part
of the service method of the generated servlet. Thus the variable "i" will become the local variable of the generated
servlet. Thus the above statement is true.
--------------------------------------------------------------------

98
QUESTION NO : 152
QUESTION STATEMENT : In a web application, user fills a form for his/her details. The information entered by the
user is taken and stored in a JavaBean, which is used by a JSP.
The first two lines of code for the JSP are as follows:
<jsp:useBean id="userBean" class="myapp.UserBean" scope="request"/>
<jsp:setProperty name="useBean" //XXX />
Which of the following should be placed in the position //XXX, to parse all the form element values to the
corresponding JavaBean property? Assumption : The form input elements have the corresponding variables (with the
same name) in the JavaBean.
CHOICES :
a)
b)
c)
d)
e)

param="*"
param="All"
property="*"
property="All"
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The jsp:setProperty action is used in conjunction with the jsp:useBean action to set the value of
bean properties used by JSP page. The property of the Java Bean can also be set like below:
<jsp:setProperty name="myBean" property="name" value="<%=expression %>" />
When developing beans for processing form data, you can follow a common design pattern by matching the names of
the bean properties with the names of the form input elements. You also need to define the corresponding getter/setter
methods for each property within the bean. The advantage in this is that you can now direct the JSP engine to parse all
the incoming values from the HTML form elements that are part of the request object, then assign them to their
corresponding bean properties with a single statement, like this:
<jsp:setProperty name="user" property="*" />
This runtime magic is possible through a process called introspection, which lets a class expose its properties on
request. The introspection is managed by the JSP engine, and implemented through the Java reflection mechanism. This
feature alone can be a lifesaver when processing complex forms containing a significant number of input elements.
If the names of your bean properties do not match those of the form's input elements, they can still be mapped explicitly
to your property by naming the parameter as:
<jsp:setProperty name="user" property="address" param="parameterName" />
--------------------------------------------------------------------

QUESTION NO : 153
QUESTION STATEMENT :
The getRequestDispatcher() method of the ServletContext interface returns ___ if the ServletContext cannot return a
RequestDispatcher.

99

CHOICES :
a) ""
CORRECT ANSWER :
null
EXPLANATION :
The ServletContext defines a set of methods that a servlet uses to communicate with its servlet container, for example,
to get the MIME type of a file, dispatch requests, or write to a log file.
The getRequestDispatcher() method returns a RequestDispatcher object that acts as a wrapper for the resource located
at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource
in a response. The resource can be dynamic or static.
Here is the signature for getRequestDispatcher() method:
public RequestDispatcher getRequestDispatcher(java.lang.String path)
This method returns null if the ServletContext cannot return a RequestDispatcher.
--------------------------------------------------------------------

QUESTION NO : 154
QUESTION STATEMENT : The SingleThreadModel interface has only two methods listed below.
a.) getInstanceNumber()
b.) setInstanceNumber()
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The simplest way to ensure that a servlet is thread safe is to implement SingleThreadModel interface. This interface
defines no methods and simply serves as a flag to the server. If a servlet implements this interface, the server guarantees
that no more than one thread can execute the service(), doGet(), or doPost() method at a time for a given servlet
instance. Thus the above statement is false.
--------------------------------------------------------------------

QUESTION NO : 155

100
QUESTION STATEMENT : Which of the following are valid DD (Deployment Descriptor) declarations for a <webapp> element of a web application?
CHOICES :
a) <web-app>
</web-app>
b)
<web-app>
<display-name> My Web Application </display-name>
<listener> MyListener </listener>
</web-app>
c)
<web-app>
<display-name> My Web Application </display-name>
<listener>
<listener-class> whizlabs.com.MyListener </listener-class>
</listener>
</web-app>
d) <web-app>
<listener>
<listener-class> whizlabs.com.MyListener </listener-class>
</listener>
<servlet>
<display-name> MyServlet </display-name>
</servlet>
</web-app>
CORRECT ANSWER : ac
EXPLANATION :
A and C are correct choices. The web-app element is the root of the deployment descriptor for a web application. Here
is the DTD for web-app element:
<!ELEMENT web-app (icon?, display-name?, description?,
distributable?, context-param*, servlet*, servlet-mapping*,
session-config?, mime-mapping*, welcome-file-list?, error-page*,
taglib*, resource-ref*, security-constraint*, login-config?,
security-role*, env-entry*, ejb-ref*)>
Please note that "?" indicates optional (none or one occurrence) and "*" indicates none or more (any number)
occurrences. Thus the <web-app> element has no mandatory sub-element. Thus choice A is correct.
The DTD for <listener> element is as follows:
<!ELEMENT listener (listener-class)>
This says that listener element should have one occurrence of listener-class sub-element. Thus choice B is incorrect and
choice C is correct.
The DTD for <servlet> element is as follows:
<!ELEMENT servlet (icon?, servlet-name, display-name?, description?,
(servlet-class|jsp-file), init-param*, load-on-startup?, run-as?, security-role-

101
ref*)>
This says that <servlet-name> is a mandatory sub-element of <servlet> element. Also either of <servlet-class> and <jspfile> is mandatory. Thus choice D is incorrect.
--------------------------------------------------------------------

QUESTION NO : 156
QUESTION STATEMENT : Which of the following JSP codes will compile successfully?
CHOICES :
a) <% int i =5 %>
b) <%= "how" + "are" + "you" %>
c) <% if(true){ %>
<%= 5; %>
<% } %>
d) <% for (int count=0; count<10; count++) { out.println("The value of i is :"+count); } %>
CORRECT ANSWER : bd
EXPLANATION :
Choice B and D are correct.
Following is the syntax for various scripting elements in JSP:
Declarations (e.g.<%! int i=4; %>)
Scriplets
(e.g. <% for (int count=0; count<10; i++) { out.println("The counter is:" + i); } %>)
Expressions (e.g.<%=myBean.getNumber() %>)
A scriptlet is a block of java code that is executed at request-processing time. Choice A is incorrect. The code will not
compile as ';' is missing at the end of the statement. The correct code would be <% int i =5; %>.
An expression (as in choice B) is a shorthand notation for a scripltlet that outputs a value in the response stream back to
the client. When an expression is evaluated, the result is converted to a string and is displayed. If any part of the
expression is an object, the conversion is done by using the toString() method of the object. The ouput of the choice B
would be displaying howare you to the client.
Choice C is incorrect as the statement "<%= 5; %>" will cause compilation error. It should be <%= 5 %> as expression
doesn't end with ';'.
Choice D is correct; it will compile without any problem.
--------------------------------------------------------------------

QUESTION NO : 157
QUESTION STATEMENT : Which of the following are valid Listener Interfaces?
CHOICES :

102
a)
b)
c)
d)
e)
f)

HttpSessionListener
HttpSessionBindingListener
ServletContextSessionListener
HttpSessionAttributeListener
HttpSessionActivationListener
HttpSessionPassivationListener

CORRECT ANSWER : abde


EXPLANATION :
Choice A, B, D and E are correct. There is no HttpSessionPassivationListener. Also note that ServletContext Listener is
a valid one and not ServletContextSessionListener.
Following is the definition of about the valid listeners:
HttpSessionListener : Implementations of this interface may are notified of changes to the list of active sessions in a
web application. To recieve notification events, the implementation class must be configured in the deployment
descriptor for the web application.
HttpSessionBindingListener : Causes an object to be notified when it is bound to or unbound from a session. The object
is notified by an HttpSessionBindingEvent object. This may be as a result of a servlet programmer explicitly unbinding
an attribute from a session, due to a session being invalidated, or die to a session timing out.
ServletContextListener : Implementations of this interface receive notifications about changes to the servlet context of
the web application they are part of. To recieve notification events, the implementation class must be configured in the
deployment descriptor for the web application.
HttpSessionAttributeListener : This listener interface can be implemented in order to get notifications of changes to the
attribute lists of sessions within this web application.
HttpSessionActivationListener : Objects that are bound to a session may listen to container events notifying them that
sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists
sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.
--------------------------------------------------------------------

QUESTION NO : 158
QUESTION STATEMENT : For which of the following authentication mechanisms, having digital certificates installed
is the requirement.
CHOICES :
a)
b)
c)
d)
e)

BASIC
DIGEST
FORM
CLIENT-CERT
None of the above

CORRECT ANSWER : d
EXPLANATION :

103
D is the correct choice. In case of CLIEN-CERT or HTTPS Client Authentication mechanism, the client authenticate
himself/herself via a digital certificate following the SSL protocol. All of the major web browsers and Web servers
support the ability to authenticate to a server via a digital certificate.
--------------------------------------------------------------------

QUESTION NO : 159
QUESTION STATEMENT : Which of the following are default values for the the import attribute of the page directive
of a JSP (when the value of language attribute is java)?
a.) java.lang.*
b.) javax.servlet.*
c.) javax.servlet.http.*
d.) javax.servlet.jsp.*
CHOICES :
a)
b)
c)
d)
e)
f)

Only a
a and c
a and d
a, b and c
only d
all of the above

CORRECT ANSWER : f
EXPLANATION :
F is the correct choice. An import attribute describes the types that are available to the scripting environment. The value
is as in an import declaration in the Java programming language, i.e. a (comma separated) list of either a fully qualified
Java programming language type name denoting that type, or of a package name followed by the ".*" string, denoting
all the public types declared in that package. The import list shall be imported by the translated JSP page
implementation and is thus available to the scripting environment.
The default import list is
java.lang.*,
javax.servlet.*,
javax.servlet.jsp.* and
javax.servlet.http.*.
This value is currently only defined when the value of the language attribute is "java".
Thus F is the correct choice.
--------------------------------------------------------------------

QUESTION NO : 160
QUESTION STATEMENT : Which of the following are mandatory sub-elements of <login-config> element?
CHOICES :

104

a)
b)
c)
d)
e)
f)

<login-name>
<description>
<auth-method>
<realm-name>
<form-login-config>
None of the above

CORRECT ANSWER : f
EXPLANATION :
F is the correct choice. The <login-config> element is used to configure the authentication method that should be used,
the realm name that should be used for this application, and the attributes that are needed by the form login mechanism.
Here is the DTD definition for the login-config element:
<!ELEMENT login-config (auth-method?, realm-name?, form-login-config?)>
This tells that there is no mandatory sub-element for <login-config> element. Thus the choice F is true.
--------------------------------------------------------------------

QUESTION NO : 161
QUESTION STATEMENT : Which of the following is the correct xml statement corresponding to the code given
below for a JSP?
<%= System.currentTimeMillis() %>
CHOICES :
a)
b)
c)
d)
e)
f)

<%@ jsp:expression> System.currentTimeMillis() </jsp:expression>


<jsp:expression> System.currentTimeMillis() </jsp:expression>
<%@ jsp:scriptlet> System.currentTimeMillis() </jsp:scriptlet>
<% jsp:scriptlet> System.currentTimeMillis() </jsp:scriptlet>
<%@ jsp:declaration> System.currentTimeMillis() </jsp:declaration>
<% jsp:declaration> System.currentTimeMillis() </jsp:declaration>

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. A JSP expression is used to insert the value of a scripting language expression into the data
stream and returned to the client. The syntax for jsp expression is as follows:
<%= Java expression %>
A jsp:expression element (xml equivalent of JSP expression) has no attributes and its body is the expression. Its syntax
is:
<jsp:expression>expression goes here </jsp:expression>
Thus B is the correct choice.

105

--------------------------------------------------------------------

QUESTION NO : 162
QUESTION STATEMENT : Match the following JSP implicit objects with the given description/purpose/function?
Implicit Object
1.) out
2.) pageContext
3.) application
4.) session

Description
A.) HttpSession
B.) ServletContext
C.) JspWriter
D.) Object that encapsulates implementation-dependent features and provides convenience methods.

CHOICES :
a) 1.) -> D.)
2.)-> B.)
3.) -> C.)
4.) -> A.)
b) 1.) -> B.)
2.)-> D.)
3.) -> C.)
4.) -> A.)
c) 1.) -> C.)
2.)-> D.)
3.) -> B.)
4.) -> A.)
d) 1.) -> D.)
2.)-> C.)
3.) -> B.)
4.) -> A.)
CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The implicit object "out" is an instance of javax.servlet.jsp.JspWriter, writes into the output
stream. It has "page" scope. The pageContext object is an instance of class javax.servlet.jsp.PageContext that
encapsulates implementation-dependent features and provides convenience methods. A JSP page implementation class
can use a PageContext to run unmodified in any compliant JSP container while taking advantage of implementationspecific improvements like high performance JspWriters .The implicit object "application" is an instance of
javax.servlet.ServletContext, obtained from the servlet configuration object. The getServletContext() method returns the
ServletContext object associated with the invoking PageContext object. It has an "application" scope. The "session"
object is an instance of javax.servlet.http.HttpSession and it represents a user's session created for the requesting client.
It has a "session" scope.
Thus C is the correct choice.
--------------------------------------------------------------------

QUESTION NO : 163
QUESTION STATEMENT :

106
The ___ element describes a URI, relative to the location of the web.xml document, identifying a Tag Library used in
the Web Application. (Just write the element name without any braces. e.g. init-param)
CHOICES :
a) ""
CORRECT ANSWER :
taglib-uri
EXPLANATION :
The taglib-uri element describes a URI, relative to the location of the web.xml document, identifying a Tag Library used
in the Web Application. The DTD for it is as follows:
<!ELEMENT taglib-uri (#PCDATA)>
Also please note that, it is the child element of taglib element, the DTD for which is as follows:
<!ELEMENT taglib (taglib-uri, taglib-location)>

--------------------------------------------------------------------

QUESTION NO : 164
QUESTION STATEMENT : Which of the following lines of code for JSP are correct syntactically?
CHOICES :
a) <%! int i=10; %>
<% if(i>5) {%>
<%= "i>5" %>
<% }else {%>
<%= i<5 %>
<% } %>
b) <% if(true) { %>
out.println("I am fine");
<% } else {%>
out.println("You are fine");
<% } %>
c) <% if(true) %>
I am fine
<% else %>
You are fine
d) <% if(true) { System.out.println("I am fine");} else { System.out.println("You are fine");} %>
e) <%! int i; %>
<% if(i==0) %>
<% i++; %>
<% else %>
<%= "i==1" %>

107

CORRECT ANSWER : abcd


EXPLANATION :
Choice A,B,C and D are correct. The choice A will compile successfully and will print "i>5" on execution. The first
statement in choice A declares and initializes variable "i". The second statement compares the value of i with 5. The
result of this comparison is "true" and thus <%= "i>5" %> will be executed and "i>5" will be printed. Please note that
"{,}" braces are required as the statement <%= "i>5" %> gets converted to 3 statements in the resulting servlet (two of
these statements are output stream related statements required to print "i>5"). Try to execute this code on your web
server and see the resulting servlet code for more details.
Choice E is very similar to choice A but "{,}" braces are missing and thus it will not compile. Thus E is not correct.
Choice B and C are simple conditional statements but please note that choice B will print "out.println("I am fine"); "
and not just "I am fine" unlike choice C.
Also choice D is correct syntactically but note that it will print on the web server console instead of browser window
due to "System.out" statement.
--------------------------------------------------------------------

QUESTION NO : 165
QUESTION STATEMENT : Consider the following HTML form and corresponding servlet
//Hello.html
<html>
<body>
<form method="GET" action="/servlet/PostTest">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
//PostTest.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostTest extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
doPost(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");

108
out.println("<HTML>");
out.println("<HEAD><TITLE> Hello </TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
}
What will be the output on entering "SCWCD" as the name and clicking Submit button of the HTML (Hello.html)
form?
CHOICES :
a)
b)
c)
d)

The servlet will not compile


It will give run time error
Blank html page as an output
Prints : Hello, SCWCD

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. Please note that the Action element of the Html form specifies Get as the HTTP method. But
also note that its always the service() method which is first called and then based on the type of request (GET/POST),
the corresponding doXXX method is called. In the above case on submission, the service() method of the servlet will be
called. And since we have overridden it and it explicitly call the doPost() method. Thus doPost() method will be called
and "Hello, SCWCD" will be printed.
--------------------------------------------------------------------

QUESTION NO : 166
QUESTION STATEMENT : Which of the following are valid DD (Deployment Descriptor) declarations for a <webapp> element of a web application?
CHOICES :
a) <servlet>
</servlet>
b) <servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class> java.sun.com.MyServlet </servlet-class>
</servlet>
c) <servlet>
<init-param>
<param-name> age </param-name>
<param-value> 25 </param-value>
</init-param>
<init-param>
<param-name> score </param-name>
<param-value> 98 </param-value>
</init-param>

109

</servlet>
d) <servlet>
<servlet-name> MyServlet </servlet-name>
<description> It's My Servlet </description>
<servlet-class> java.sun.com.MyServlet </servlet-class>
<init-param>
<param-name> age </param-name>
<param-value> 25 </param-value>
<description> It's My Parameter </description>
</init-param>
</servlet>
CORRECT ANSWER : bd
EXPLANATION :
B and D are correct. The DTD for <servlet> element is as follows:
<!ELEMENT servlet (icon?, servlet-name, display-name?, description?,
(servlet-class|jsp-file), init-param*, load-on-startup?, run-as?, security-roleref*)>
This says that <servlet-name> is a mandatory sub-element of <servlet> element. Also either of <servlet-class> and <jspfile> is mandatory.
Thus choice B is correct and choice A, C are incorrect.
The DTD for <init-param> element is as follows:
<!ELEMENT initialize-param (param-name, param-value, description?)>
It says that <param-name> and <param-value> are mandatory sub-elements of <init-param> element.
Thus choice D is also correct.
--------------------------------------------------------------------

QUESTION NO : 167
QUESTION STATEMENT : Which of the following are mandatory sub-elements of <servlet-mapping> element?
CHOICES :
a)
b)
c)
d)
e)
f)

<servlet-name>
<servlet-class>
<url-map>
<url-mapping>
<url-pattern>
<description>

CORRECT ANSWER : ae
EXPLANATION :

110
Choice A and E are correct. The servlet-mapping element defines a mapping between a servlet and a url pattern. The
DTD for servlet-mapping is follows:
<!ELEMENT servlet-mapping (servlet-name, url-pattern)>
Thus <servlet-name> and <url-pattern> are the mandatory sub-elements of the <servlet-mapping> element. Thus choice
A and E are true.
--------------------------------------------------------------------

QUESTION NO : 168
QUESTION STATEMENT : The sendError() method(s) of HttpServletResponse should be invoked before the response
is committed. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
The above statement is true. The "sendError" method of the HttpServletResponse interface will set the appropriate
headers and content body for an error message to return to the client. These methods (there are two overloaded
methods) return an error message to the client according to the status code.
Here are the overloaded sendError() methods:
sendError(int): Sends an error response to the client using the specified status code and clearing the buffer.
sendError(int, String): Sends an error response to the client using the specified status clearing the buffer.
If the response has already been committed, both of these methods throws an IllegalStateException. Only after using
these methods, the response should be considered to be committed.
--------------------------------------------------------------------

QUESTION NO : 169
QUESTION STATEMENT : Which of the following use of <jsp:useBean> tag for a JSP which uses
java.sun.com.MyBean JavaBean component are correct?
CHOICES :
a) <jsp:useBean id = "java.sun.com.MyBean" scope="page" />
b) <jsp:useBean id = "MyBean" class="java.sun.com.MyBean" />
c) <jsp:useBean id = "MyBean" type = "java.lang.String" scope="page" />
d) <jsp:useBean id = "MyBean" beanName="java.sun.com.MyBean" scope="page" />
e) <jsp:useBean id = "MyBean" beanName="java.sun.com.MyBean" className="MyBean" type = "java.lang.String"
scope="page" />

111

CORRECT ANSWER : bc
EXPLANATION :
Choice B and C are correct. A jsp:useBean action associates an instance of a Java programming language object defined
within a given scope and available with a given id with a newly declared scripting variable of the same id .
Following is the syntax of the jsp:useBean action:
<jsp:useBean id="name" scope="page|request|session|application" beandetails />
where beandetails can be one of:
class="className"
class="className" type="typeName"
beanName="beanName" type="typeName"
type="typeName"
Following is the description of various attributes:
a.) id - The case sensitive name used to identify the object instance.
b.) scope - The scope within which the reference is available. The default value is page.
c.) class - The fully qualified (including package name) class name.
d.) beanName - The name of a Bean, as you would supply to instantiate() method in the java.beans.Beans class. This
attribute can also be a request time expression.
e.) type - This optional attribute specifies the type of the class, and follows standard java casting rules. The type must be
a superclass, an interface, or the class itself. The default value is the same as the value of the class attribute.
From the rules above, we can say:
either of class and type must be present. Thus A is incorrect and B, C are correct.
beanName if present must be accompanied by type. Thus D is incorrect.
both beanName and class can't be present. Thus E is also incorrect.
--------------------------------------------------------------------

QUESTION NO : 170
QUESTION STATEMENT :
The setContentType() method belongs to ____ interface. (Parent interface, not inherited ones)
CHOICES :
a) ""
CORRECT ANSWER :
ServletResponse
EXPLANATION :
The setContentType() method belongs to ServletResponse interface. Here is the signature with brief about this method:

112

public void setContentType(java.lang.String type)


Sets the content type of the response being sent to the client. The content type may include the type of character
encoding used, for example, text/html; charset=ISO-8859-4.
--------------------------------------------------------------------

QUESTION NO : 171
QUESTION STATEMENT : Which of the following are valid sub-elements for <exception-type> element used in DD
(web.xml file) of a web application?
CHOICES :
a)
b)
c)
d)
e)
f)

<error-page>
<error-code>
<exception-name>
<error-type>
All of the above
None of the above

CORRECT ANSWER : f
EXPLANATION :
F is the correct choice. The exception type contains a fully qualified class name of a Java exception type. The DTD for
<exception-type> is as follows:
<!ELEMENT exception-type (#PCDATA)>
Thus there is no <sub-element> for <exception-type> element. Thus F is the correct choice.
--------------------------------------------------------------------

QUESTION NO : 172
QUESTION STATEMENT : A website is developed using JSP's and Servlets. Every page of the site needs to have
copyright statement at the bottom of the page. Considering the code below (TestPage.jsp and copyright.html), choose
the valid options to be used at //XXX position to include the copyright statement as the last statement of the JSP page.
// TestPage.jsp
<HTML>
<HEAD>
<TITLE> My Test Page </TITLE>
</HEAD>
<BODY>
// lot of html code describing my page

113
//XXX
</BODY>
</HTML>
//copyright.html
<HTML>
<BODY>
Copyright XYZ Pvt Ltd.
</BODY>
</HTML>
CHOICES :
a) <jsp:include file="copyright.html" >
</jsp:include>
b) <% include file="copyright.html" flush="false" %>
c) <%@ include file="copyright.html" flush="true" %>
d) <jsp:include page="copyright.html" flush="true" />
e) None of the above
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The include directive notifies the web container/server to include the content of the resource in
the current JSP, inline, at the specified place. Here is the syntax for that:
<%@ include file="Filename" %>
The jsp:include action allows a static or dynamic resource to be included in the current JSP at request time. The
resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />
--------------------------------------------------------------------

QUESTION NO : 173
QUESTION STATEMENT : Consider the Servlet and JSP code below. Which of the given choices (when placed at
//XXX position) will achieve the functionality described below?
On inoking the Servlet as http://localhost:8080/servlet/AskMeServlet?exam=SCWCD, "Yes, its easier than SCJP!"
should be printed. Assume that the JSP and Servlet are placed in their respective directories on the web server.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AskMeServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{

114
res.setContentType("text/html");
//XXX
}
}
// Answer.jsp
<html>
<body>
Yes, its easier than SCJP!
</body>
</html>
CHOICES :
a) if(req.getParameter("exam").equals("SCWCD"))
{
res.sendRedirect("../Answer.jsp");
}
b) if(req.getParameter("exam").equals("SCWCD"))
{
res.forward("../Answer.jsp");
}
c) if(req.getParameter("exam").equals("SCWCD"))
{
res.Redirect("../Answer.jsp");
}
d) if(req.getParameter("exam").equals("SCWCD"))
{
req.Redirect("../Answer.jsp");
}
e) if(req.getParameter("exam").equals("SCWCD"))
{
req.forward("../Answer.jsp");
}
f) if(req.getParameter(exam).equals("SCWCD"))
{
req.sendRedirect("../Answer.jsp");
}
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. In the above code, when the AskMeServlet is invoked as
http://localhost:8080/servlet/AskMeServlet?exam=SCWCD, the doGet() method will be called. Here we are passing
SCWCD value to the "exam" variable of the query string "?exam=SCWCD" of the servlet. The HttpServletRequest
interface provides getParameter() methods to extract the value of the variables passed to the query string. Thus
"if(req.getParameter("exam").equals("SCWCD"))" will return true.
Now what is required is to redirect the response to the Answer JSP. The HttpServletResponse interface provides the
sendRedirect() method (sendRedirect(java.lang.String location) ) which sends a temporary redirect response to the
client using the specified redirect location URL (in the above case it is ../Answer.jsp).
Thus choice A is correct. Choice B and E are incorrect as there is no forward() method in the
HttpServletResponse/HttpServletRequest interface. Choice C and D are incorrect as there is no Redirect() method in the
HttpServletResponse/HttpServletRequest interface. Choice F is incorrect as

115
"if(req.getParameter(exam).equals("SCWCD"))" statement will give compilation error; getParameter("exam") should
be used instead of getParameter(exam).
--------------------------------------------------------------------

QUESTION NO : 174
QUESTION STATEMENT : If your class extends GenericServlet class then it must implement service() method unless
its abstract.
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
GenericServlet has an abstract service (ServletRequest, ServletResponse) method. Thus if your servlet extends
GenericServlet, it must implement service() method if its concrete(non-abstract).
Note that HttpServlet extends GenericServlet and provides the extra functionality of doXXX methods.
--------------------------------------------------------------------

QUESTION NO : 175
QUESTION STATEMENT : Considering the custom tags below, choose the correct statements.
1.) <t:test/>
2.) <t:test> </t:test>
3.) <t:test name="scwcd" />
4.) <t:test>
<font color=red>
It's My Tag!!
</font>
</t:test>
5.) <t:test>
<t:test1> testing </t:test1>
</t:test>
CHOICES :
a)
b)
c)
d)
e)
f)

1.) is incorrect syntactically


2.) is an example of tag with body
3.) is an example of tag with attribute
4.) is an example of tag with attribute
4.) is an example of tag with non-empty body
5.) is an example of nested tags

116
CORRECT ANSWER : cef
EXPLANATION :
Choice C, E and F are correct. The tag at 1.) is correct and is an example of empty tag. Thus choice A is incorrect. The
custom tag at 2.) is also an example of empty tag. Thus Choice B is also incorrect. The tag at 3.) is an example of
custom with attribute (name is an attribute with scwcd as attribute value). Thus choice C is correct. The tag at 4.) is a
non-empty tag; tag with body consisting of HTML tags. The tag has no attribute. Thus choice D is incorrect and E is
correct. The tag at 5.) is an example of nested tag (test is the parent of test1 tag). Thus choice F is also correct.
--------------------------------------------------------------------

QUESTION NO : 176
QUESTION STATEMENT :
ServletContext interface and ____ class provides log methods to write a message to the WebApp log.
CHOICES :
a) ""
CORRECT ANSWER :
GenericServlet
EXPLANATION :
ServletContext interface and "GenericServlet" class provides log methods to write a message to the WebApp log.
GenericServlet class implements the log() methods provided by the ServletContext interface.
Here are the log methods with brief description of GenericServlet class:
A.) public void log(java.lang.String msg): Writes the specified message to a servlet log file, prepended by the servlet's
name.
Parameters:
msg - a String specifying the message to be written to the log file
B.) public void log(java.lang.String message, java.lang.Throwable t): Writes an explanatory message and a stack trace
for a given Throwable exception to the servlet log file, prepended by the servlet's name. See log(String, Throwable) .
Parameters:
message - a String that describes the error or exception
t - the java.lang.Throwable error or exception
--------------------------------------------------------------------

QUESTION NO : 177
QUESTION STATEMENT :
When a JSP custom tag implements IterationTag, on the completion of the body of the tag, ____ is invoked. (Write only
the method name, without braces. e.g. myMethod and not myMethod())

117

CHOICES :
a) ""
CORRECT ANSWER :
doAfterBody
EXPLANATION :
The IterationTag interface is used to repeatedly reevaluate the body of a custom action. The interface has one method:
doAfterBody() which is invoked after each evaluation of the body to determine whether to reevaluate or not.
Reevaluation is requested with the value 2, which in JSP 1.1 is defined to be BodyTag.EVAL_BODY_TAG. That
constant value is still kept in JSP 1.2 (for full backwards compatibility) but, to improve clarity, a new name is also
available: IterationTag.EVAL_BODY_AGAIN. To stop iterating, the returned value should be 0, which is
Tag.SKIP_BODY.
--------------------------------------------------------------------

QUESTION NO : 178
QUESTION STATEMENT : Consider the following code
//SimpleServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleServlet extends GenericServlet
{
public void init(ServletConfig cfg) throws ServletException
{
super.init(cfg);
System.out.println("I'm in Init method");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("I'm in Service method");
System.out.println("I'm in service method");
}
public void destroy()
{
System.out.println("i'm in destroy method");
}
}

118

Let us assume thet JavaWebServer is started up in a console window, and SimpleServlet is in the registered servlet
directory of JavaWebServer. What is the expected output on the server console window when the SimpleServlet is
accessed repeatedly?
CHOICES :
a)
I'm in Init method
I'm in service method
I'm in destroy method
This output repeats five times
b)
The first time the servlet is accessed. the following is output I'm in Init method
I'm in service method
I'm in destroy method
after that, for each subsequent servlet access, the following is output I'm in service method
I'm in destroy method
c)
The first time the servlet is accessed. the following is output I'm in Init method
I'm in service method
after that, for each subsequent servlet access, the following is output I'm in service method
d)
The first time the servlet is accessed. the following is output I'm in Init method
I'm in service method
after that, for each subsequent servlet access, the following is output I'm in service method
After a large number of requests, say a 100, or more, the following is output I'm in service method
I'm in destroy method
and after that, the following is output until say another 100 requests have been made I'm in service method

CORRECT ANSWER : c
EXPLANATION :

119
C is the correct choice. The init() method is invoked only the very first time the servlet is loaded into memory.
Following that, whenever the servlet is accessed (a request is made to it), its service() method is invoked. Depending
upon the web server, the destroy() method is invoked if the sevlet is not accessed at all for a specified time period, or
only when the server is shut down. Basically, the destroy() method is invoked right before the servlet is removed from
memory.
--------------------------------------------------------------------

QUESTION NO : 179
QUESTION STATEMENT : What will be output when the following JSP is compiled and executed?
<html>
<body bgcolor="#FFFFFF">
<%! int i; %>
The value of i is: <%= i ;%>
</body>
</html>
CHOICES :
a)
b)
c)
d)

It will print: "The value of i is: 0"


It will give compilation error.
It will give run time error saying : "the variable i must have been initialized.
None of the above.

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. Please note that the expressions (<%= ... %>) in JSP doesn't ends with semicolons. Thus a
compile time error will be given. Thus choice B is correct and other choices are incorrect.
--------------------------------------------------------------------

QUESTION NO : 180
QUESTION STATEMENT : A JSP Custom tag can contain which of the following?
CHOICES :
a)
b)
c)
d)
e)

Custom Tag
Core JSP Tag
Scripting element
HTML text
Tag dependent body just before the start tag.

CORRECT ANSWER : abcd

120

EXPLANATION :
Choice A, B, C and D are correct. A JSP custom tag can contain another custom tag. The tags of this type are called
nested tags. Here is an example:
<tt:outerTag>
<tt:innerTag />
</tt:outerTag>
It can also contain a core JSP tag like <jsp:getProperty>. A custom tag can also define a scripting variable that can be
used in scripts within a page. Below is an example of such a custom tag tt:myTag):
<tt:myTag id="count" name="count" type="myCart.Count" />
A custom tag can also contain HTML text as shown below:
<test:MyTag>
<font color=red>
It's My Tag!!
</font>
</test:MyTag>
A custom tag may optionally have tag-dependent body content between the start tag and the end tag. Please note that
body is between the start and the end tag. Thus choice E is incorrect. The content between the start tag and the end tag
is body. In fact the tag shown above using the HTML text is also an example of the tag with the body.
--------------------------------------------------------------------

QUESTION NO : 181
QUESTION STATEMENT : What does HTTP status code 301 signifies in regard to HTTP redirect response?
CHOICES :
a)
b)
c)
d)
e)

Redirected Successfuly
Redirection failure
Moved Temporarily
Moved Permanently
None of these

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. Redirect is an HTTP response from the server instructing the client to request a resource at a
different URL. There are two key elements in the header of an HTTP response that convey a redirect to the client. These
elements are the HTTP status code and the Location header. The HTTP status code 301 indicates Moved Permanently
while 302 indicates Moved Temporarily.

--------------------------------------------------------------------

121

QUESTION NO : 182
QUESTION STATEMENT : If you want to apply MVC (Model View Controller) design pattern on a web application,
which of the following will be the role most suited for a JSP (Java Server Page).
CHOICES :
a)
b)
c)
d)

Model
View
Controller
None of the above

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. In a web application, designed with MVC pattern, the backend data (in the database or the
Entity EJB) will best provide the "model", the business logic written in the servlet will be "controller" and the JSP will
be most suited to play the role of "view". The servlet takes the request from the client (browser), instantiates/creates the
JavaBean/EJB and forwards the request to the JSP. Finally JSP, which represents the "view", sends back the response to
the client.

--------------------------------------------------------------------

QUESTION NO : 183
QUESTION STATEMENT : Which of the following are true regarding the following jsp element?
<jsp:useBean id="myBean" class="mybox.MyBean" scope="session"/>
CHOICES :
a)
b)
c)
d)

It creates an instance of MyBox class if none exists.


It doesn't creates an instance of MyBox class if none exists and will give compilation error.
It stores the instance as an attribute of the session object.
It also makes the bean available throughout the application by the name myBean.

CORRECT ANSWER : ac
EXPLANATION :
A and C are correct. In case the instance of the bean declared in the jsp element as above doesn't exist, it will be created.
Thus A is correct and B is incorrect. As the scope of the bean is declared to be session, the instance will be stored as a
session attribute and will be available for the particular session and not throughout the application. Thus C is correct
and D is incorrect.
--------------------------------------------------------------------

QUESTION NO : 184

122
QUESTION STATEMENT : HTTP Digest Authentication mechanism is more secure than HTTP Basic mechanism.
True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
HTTP Basic Authentication, which is based on a username and password, is the authentication mechanism defined in
the HTTP/1.0 specification. In case of Basic Authentication, the server prompts user for login/password, the
combination of which is used for the purpose of authentication. Basic Authentication is not a secure authentication
protocol. User passwords are sent in simple base64 encoding. Like HTTP Basic Authentication, HTTP Digest
Authentication authenticates a user based on a username and a password. However the authentication is performed by
transmitting the password in an encrypted form which is much more secure than the simple base64 encoding used by
Basic Authentication.
--------------------------------------------------------------------

QUESTION NO : 185
QUESTION STATEMENT : Which of the following statements regarding GET and POST methods are true?
CHOICES :
a)
b)
c)
d)

GET is the method commonly used to request a resource from the server.
POST is the method commonly used to request a resource from the server.
GET is the method commonly used for passing user input to the server.
POST is the method commonly used for passing user input to the server.

CORRECT ANSWER : ad
EXPLANATION :
A and D are correct. The Get is the most common HTTP method used to request a resource (e.g. an html page) from the
HTTP server (or Web server). POST is an HTTP method commonly used for passing user input (e.g. HTML form data)
to the HTTP server (or Web server).
--------------------------------------------------------------------

QUESTION NO : 186
QUESTION STATEMENT : The below deployment descriptor definition for an error-page element to be used in a web
application is correct?
<web-app>
...
<error-page>
<error-type>java.lang.NumberFormatException</error-code>

123
<error-code>400</error-code>
<location>/Error.html</location>
</error-page>
</web-app>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The error-page element contains a mapping between an error code or exception type to the path of a resource in the web
application. Here is the DTD definition for the error-page element:
<!ELEMENT error-page ((error-code | exception-type), location)>
The error-code contains an HTTP error code, ex: 404. The exception type contains a fully qualified class name of a Java
exception type. The location element contains the location of the resource in the web application.
According to the above DTD definition, the error-page tag must contain either of the error-code or exception-type and
location. It cannot contain both the error-code and error-type. Thus the above definition is incorrect.
--------------------------------------------------------------------

QUESTION NO : 187
QUESTION STATEMENT :
The object implementing the ___ interface is notified when it is bound to or unbound from a session. (Write only the
interface name)
CHOICES :
a) ""
CORRECT ANSWER :
HttpSessionBindingListener
EXPLANATION :
The object implementing the ___ interface is notified when it is bound to or unbound from a session. The object is
notified by an HttpSessionBindingEvent object. This may be as a result of a servlet programmer explicitly unbinding an
attribute from a session, due to a session being invalidated, or die to a session timing out.
--------------------------------------------------------------------

124
QUESTION NO : 188
QUESTION STATEMENT : Which of the following are the methods for state/session management in the context of
Servlets?
CHOICES :
a)
b)
c)
d)
e)

Rewritten URLs
Hidden Variables
Cookies
HTTP Redirects
Using HttpSession Interface

CORRECT ANSWER : abce


EXPLANATION :
A, B, C and E are correct choices. State management is the ability to maintain client's current state by passing clientspecific information between the client and the server. In contrast, session management provides an association between
the client and the server that allows server to uniquely identify each client. This association persists across the requests
for a specified period of time. Allowing clients to select their background color of an their html page is an example of
state management. With state management, the client identity can't be maintained. For e.g., two clients select red as
their background color. With only state management, the server can determine the preferred background color for each
of these clients but it cannot distinguish one client from the other. The solution to this is the session management, which
is the superset of state management and maintains both state as well as identity. Rewritten URLs pass state information
between the client and server by embedding information in the URL of all hyperlinks within an HTML document. The
information is passed in the query string of a URL in the form of name/value pairs. For e.g.
http://www.whizlabs.com/servlets/SampleServlet?bcolor=blue
This method is only effective when the client follows a hyperlink. If a client needs to submit an HTML Form by
clicking a button, the Hidden Variables method is used. A hidden variable operates like an HTML input field (e.g., text
field) in that when the page is submitted, the client transmits the field's name/value pair to the server. On receiving the
client's POST request, the server extracts the value of the variable (using getParameter() or getParameterValues()
method of HttpServletRequest interface) and uses it to construct the next HTML document/page. Generally the
combination of both rewritten URLs and hidden variables is used to maintain state and session with HTTP.
Cookie is a simple mechanism that allows the server to instruct the client to store some amount of state information. In
turn, this information is returned to the server with each client request.
The session management mechanism in the Servlet API resides in the HttpSession interface. An HttpSession object
encapsulates the essential information of an HTTP session, such as a unique session ID and other client-specific
information.
An HTTP redirect allows the server to respond to a client request with instructions to load a resource at a different
location. It is not a mechanism for state/session management. Thus A,B,C and E are correct while D is incorrect.
--------------------------------------------------------------------

QUESTION NO : 189
QUESTION STATEMENT : Implementations of the request and response objects are guaranteed to be thread safe.
True/False?
CHOICES :

125

a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
Implementation of the request and response objects are "not guaranteed" to be thread safe. They should only be used
within the scope of the request handling thread.
References to the request and response objects must not be given to objects executing in other threads as the resulting
behaviour may be non-deterministic.
--------------------------------------------------------------------

QUESTION NO : 190
QUESTION STATEMENT : Which of the following are true regarding destroy() method of the HttpServlet?
CHOICES :
a)
b)
c)
d)

This method is called by the Web server.


It is called immediately after the servlet is unloaded.
It is used in order to free up any resources being used by the servlet.
It is one of the life cycle methods of HTTP Servlet.

CORRECT ANSWER : acd


EXPLANATION :
A,C and D are correct. A is correct as destroy() is called by the Web server/servlet container. B is incorrect as destroy is
callled immediately before and not after the servlet is unloaded. C is correct as destroy() method like the destory
method of an applet is used to free up any resources being used by the servlet. D is correct as destroy() like init(),
service() is one of the lifecycle methods of HTTP Servlet.

--------------------------------------------------------------------

QUESTION NO : 191
QUESTION STATEMENT : Web components to a J2EE application are added in a package called WAR (web
application archive). A WAR has a specific hierarchical directory structure and the top-level directory is called the
document root of the application. The document root is named as WEB-INF. True/False?
CHOICES :
a) True
b) False

126
CORRECT ANSWER : b
EXPLANATION :
The document root is where JSP pages, client side classes and archives, and static web resources are stored. The
document root contains a subdirectory called WEB-INF, which contains other files and directories such as web
application deployment descriptor file, tag lib descriptor files, classes and lib directories. Thus WEB-INF is not the
document root but a sub-directory of the document root. Thus the above statement is false.
--------------------------------------------------------------------

QUESTION NO : 192
QUESTION STATEMENT : What will be output when the following JSP (MyJSP.jsp) is compiled and executed? The
content of the files referenced by this file is also shown below.
//MyJSP.jsp ...
<html>
<body bgcolor="#FFFFFF">
<%@ include file="imfine.jsp" %>
<%@ include file="thankyou.html" %>
</body>
</html>
//imfine.jsp ...
<html>
<body bgcolor="#FFFFFF">
I am fine.
</body>
</html>
//thankyou.html ...
<html>
<body bgcolor="#FFFFFF">
Thankyou!
</body>
</html>
CHOICES :
a)
b)
c)
d)
e)

It will give a blank html page as an output.


It will give compile time error.
It will give run time error.
It will print : "I am fine. Thankyou!"
None of the above.

127

CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The include directive (<%@ include file="filename" %>) notifies the web server to include the
content of the resource in the current JSP, inline at the specified place. Thus first include directive will place the content
of imfine.jsp page and then the content of thankyou.html file will be inlined. Thus as a result "I am fine. Thankyou!"
will be printed out. Thus choice D is correct.
--------------------------------------------------------------------

QUESTION NO : 193
QUESTION STATEMENT : Using rewritten URLs and hidden variables over Cookie mechanism for state and session
management is both advantageous and disadvantageous. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
The primary advantage of rewritten URLs and hidden variables state/session management mechanism is that virtually
all browsers support both rewritten URLs and hidden variables. While cookie mechanism is not supported by all
browsers. The disadvantage to this method is the amount of processing required on the server in order to implement
rewritten URLs and hidden variables. The server needs to parse every HTML page it serves, adding state information to
hyperlink URLs and adding hidden variables to all HTML forms.
--------------------------------------------------------------------

QUESTION NO : 194
QUESTION STATEMENT : A custom tag can have attributes. An attribute value can be set from a "runtime
expression". True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes, the value of attributes used in a JSP Custom Tag can be set from a String constant or a runtime expression, whose
type is a compound Java programming language type. A runtime expression simply returns its value; no automatic
conversion is performed. As a consequence, the type returned by from an expression must match or be castable to the

128
type of the attribute, which is specified in the object that implements the tag. Here is an example of a custom tag
(tt:myCart) that uses a runtime expression to set the value of the "counter" attribute.
<tt:myCart counter="<%=myCart.getCounter() %>" type="cart.MyCounter">
--------------------------------------------------------------------

QUESTION NO : 195
QUESTION STATEMENT : To which methods of the HTTPServlet class, does the HTTP POST and HEAD requests
associated?
CHOICES :
a)
b)
c)
d)
e)

post() and head()


doPost() and doHead()
setPost() and setHead()
getPost() and setHead()
HEAD is not an HTTP request

CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. The doPost() method is called whenever an HTTP POST request is received by the servlet. It is
most commonly used to process information collected from an HTML form. The doHead() method is called in response
to an HTTP HEAD request. A HEAD request is identical to a GET request except that only HTTP headers are returnedthe body content is excluded. There are no method like post(), setPost(), getPost() in HTTPServlet class. Thus B is the
correct choice and all other choices are incorrect.
--------------------------------------------------------------------

QUESTION NO : 196
QUESTION STATEMENT :
When the start tag of a simple custom tag is encountered, the JSP page's servlet invokes the handler's ____ method.
(Write only the method name, without braces. e.g. myMethod and not myMethod())
CHOICES :
a) ""
CORRECT ANSWER :
doStartTag
EXPLANATION :
On encountering the start tag of a simple custom tag (no body and attributes), the JSP page's servlet first calls methods
to initialize the appropriate handler and then invokes the handler's doStartTag() method.

129

--------------------------------------------------------------------

QUESTION NO : 197
QUESTION STATEMENT :
The ____ element indicates the deployment properties for a web application listener object. (Just write the element
name without any braces. e.g. init-param)
Hint (The DTD definition) : <!ELEMENT ___ (listener-class)>
CHOICES :
a) ""
CORRECT ANSWER :
listener
EXPLANATION :
The "listener" element indicates the deployment properties for a web application listener object. The listener-class
element declares a class in the application must be registered as a web application listener bean. The value is the fully
qualified class name of the listener class. Here is an example of the DD file of a web application:
<web-app>
...
<listener>
<listener-class>whizlabs.com.SCWCDListner</listener-class>
</listener>
...
</web-app>

--------------------------------------------------------------------

QUESTION NO : 198
QUESTION STATEMENT : The method getSession() belongs to which of the following?
CHOICES :
a)
b)
c)
d)

HttpServletRequest interface
HttpServletResponse interface
HttpSession interface
HttpSessionContext interface

CORRECT ANSWER : a
EXPLANATION :

130
A is the correct choice. The getSession() method belongs to the HttpServletRequest interface. The method signature and
brief description is as follows:
public abstract HttpSession getSession(boolean create)
Gets the current valid session associated with this request, if create is false or, if necessary, creates a new session for the
request, if create is true.
Please note that the above method also belong to the HttpServletResponseWrapper class (in javax.servlet.http
package). This class provides a convenient implementation of the HttpServletResponse interface that can be subclassed
by developers wishing to adapt the response from a Servlet.
--------------------------------------------------------------------

QUESTION NO : 199
QUESTION STATEMENT : The use of synchronization blocks of code to prevent "race condition" in java servlets
often creates a performance bottleneck. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
A race condition occurs when the proper behaviour of the program relies on one thread completing execution before
another. This timing requirement can result in inconsistent behaviour since there is usually no guarantee that one thread
will finish before another.
To prevent race condition the concept of synchronization is used. It allows the servlet engine to call the service(),
doGet(), doPost() method without having to wait for all prior executions of these methods to finish. To achieve this, one
can synchronize a block of code or even synchronize the entire service() method. In this way, only one thread at a time
can execute the method.
However, this approach often incurs a large performance penalty. Synchronized blocks of code create a performance
bottleneck since all other threads to "wait in line" for the current thread to complete its execution of synchronized code.
The more code that is synchronized, the greater the performance penalty. To avoid this penalty, minimize the amount of
code that is synchronized by using the "synchronized(this)" technique.
--------------------------------------------------------------------

QUESTION NO : 200
QUESTION STATEMENT : Which of the following is the correct definition of <body-content> sub-element of the
<tag> element of a Tag, which has no body?
CHOICES :
a) <body-content> empty </body-content>

131
b) <body-content>
</body-content>
c) <body-content> "" </body-content>
d) <body-content> none </body-content>
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. A tag with no body will have <body-content> empty </body-content> sub-element.
--------------------------------------------------------------------

QUESTION NO : 201
QUESTION STATEMENT :
_____ is the default HTTP method used for accessing URLs.
CHOICES :
a) ""
CORRECT ANSWER :
GET
EXPLANATION :
GET is the default HTTP method used for accessing URLs, i.e, by default, the doGet() method of an HTTP servlet will
be invoked. It is the most coommon HTTP method. It is used to request a resource from the server, Containing no body
content,a Get request is comprised of only a method statement and various request header fields.
--------------------------------------------------------------------

QUESTION NO : 202
QUESTION STATEMENT :
Every time a request comes to the JSP, the container generated ____ method is invoked, the request is processed, and
the JSP generates the appropriate response. (Write only the method name without any braces e.g. myMethod and not
myMethod())
CHOICES :
a) ""
CORRECT ANSWER :
_jspService
EXPLANATION :

132
The JSP specification defines the contract between the JSP container and the JSP page author. This contract defines the
assumptions an author can make for the actions described in the JSP page. The main portion of this contract is the
_jspService() method that is generated automatically by the JSP container from the JSP page.
Every time a request comes to the JSP, the container generated ____ method is invoked, the request is processed, and
the JSP generates the appropriate response. This response is taken by the container and passed back to the client.
--------------------------------------------------------------------

QUESTION NO : 203
QUESTION STATEMENT :
The ___ element declared in the DD (Deployment Descriptor) of a web application contains the canonical name of the
servlet. (Just write the element name without any braces. e.g. init-param)
CHOICES :
a) ""
CORRECT ANSWER :
servlet-name
EXPLANATION :
The servlet-name element contains the canonical name of the servlet. Each servlet name is unique within the web
application. Here is the DTD declaration for servlet-name element:
<!ELEMENT servlet-name (#PCDATA) >
--------------------------------------------------------------------

QUESTION NO : 204
QUESTION STATEMENT :
The ___ interface is used by the container to notify the objects bound to a session, that the session will be activated.
CHOICES :
a) ""
CORRECT ANSWER :
HttpSessionActivationListener
EXPLANATION :
HttpSessionActivationListener interface is used by the container to notify the objects bound to a session, that the
session will be activated and also when the session is about to be passivated. It does this using the following methods:

133
sessionDidActivate(HttpSessionEvent) : public void sessionDidActivate(HttpSessionEvent se)
Notification that the session has just been activated.
sessionWillPassivate(HttpSessionEvent) :public void sessionWillPassivate(HttpSessionEvent se)
Notification that the session is about to be passivated.
--------------------------------------------------------------------

QUESTION NO : 205
QUESTION STATEMENT : For tags that have body, the type of the body content needs to be specified. Body content
containing custom and core tags, scripting elements, and HTML text is categorized as which of the following types?
CHOICES :
a)
b)
c)
d)

JSP
tagdependent
Any of the above.
None of the above.

CORRECT ANSWER : a
EXPLANATION :
For tags with body, the syntax of body content element is as follows:
<body-content> JSP|tagdependent </body-content>
The body content containing custom and core tags, scripting elements, and HTML text is categorized as JSP while all
other types of body content, for e.g. SQL statements passed to the query tag, would be labeled tagdependent. Also
please note that the value of body-content element doesn't affect the interpretation of the body by the tag handler; the
element is only intended to be used by an authoring tool for rendering the body content.

--------------------------------------------------------------------

QUESTION NO : 206
QUESTION STATEMENT :
The ____ object allows you to forward requests to or include output from other server resources. (write class name)
CHOICES :
a) ""
CORRECT ANSWER :
RequestDispatcher

134

EXPLANATION :
With 2.1 version of Servlet API, the RequestDispatcher object allows to programatically forward requests to and
include context from other server resources. This is the purpose of RequestDispactcher object, which includes two
methods - forward() and include().
--------------------------------------------------------------------

QUESTION NO : 207
QUESTION STATEMENT : A secure web application needs to declare the security policy in their deployment
descriptor file. The one of the elements of the deployment descriptor file is <role-name>.
The <role-name> element is the subelement of which of the following elements?
CHOICES :
a)
b)
c)
d)

<auth-constraint>
<login-config>
<url-pattern>
<role>

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. To specify which roles a user must be in before he is allowed to access a resource, the <rolename> tag is used. The <role-name> element is nested in <auth-constraint> element. The <auth-constraint> element
indicates the user roles that should be permitted access to the resource collection. Here is an e.g.
<auth-constraint>
<role-name> admin </role-name>
<role-name> master </role-name>
</auth-constraint>
The above declaration means a user with either of the admin or master roles will have access to the application.
The <login-config> element is used to define the user authentication mechanism (e.g. BASIC HTTP Authentication)
used in the application. The <url-pattern> element is used to define the resources (files, directories) to be protected.
There is no such element as <role>. Thus choice A is correct and others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 208
QUESTION STATEMENT : Which of the following is used to declare variables in a JSP page?
CHOICES :
a) <%@ ... %>
b) <% ... %>
c) < ... >

135
d) <%! ... %>
e) None of the above
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The syntax for declaring and intializing a variable in JSP is as follows:
<%! variable=variable_value ; %>
Example
<%!
private int i=4;
public void myMethod()
{
...
}
%>

--------------------------------------------------------------------

QUESTION NO : 209
QUESTION STATEMENT :
When a JSP custom tag is read, and an action started (a tag instance created), the ___ object is passed to the tag object
so that its environment can be initialized. (Write the class name for the object)
CHOICES :
a) ""
CORRECT ANSWER :
PageContext
EXPLANATION :
In case of JSP Custom Tag, the "PageContext" object is the first property to be set in the tag instance, followed by the
parent of the tag. The PageContext is an interface through which JSP and web server interacts.
Following is the part of the code of a typical _jspService() method in a translated JSP:
public void _jspService() (HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
...
PageContext pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
...
MyTagLibrary myTag = new MyTagLibrary();
myTag.setPageContext(pageContext);

136
...
}
--------------------------------------------------------------------

QUESTION NO : 210
QUESTION STATEMENT :
There are two mechanisms for including content from another source in a JSP page: the ___ directive and the
jsp:include action.
CHOICES :
a) ""
CORRECT ANSWER :
include
EXPLANATION :
The include directive notifies the web container/server to include the content of the resource in the current JSP, inline, at
the specified place. Here is the syntax for that:
<%@ include file="Filename" %>
The jsp:include action allows a static or dynamic resource to be included in the current JSP at request time. The
resource is specified using the URL format as show below:
<jsp:include page="url" flush="true" />
Please note the difference between the above two mechanisms. In the first case, the content of the included file is parsed
by the JSP at translation time (or compilation time). While the jsp:include action is used to include resources at runtime,
at the time of processing the request. When using include directive, the included file should not be another dynamic
page. In case of jsp:include action, the included resource can be either static or dynamic.
--------------------------------------------------------------------

QUESTION NO : 211
QUESTION STATEMENT : Every HTTP response returned from the server begins with a status code (e.g. 200). Which
of the following statements regarding the status codes are true?
CHOICES :
a)
b)
c)
d)
e)

The status code range 2xx (200's) indicates Success.


The status code range 3xx (300's) indicates Redirection.
The status code range 4xx (400's) indicates Client Error.
The status code range 5xx (500's) indicates Server Error.
The status code range 6xx (600's) indicates Information.

137

CORRECT ANSWER : abcd


EXPLANATION :
A,B,C and D are correct. The code range 1xx (100's) indicate information.
--------------------------------------------------------------------

QUESTION NO : 212
QUESTION STATEMENT :
The ___ element (in the Deployment Descriptor) contains the declaration of a web application's servlet context
initialization parameters.
Hint (The DTD definition) : <!ELEMENT ____ (param-name, param-value, description?)>
CHOICES :
a) ""
CORRECT ANSWER :
context-param
EXPLANATION :
The "context-param" element contains the declaration of a web application's servlet context initialization parameters.
The param-name element contains the name of a parameter. Each parameter name must be unique in the web
application. The param-value element contains the value of a parameter. Here is an example of the DD file for a web
application:
<web-app>
...
<context-param>
<param-name> SCWCD </param-name>
<param-value> scwcdwhiz@whizlabs.com </param-name>
</context-param>
...
</web-app>
--------------------------------------------------------------------

QUESTION NO : 213
QUESTION STATEMENT :
The ___ method of the ServletResponse returns a PrintWriter object that can send character text. to the client. (Write
only the method name without any braces e.g. myMethod and not myMethod())
CHOICES :

138
a) ""
CORRECT ANSWER :
getWriter
EXPLANATION :
The ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet
container creates a ServletResponse object and passes it as an argument to the servlet's service method.
To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream() . To send
character data, use the PrintWriter object returned by getWriter() . To mix binary and text data, for example, to create a
multipart response, use a ServletOutputStream and manage the character sections manually.
Here is an example:
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("I'm in Service() method");
}
--------------------------------------------------------------------

QUESTION NO : 214
QUESTION STATEMENT :
Looking at the page directive given below, ___ be written at position ///xxx for the JSP not to take part in session.
<%@ page session= "//xxx" %>
CHOICES :
a) ""
CORRECT ANSWER :
false
EXPLANATION :
The "session" attribute of the page directive Indicates that the page requires participation in an (http) ses-sion. If "true"
then the implicit script language variable named "session" of type javax.servlet.http.HttpSession references the
current/new session for the page. If "false" then the page does not participate in a session; the "session" implicit variable
is unavailable, and any reference to it within the body of the JSP page is illegal and shall result in a fatal translation
error. Default is "true".
--------------------------------------------------------------------

139

QUESTION NO : 215
QUESTION STATEMENT : Which of the following statements are true regarding JSP Custom Tags?
CHOICES :
a) A Custom Tag is a user-defined JSP language element.
b) When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object
called tag handler.
c) Custom tags can be customized via attributes passed from the calling page.
d) Custom tags can't be nested within one another.
e) Custom tags can communicate with each other.
CORRECT ANSWER : abce
EXPLANATION :
Choice A, B, C and E are correct. A JSP page can contains two type of tags: the standard JSP tags for invoking
operations on JavaBeans components and performing request dispatching and the custom tags, which are user defined
tags and are extensions to the JSP language. Thus choice A is correct. When a JSP page containing a custom tag is
translated into a servlet, the tag is converted into operations on an object called a tag handler. The web container/web
server then invokes those operations when the JSP page's servlet is executed. A tag handler is an object invoked by a
web container/web server to evaluate a custom tag during the execution of the JSP page that reference the tag. Thus
choice B is also correct. A custom tag can have attributes. Attributes are listed in the start tag and have the syntax
attribute_name="attribute_vaue". Attribute values serve to customize the behaviour of a custom tag just as parameters
are used to customize the behaviour of a method. Thus choice C is also correct. Custom tags can be nested within one
another and thus can cooperate with each other. Here is an example
<tt:outerTag>
<tt:innerTag />
</tt:outerTag>
Thus choice D is incorrect. JSP custom tags can communicate with each other. You can create and initialize a
JavaBeans component, create a variable that refers to that bean in one tag, and then use the bean in another tag. In the
example given below, tag1 creates an object named "myObj", which is then reused by tag2.
<tt:tag1 id="myObj" attr="value" />
<tt:tag2 name="myObj" />
Thus choice E is also correct.

--------------------------------------------------------------------

QUESTION NO : 216
QUESTION STATEMENT : There are two types of web components: Java Servlets and Java Server Pages (JSP). While
both can be used interchangeably, each has its strengths and weaknesses. Which of the two is best suited to managing
the "control" functions of an application?
CHOICES :
a) JSP
b) Servlets

140

CORRECT ANSWER : b
EXPLANATION :
B is correct. Java servlets are best suited to managing the control functions such as request dispatching and handling
non-textual data. JSP pages are more appropriate for generating text-based markup such as HTML, WML and XML. In
other words JSP pages represent the "view" part of a web application.
--------------------------------------------------------------------

QUESTION NO : 217
QUESTION STATEMENT : Which of the following methods need to be overriden for customizing the initialization
process of a JSP page?
CHOICES :
a)
b)
c)
d)
e)
f)

jspInit()
init()
start()
jspStart()
jspDestroy()
None of the above

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. To perform any one-time activity like reading persistent configuration data, initializing any
resource, one needs to override the jspInit() method of the JspPage interface. The page is initialized by invoking the
jspInit() method. This initialized the JSP much in the same way as servlets are initialized. The jspDestroy() method is
used to release the resources. Other methods are invalid.

--------------------------------------------------------------------

QUESTION NO : 218
QUESTION STATEMENT : The "value" attribute of the jsp:setProperty action can take a request-time attribute
expression as a value. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :

141
The jsp:setProperty actions is used in conjunction with the useBean action to set the value of bean properties used by
JSP page. The property of the Java Bean can also be set like below:
<jsp:setProperty name="myBean" property="number" value="<%=expression %>" />
In the code above, the "number" property of the JavaBean referred by "myBean" is set to value of the expression. Thus
the above statement is true.
--------------------------------------------------------------------

QUESTION NO : 219
QUESTION STATEMENT : Which of the following statements are true based on the <auth-constraint> element
definition of the Deployment Descriptor file of a web application?
<auth-constraint>
<role-name> * </role-name>
<role-name> role1 </role-name>
<role-name> role2 </role-name>
</auth-constraint>
CHOICES :
a) The above definition is incorrect.
b) Only users belonging to role1 or role2 are allowed to access the portion of the web application described by the
containing security-constraint.
c) A user belonging to any security-role is allowed to access the portion of the web application described by the
containing security-constraint.
d) None of the user is allowed to access the portion of the web application described by the containing securityconstraint.
CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The auth-constraint element indicates the user roles that should be permitted access to this
resource collection. The role-name used here must either correspond to the role-name of one of the security-role
elements defined for this web application, or be the specially reserved role-name "*" which is a compact syntax for
indicating "all roles" in the web application. If both "*" and role names appear, the container interprets this as all roles.
If no roles are defined, no user is allowed access to the portion of the web application described by the containing
security-constraint. The container matches role names case sensitively when determining access.
Thus choice C is correct while others are incorrect.
--------------------------------------------------------------------

QUESTION NO : 220
QUESTION STATEMENT : The implicit JSP objects like request, response, and out are only visible in the
_jspService() method. True/False?
CHOICES :

142

a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes unless passed in as arguments to other methods, the implicit JSP arguments are only visible in the jspService()
method.
--------------------------------------------------------------------

QUESTION NO : 221
QUESTION STATEMENT : Which of the following statements is true regarding MyServlet?
import javax.servlet.*;
import javax.servlet.http.*:
import java.io.*;
public class MyServlet extends HttpServlet implements SingleThreadModel
{
String myName;
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
response.setContentType("text/plain");
PrintWriter out = res.getWriter();
myName = req.getParameter("name");
sayHello(out);
out.close();
}
public void sayHello(PrintWriter out)
{
out.println("Hello " + myName);
}
}
CHOICES :
a)
b)
c)
d)

MyServlet is thread safe.


MyServlet is not thread safe because myName is an instance variable.
MyServlet is not thread safe because MyServlet implements SingleThreadModel.
None of these.

CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. An application is thread safe if it always behaves predictably regardless of the number of
concurrent threads running in its process space. The simplest way to ensure that a servlet is thread safe is to implement
the SingleThreadModel interface. By implementing this interface, the server guarantees that no more than one thread

143
can execute the service(), doGet(), or doPost() method at a time for a particular servlet instance. This makes the servlet
thread safe. Thus even if the MyServlet has instance variables, it is thread safe. Thus A is correct and other choices are
incorrect.
--------------------------------------------------------------------

QUESTION NO : 222
QUESTION STATEMENT : You need to design a web application which needs the information about all the residents
of a given state. The information about the residents is already available but scattered using different storage
mechanisms. Which of the following design patterns will you choose to avoid the problems (resulting from the different
storage mechanisms) in the future?
CHOICES :
a)
b)
c)
d)
e)

Value Objects
MVC
Data Access Object
Business Delegate
None of the above

CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. Many web applications need to access data sources. This data source may be a legacy system, an
RDBMS, a flat file or some other form. Due to presence of disparate data sources, normally there occurs a tight
coupling between the components and the data source implementation. Thus DAO (Data Access Object) is used to
abstract and encapsulate all access to the data source. The Data Access Object (DAO) manages the connection with the
data source to obtain and store data. The web component that relies on the DAO object uses the simple interface
exposed by the DAO for its clients. Effectively, the DAO acts as an adapter between the component and the data source.
In this way DAO enables transparency; the business objects can use the data source without knowing the specific details
of data source's implementation. Access is transparent because the implementation details are hidden inside the Data
Access Object.
Also a layer of Data Access Objects makes it easier for an application to migrate to a different database implementation.
The business objects have no knowledge of the underlying data implementation. Thus, the migration involves changes
only to the data access object layer.
--------------------------------------------------------------------

QUESTION NO : 223
QUESTION STATEMENT : The JSP technology allows the mechanism to buffer the output written to the response
object. True/False?
CHOICES :
a) True
b) False

144

CORRECT ANSWER : a
EXPLANATION :
When a JSP page is executed, output written to the response object is automatically buffered. The size of the buffer can
be set using the following directive:
<%@ page buffer="none|XXXKb" %>
If the buffer size is larger then more content can be written before anything is sent to client. Thus it provides the JSP
page with more time to set appropriate status codes/headers. In case of smaller buffer size, the server memory load
decreases but at the same time it allows the client to start receive date quickly.
--------------------------------------------------------------------

QUESTION NO : 224
QUESTION STATEMENT : What will be the output on execution of the following code in a Java Server Page (JSP)?
<html>
<body>
<% int count; %>
<% for (int i=0; i<10; i++) { out.println("The counter is :"+count); } %>
</body>
</html>
CHOICES :
a)
b)
c)
d)

It will print "The counter is :0" 10 times.


It will print "The counter is :0" 9 times.
The above code will give compilation error.
None of the above.

CORRECT ANSWER : c
EXPLANATION :
C is the correct answer. Please note that the syntax for declaring a variable in a JSP page is:
<%! var_type var=var_value; %>
In the above code '!' is missing.
But please note that if the statment above would have been <% int count=0; %>, the code would have compiled and run
without error. This is because in that case, the count would have act as a local variable (variable of the _jspService()
method; the code inside <% %> becomes part of the service method of the generated servlet).
In the question above, the code will not compile because; local variable needs to be initialized. Thus the above code will
compilation error stating "Variable count may not have been initialized".
--------------------------------------------------------------------

145

QUESTION NO : 225
QUESTION STATEMENT :
The object implementing the ___ interface is notified of changes to the attribute list on the servlet context of a web
application. (Write only the interface name)
CHOICES :
a) ""
CORRECT ANSWER :
ServletContextAttributeListener
EXPLANATION :
The object implementing the "ServletContextAttributeListener" interface is notified of changes to the attribute list on
the servlet context of a web application. The object needs to implement the following methods of the interface:
a.) public void attributeAdded(ServletContextAttributeEvent scab)
Notification that a new attribute was added to the servlet context. Called after the attribute is added.
b.) public void attributeRemoved(ServletContextAttributeEvent scab)
Notification that an existing attribute has been removed from the servlet context. Called after the attribute is
removed.
c.) public void attributeReplaced(ServletContextAttributeEvent scab)
Notification that an attribute on the servlet context has been replaced. Called after the attribute is replaced.
--------------------------------------------------------------------

QUESTION NO : 226
QUESTION STATEMENT : Is the following JSP tag library directive definition correct?
<%@ tag uri="URI" prefix="prefix" %>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The above declaration is incorrect. The correct declaration syntax is:
<%@ taglib uri="URI" prefix="prefix" %>

146
The uri attribute refers to a URI that uniquely identifies the TLD (Tag Library Descriptor). The prefix attribute defines
the prefix that distinguishes tags defined by a given library from those provided by other tag libraries.

--------------------------------------------------------------------

QUESTION NO : 227
QUESTION STATEMENT : Is the following declaration for init-param element used in DD file correct?
<init-param>
<param-value> 5 </param-value>
<param-name> age </param-name>
</init-param>
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The above declaration is incorrect, as <param-name> should be declared before <param-value>. The DTD for initparam element is as follows:
<!ELEMENT initialize-param (param-name, param-value, description?)>
This states that "param-name" should be declared before "param-value". This also states that the description element is
optional.
--------------------------------------------------------------------

QUESTION NO : 228
QUESTION STATEMENT :
The ___ interface provides a way to identify a user across more than one page request or visit to a website and to store
information about that user. (Write the name of the interface)

CHOICES :
a) ""
CORRECT ANSWER :
HttpSession

147
EXPLANATION :
The HttpSession interface provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session
persists for a specified time period, across more than one connection or page request from the user. A session usually
corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using
cookies or rewriting URLs.
--------------------------------------------------------------------

QUESTION NO : 229
QUESTION STATEMENT : Event Listener classes can be used by the web application developer as a way of tracking
sessions within an application. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes Listener classes provide the developer with a way of tracking sessions within a web application. It is often useful in
tracking sessions to know whether a session became invalid because the container timed out the session, or because a
web component within the application called the invalidate() method. The HttpSessionListener interface provides the
following methods for the above purpose:
a.) public void sessionCreated(HttpSessionEvent se)
Notification that a session was created.
b.) public void sessionDestroyed(HttpSessionEvent se)
Notification that a session was invalidated.
--------------------------------------------------------------------

QUESTION NO : 230
QUESTION STATEMENT :
The ___ method of the HttpServletResponse interface will set the appropriate headers and content body for an error
message to return to the client. (Write only the method name without any braces e.g. myMethod and not myMethod())
CHOICES :
a) ""

148
CORRECT ANSWER :
sendError
EXPLANATION :
The "sendError" method of the HttpServletResponse interface will set the appropriate headers and content body for an
error message to return to the client. The sendError() methods (there are two overloaded methods) return an error
message to the client according to the status code.
Here are the overloaded sendError() methods:
sendError(int): Sends an error response to the client using the specified status code and clearing the buffer.
sendError(int, String): Sends an error response to the client using the specified status clearing the buffer.

--------------------------------------------------------------------

QUESTION NO : 231
QUESTION STATEMENT :
The Form Based Authentication mechanism for securing a web application uses a login form, which must contain fields
for a username and a password. The username field must be named ____.
CHOICES :
a) ""
CORRECT ANSWER :
j_username
EXPLANATION :
The form used by Form Based Authentication mechanism consists of fields for username and password. These fields
must be named 'j_username' and 'j_password', respectively.
Here is an example showing how the form should be coded into the HTML page:
<form method="POST" action="j_security_check">
<input type="text" name="j_username">
<input type="password" name="j_password">
</form>
Also note that in order for the authentication to proceed appropriately, the action of the action of the login must always
be j_security_check. This restriction is made so that the login form will work no matter which resource it is for, and to
avoid requiring the server to specify the action field of the outbound form.

--------------------------------------------------------------------

149

QUESTION NO : 232
QUESTION STATEMENT : Which of the following are valid attributes of the jsp:useBean action tag used to associate
a JavaBean with a JSP?
CHOICES :
a)
b)
c)
d)
e)
f)

id
name
value
scope
class
type

CORRECT ANSWER : adef


EXPLANATION :
Choice A, D, E and F are correct. Following is the syntax of the jsp:useBean action:
<jsp:useBean id="name" scope="page|request|session|application" beandetails />
where bean details can be one of:
class="className"
class="className" type="typeName"
beanName="beanName" type="typeName"
type="typeName"
Following is the description of various attributes:
a.) id - The case sensitive name used to identify the object instance.
b.) scope - The scope within which the reference is available. The default value is page.
c.) class - The fully qualified (including package name) class name.
d.) beanName - The name of a Bean, as you would supply to instantiate() method in the java.beans.Beans class. This
attribute can also be a request time expression.
e.) type - This optional attribute specifies the type of the lcass, and follows standard java casting rules. The type must be
a superclass, an interface, or the class itself. The default value is the same as the value of the class attribute.
--------------------------------------------------------------------

QUESTION NO : 233
QUESTION STATEMENT : Which of the following combinations (Design Pattern - Functionality) regarding Design
Patterns are correct?
CHOICES :
a)
b)
c)
d)

Business Delegate - Reduces the coupling between presentation-tier clients and business services.
Data Access Object - Multiple View using the same model.
MVC - Enables easier migration to different persistence storage implementation.
Value Object - Reduces Network Traffic

150
CORRECT ANSWER : ad
EXPLANATION :
Choice A and D are correct. In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with
business services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the
business services: when the implementation of the business services change, the code in the presentation tier must
change. The goal of Business Delegate object design pattern is to minimize the coupling between presentation-tier
clients and the business service API, thus hiding the underlying implementation details of the service. Thus choice A is
correct.
Choice B is incorrect as it's the MVC design pattern rather than DAO (Data Access Object) which provide Multiple
View using the same model.
Choice C is incorrect as it's the DAO (Data Access Object), which enables easier migration to different persistence
storage implementation.
The Value Object is used to encapsulate the business data. A single method call is used to send and retrieve the Value
Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Value
Object, populate it with its attribute values, and pass it by value to the client. Thus choice D is also correct.
--------------------------------------------------------------------

QUESTION NO : 234
QUESTION STATEMENT :
The tlib-version element is the sub element of ___ element.
CHOICES :
a) ""
CORRECT ANSWER :
taglib
EXPLANATION :
The tlib-version is the subelement of "taglib" element. Here is the DTD for taglib and tlib-version
<!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?, display-name?,
small-icon?, large-icon?, description?, validator?, listener*, tag+) >
<!ELEMENT tlib-version (#PCDATA)>
The taglib element is the document root and is used to describe a JSP tag library. It defines tlib-version, which specifies
the version for the tag library implementation.
--------------------------------------------------------------------

QUESTION NO : 235

151
QUESTION STATEMENT : Servlets are built on JSP semantics and all servlets are compiled to JSP pages for runtime
usage.True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : b
EXPLANATION :
The reverse of the above statment is true, i.e, JSPs are built on Servlet semantics and all JSPs are compiled to servlets
for runtime usage.
--------------------------------------------------------------------

QUESTION NO : 236
QUESTION STATEMENT : Consider the following HTML form and the corresponding servlet
//PostTest.html
<html>
<body>
<form method="POST" action="/servlet/PostTest">
val1=<input type="text" name="value1"><br>
val2=<input type="text" name="value2">
<input type="submit" name="AddButton">
</form>
</body>
</html>
// PostTest.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostTest extends HttpServlet
{
int sum = 0;
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("val1 obtained is = "+req.getParameter("value1"));
out.println("val2 obtained is = "+req.getParameter("value2"));
out.println("val1 obtained again is = "+req.getParameter("value1"));
out.println("val2 obtained again is = "+req.getParameter("value2"));
}

152
}
The form PostTest.html is accessed in a browser, and the values entered are value1 = 500 and value2 = 600. What will
be displayed in the browser on clicking the 'submit' button?
CHOICES :
a)
A compile time error
b)
val1 obtained is = 500
val2 obtained is = 600
val1 obtained again is = 500
val2 obtained again is = 600
c)
val1 obtained is = 500
val2 obtained is = 600
val1 obtained again is = null
val2 obtained again is = null
d)
val1 obtained is = 500&600
val2 obtained is = null
val1 obtained again is = null
val2 obtained again is = null
CORRECT ANSWER : b
EXPLANATION :
Choice B is correct. The "String HttpServletRequest.getParameter(String )" method has been implemented in such a
way that no matter how many times it is called for a particular parameter, it always returns the parameter value.

--------------------------------------------------------------------

You might also like