Web Component Sample Questions
Web Component Sample Questions
B. ${product.price = param.i2}
C. </jsp:useBean>
D. </jsp:useBean>
Answer: C
Explanation:
Questions 2. You need to create a JavaBean object that is used only within the current ISP
page. It must NOT be accessible to any other page including those that this page might
import. Which JSP standard action < .in accomplish this goal?
A. <jsp:useBean id = `pageBean' type = `com.example.MyBean' />
B. <jsp:useBean id = `pageBean' class = `com.example.MyBean' />
C. <jsp:makeBean id = `pageBean' type = `com.example.MyBean' />
D. <jsp:makeBean id = `pageBean' class = `com.example.MyBean' />
E. <jsp:useBean id = `pageBean' class = `com.example.MyBean' />
F. <jsp:makeBean id = `pageBean' class = `com.example.MyBean' />
Answer: B
Explanation:
Questions 3. Given the JavaBean class:
public class MyBean {
private Boolean roasted = false;
public MyBean () {}
public Boolean isRoasted () { returned roasted }
public void setRoasted (Boolean roasted) { this.roasted = roasted; ] }
Assume a controller has created an instance of this bean, called setRoasted (true), and
inserted the bean into the application scope using the name "myBean".
A JSP contains these two tags:
<jsp: useBean id = "aBean" class = "MyBean" scope = "page" \ /> <jsp: getProprty name =
"aBean" property = "roasted" \ />
Which is true?
A. the page will include the output false
B. the page will include the output
C. the page will report that the property roasted does not exist
D. the page will report that the syntax of the useBean tag is incorrect
E. the page will report that the syntax of the getProperty tag ls incorrect
Answer: E
Explanation:
Questions 4. A developer chooses to avoid using singieThreadModel but wants to ensure
that data If; updated in a thread safe manner.
Which two can support this design goal? (Choose two)
B. javax.servlet.http.HttpSessionValueListener
C. javax.servlet.http.HttpSessionBindingListener
D. javax.servlet.http.HttpSessionAttributeListener
Answer: D
Explanation:
Questions 10. Which statement is true about web container session management?
A. Access to session-scoped attributes is guaranteed to be thread-safe by the web container.
B. To activate URL rewriting, the developer must use the
HttpServletResponse.setURLRewriting method.
C. If the web application uses HTTPS, then the web container may use the data on the
HTTPS request stream to identify the client.
D. The JSESSIONID cookie is stored permanently on the client so that a user may return to
the web application and the web container will rejoin that session.
Answer: C
Explanation:
Questions 11. A method call inside your servlet has thrown an IOException
resulting from a lost network connection to a necessary resource. The servlet
has determined that it will be unable to operate successfully fen few minutes,
but expects to be able to resume operation after that period. How should this
situation handled?
A. The servlet should re-throw the exception to the web container.
B. The servlet should throw a servletException to the web container.
C. The servlet should throw an unavailableException to the web container.
D. The servlet should redirect to an error page that reports the exception
message.
E. The servlet should retry the request until the method returns successfully.
Answer: C
Explanation:
Questions 12. During initialization, a servlet finds that the database connection
it requires is unavailable. As the system designer, you know that the database
start up completes several minutes after the web- container initializes the
servlet. How should this be handled?
A. Retry the connection until it is successful, then allow the init() method to
complete.
B. Throw a ServletException
C. Throw the IOException
D. Throw an UnavailableException
Answer: D
Explanation:
Questions 24. The jquery_1_3_2.jar file contains the JQuery Ajax framework in
its META-INF/ resources directory. Where should the jar file be placed inside the
web application to ensure the resources it contains are accessible by clients?
A. WEB-INF/classes
B. WEB-INF/jar
C. WEB-INF/lib
D. WEB INF/resources
Answer: C
Explanation:
Questions 25. Given a jar file packaged with three web fragments with names
X, Y and Z respectively.
Which of the following deployment descriptor, web.xml, snippets correspond to
the web fragment processing orders of X, Y, Z?
(i) <absolute-ordering>
<name>X</name>
<name>Y</name>
<name>Z</name>
</absolute-ordering>
(ii) <absolute-ordering>
<name>X</name>
<name>Y</name>
</absolute-ordering>
(iii) <absolute-ordering>
</others>
<name>Y</name>
<name>Z</name>
</absolute-ordering>
(iv) <absolute-ordering>
<name>X</name>
</others>
<name>Z</name>
</absolute-ordering>
(v) <absolute-ordering>
<name>X</name>
<name>Y</name>
</others>
</absolute-ordering>
A. (i) only
B. (i) and (ii)
C. (i) and (iv)
D. (i), (iii), (iv) and (v)
Answer: C
Explanation:
Questions 26. Which defines the welcome files in a web application deployment
descriptor?
A. </welcome>
B. </welcome-file-list>
C. </we1come >
D. </welcome-file-list>
E. </welcome>
Answer: B
Explanation:
Questions 27. Which code snippet specifies the metadata for a servlet with:
(i) url mapping "/mytest"'
(ii) Initial parameter with name "debug" and value "10"' (iii) Support
asynchronous operation?
A. public class TestServlet extends HttpServlet {}
B. Public class testServlet {}
C. Initparams = {@InitParam (name = "debug", value = "10") }, supportAsync
= true) public class TestServlet extends HttpServlet {}
D. Initparams = {@InitParam (name = "debug", value = "10") },
asyncSupported = true) public class TestServlet extends HttpServlet {}
E. Initparam = @WebInitParam (name = "debug", value = "10"), supportAsync
= true) public class testServlet {}
Answer: D
Explanation:
Questions 28. Which annotation specifies the metadata as a
javax.servlet.http.HttpSessionListener?
A. @Listener
B. @WebListener
C. @WebSessionListener
D. @HttpSessionListener
Answer: A
Explanation:
Questions 29. You are creating a new ISP page and you need to execute some
code that acts when the- page is first executed, but only once. Which three are
possible mechanisms for performing this initialization code? (Choose three)
A. In the init method.
B. In the jspInit method.
C. In the constructor of the JSP's Java code.
D. In a JSP declaration, which includes an initializer block.
E. In a JSP declaration, which includes a static initializer block.
Answer: B,D,E
Explanation:
Questions 30. You are creating a web form with this HTML:
11. <form action="sendOrder.jsp">
12. <input type="text" name="creditCard">
13. <input type="text" name="expirationDate">
14. <input type="submit">
15. </form>
Which HTTP method is used when sending this request from the browser?
A. GET
B. PUT
C. POST
D. SEND
E. FORM
Answer: A
Explanation:
Questions 31. Your web application requires the ability to load and remove web files
dynamically to the web container's file system? Which two HTTP methods are used to
perform these actions? (Choose two)
A. PUT
B. POST
C. SEND
D. DELETE
E. REMOVE
F. DESTROY
Answer: A,D
Explanation:
Questions 32. A web application wants to expose to its clients an operation that results in a
transaction being performed across several systems, for example the transfer of money
from one bank account to another
Which HTTP method should it use?
A. GET
B. HEAD
C. OPT IONS
D. POST
Answer: D
Explanation:
Questions 33. A Client wants to retrieve a representation of a resource, e.g. an XML
document, localized according to the preferences of the user. Each user is allowed to
specify one or more languages, in order of preference. Such preferences are application
independent. How can the Client send language preference Information to the Server using
a standard HTTP facility?
A. In the request body
B. In a request header
C. In the request line
D. In the request URL
Answer: B
Explanation:
Questions 34. Which JSTL code snippet can be used to import content from another web
resource?
A. <c:import url = "foo.jsp"/>
B. <c:import page = "foo.jsp"/>
C. <c:include url = "foo.jsp"/>
D. <c:include page = "foo.jsp"/>
E. Importing cannot be done in JSTL. A standard action must be used instead.
Answer: A
Explanation:
Questions 35. In a jsp-centric shopping cart application cart application to move a client's
home address of Customer object into the shipping address of the order object. The address
data is stored in a value object class called Address with properties for: street address, city,
province, country, and postal code.
Which two code snippets can be used to accomplish this goal?
A. value='${client.homeAddress}' />
B. value='${client.homeAddress}' />
C. <jsp:setProperty name='${order}' property='shipAddress' value='$
{client.homeAddress}' />
D. <jsp:getProperty name='client' property='homeAddress' /> </c:store>
E. <jsp:getProperty name='client' property='homeAddress' /> </c:set>
F. <c:setProperty name='${order}' property='shipAddress'> <jsp:getProperty name='client'
property='homeAddress' /> </c:setProperty>
Answer: B,E
Explanation:
Questions 36. You are creating a JSP page to display a collection of data. This data can be
displayed in several different ways so the architect on your project decided to create a
generic servlet that generates a comma delimited string so that various pages can render the
data in different ways. This servlet takes on request parameter: objoctI
D. Assume that this servlet is mapped to the URL pattern:
/WEB-INF/data.
In the JSP you are creating, you need to split this string into its elements separated by
commas and generate an HTML <ul> list from the data.
Which JSTL code snippet will accomplish this goal?
A. </ul>
B. </ul>
C. </ul>
D. </ul>
Answer: D
Explanation:
Questions 37. Which JSP standard action can be used to import content from a resource
called foo.jsp?
A. <jsp:import file='foo.jsp' />
B. <jsp:import page='foo.jsp' />
C. <jsp:include page='foo.jsp' />
D. <jsp:include file='foo.jsp' />
E. <jsp:import>foo.jsp</jsp:import>
F. <jsp:include>foo.jsp</jsp:include>
Answer: C
Explanation:
Questions 38. Refer to the Exhibit.
Assuming the tag library in the exhibit is imported with the prefix forum, which custom tag
invocation procedures a transaction error in a jsp page?
Explanation:
Questions 39. Given the element from the web application deployment descriptor:
<jsp ? property ? group>
<url ? pattern>/main/page1.jsp</url ? pattern>
<scripting ? invalid>true</scripting ? invalid>
</jsp--property--group>
And given that /main/page1.jsp contains:
<% int i = 12; %>
<b> <%= i %> </b>
What is the result?
A. <b> <b>
B. <b> l2 </b>
C. The JSP fails to execute.
D. <b> <%= i % > < b>
Answer: C
Explanation:
Questions 40. A web application allows the HTML title banner to be set using a context
initialization parameter called titlestr.
Which two properly set the title in the scenario? (Choose two)
A. <title> $ {titlestr} </title>
B. <title> $ {initparam.titlestr}</title>
C. <title> $ {param [0]. titlestr} </title>
D. <title> $ {paramValues.titleStr} </title>
E. <title> $ {initParam [`titleStr'] } </title>
F. <title> $ {servletParams.titleStr} </title>
G. <title> $ {request.get ("titleStr") } </title>
Answer: B,E
Explanation:
Questions 41. Given:
11. <%
12. request.setAttribute ("vals", new String[] {"1", "2", "3", "4"});
13. request.setAttribute ("index", "2");
14. %>
15. <% - - insert code here - - %>
Which three EL expressions, inserted at line 15, are valid and evaluate to "3"? (Choose
three)
A. ${vals.2}
B. ${vals ["2"] }
C. ${vals.index}
D. ${vals[index] }
E. ${vals} [index]
F. ${vals. (vals.index) }
G. ${vals [vals[index-1]] }
Answer: B,D,G
Explanation:
Questions 42. Given:
Which three EL expressions, inserted at line 16, are valid and evaluate to "d"? (Choose
three)
A. ${map.c}
B. ${map.[c]}
C. ${map.["c"]}
D. ${map.map.b}
E. ${map.[map.b]}
F. ${map. (map.b)}
Answer: A,C,E
Explanation:
Questions 43. Which is a benefit of precompiling a JSP page?
A. It avoids initialization on the first request.
B. It provides the ability to debug runtime errors in the application.
C. It provides better performance on the first request for the JSP page.
D. It avoids execution of the _jspService method on the first request.
Answer: C
Explanation:
Questions 44. A web browser need NOT always perform a complete request for a particular
page that it suspects might NOT have changed. The HTTP specification provides a
mechanism for the browser to retrieve only a partial response from the web server; this
response includes information, such as the Last-Modified date but NOT the body of the
page. Which HTTP method will the browser use to retrieve such a partial response?
A. GET
B. ASK
C. SEND
D. HEAD
E. TRACE
F. OPTIONS
Answer: D
Explanation:
C. <jsp:declaration.instance>
D. <jsp:scriptlet.declaration>
Answer: A
Explanation:
Questions 49. To take advantage of the capabilities of modern browsers that use web
standards, such as XHTML and CSS, your web application is being converted from simple
JSP pages to JSP Document format. However, one of your JSPs,
/scripts/screenFunctions.jsp, generates a JavaScript file. This file is included in several web
forms to create screen-specific validation functions and are included in these pages with the
following statement:
Which JSP code snippet declares that this JSP Document is a JavaScript file?
2. <ex:hello />
Which JSP code, inserted at line 1, completes the JSP code to invoke the hello tag?
44. <param-value>[email protected]</param-value>
45. </context-param>
Which JSP code snippet creates this email link?
A. <a href=`mailto:${contextParam.webmaterEmail}'>contact us</a>
B. <a href=`mailto:${applicationScope.webmaterEmail}'>contact us</a>
C. <a href=`mailto:${contextInitParam.webmaterEmail}'>contact us</a>
D. <a href=`mailto:${initParam.webmaterEmail}'>contact us</a>
Answer: D
Explanation:
Questions 54. Which EL expression evaluates to the request URI?
A. ${requestURI}
B. ${request.URI}
C. ${request.getURI}
D. ${request.requestURI}
E. ${requestScope.requestURI}
F. ${pageContext.request.requestURI}
G. ${requestScope.request.requestDRI}
Answer: F
Explanation:
Questions 55. You are building a dating web site. The client's date of birth is collected
along with lots of other information. The Person class has a derived method, getAge() :int,
which returns the person's age calculated from the date of birth and today's date. In one of
your JSPs you need to print a special message to clients within the age group of 25 through
35.
Which two EL code snippets will return true for this condition? (Choose two.)
A. ${client.age in [25,35]}
B. ${client.age between [25,35]}
C. ${client.age between 25,35}
D. ${client.age <= 35 && client.age >= 25}
E. ${client.age le 35 and client.age ge 25}
F. ${client.age > 35 && client.age < 25}
Answer: D,E
Explanation:
Questions 56. Given an EL function declared with:
Which two are true? (Choose two)
Explanation:
Questions 60. You are building a dating service web site. Part of the form to submit a
client's profile is a group of radio buttons for the person's hobbies:
20. <input type = `radio' name = `hobbyEnum' value = `HIKING'> Hiking <br>
21. <input type = `radio' name = `hobbyEnum' value = `SKING'> Sking <br>
22. <input type = `radio' name = `hobbyEnum' value = `SCUBA'> SCUBA <br>
23. <! - - and more options - - >>
After the user submits this form, a confirmation screen is displayed with these hobbies
listed. Assume that an application-scoped hobbies, holds a map between the hobby
enumerated type and the display name.
Which EL code snippet will display Nth element of the user's selected hobbles?
A. ${hobbies [hobbyEnum[N]}
B. ${hobbies [paramValues.hobbyEnum[N]]}
C. ${hobbies [paramValues @ `hobbyEnum' @N]
D. ${hobbies.get(paramValues.hobbyEnum[N]) }
E. ${hobbies [paramValues.hobbyEnum.get(N)] }
Answer: B
Explanation: Questions 61. For which three events can web application event listeners be
registered? (Choose three.)
A. when a session is created
B. after a servlet is destroyed
C. when a session has timed out
D. when a cookie has been created
E. when a servlet has forwarded a request
F. when a session attribute value is changed
Answer: A,C,F
Explanation:
Questions 62. To add a servlet to a context that has not been declared either via annotation
or via the descriptor, during context initialization time the following API can be used
(Choose three.)
A. servletContext.addServlet("myServletName", "MyServlet");
B. Servlet>)getClass().getClassLoader().getClassLoader().loaderClass("MyServlet"));
C. servletContext.addServlet(myServlet);
D. servletContext.addServlet( ("myServletName", <Class extends
Servlet>)gerClass().getClassLoader().loaderClass("myServlet"));
E. servletContext.addServlet("myServletName", MyServlet);
Answer: A,D,E
Explanation:
A. JSP
B. Servlet
C. Filter
D. POJO
E. Custom Tag
Answer: A,B
Explanation:
Questions 66. Given:
1. <% int[] nums = {42,420,4200};
2. request.setAttribute("foo", nums); %>
3. ${5 + 3 It 6}
4. S(requestScope['foo'][0] ne 10 div0>
5. ${10 div 0}
What is the result?
A. true true
B. false true
C. false true 0
D. true true Infinity
E. false true Infinity
F. An exception is thrown
G. Compilation or translation fails
Answer: E
Explanation:
Questions 67. View the Exhibit.
Given the web application deployment descriptor elements:
11. <filter>
12. <filter-name>ParamAdder</filter-name>
13. <filter-class>com.example.ParamAdder</filter-class>
14. </filter>
...
31. <filter-mapping>
32. <filter-name>ParamAdder</filter-name>
33. <servlet-name>Destination</servlet-name>
34. </filter-mapping>
...
55. <servlet-mapping>
56. <servlet-name>Destination</servlet-name>
57. <url-pattern>/dest/Destination</url-pattern>
58. </servlet-mapping>
What is the result of a client request of the Source servlet with no query string?
Which EL code snippet will generate the string for the previous week?
A. ${d:dateString(affWeek(curDate(), -1)) }
B. ${d:dateString [addWeek[curDate[], - ]] }
C. ${d:dateString [d:addWeek[d:curDate[], - 1]] }
D. ${d:dateString (d:addWeek(d:curDate(), -1)) }
Answer: D
Explanation:
Questions 69. Given a header in an
H. IP request:
X-Retries: 4
A Which two retrieve the value of the header from a given HttpServletRequest request?
(Choose two)
A. request-getHeader("X-Retries")
B. request.getlntHeader("X-Retries")
C. request.getRequestHeader("X-Retries")
D. request.getHeaders{"X-Retries").get(0)
E. request.getRequestHeaders("X-Retries").get(0)
Answer: A,B
Explanation:
Questions 70. Given an HttpServletRequestrequest and HttpResponseresponse, which sets a
cookie "username" with the value "joe" in a servlet?
A. request.addCookie("username", "joe")
B. request.setCookie("username", "joe")
C. response.addCookie("username", "joe")
D. request.addHeader(new Cookie("username", "joe"))
E. request.addCookie(new Cookie("username", "joe"))
F. response.addCookie(new Cookie("username", "joe"))
G. response.addHeader(new Cookie("username", "joe"))
Answer: F
Explanation:
Questions 71. Which annotation enables a servlet to efficiently process requests of typo
multipart/form-data that involve large files being uploaded by the client?
A. @AcceptMultipart
B. @MultiPartConfig
C. @MultiPartFormData
D. @WebServlet (multipart = true)
Answer: B
Explanation:
Questions 72. APIs for dynamically registering servlets and filters can be called at:
A. Context initialization time
B. Any time
C. There is no way to dynamically register servlets and filters
D. Context destruction time
E. Injected into a servlet context
Answer: A
Explanation:
Questions 73. ServletRegistration.Dynamic can be used to configure (Choose two)
A. Filter mappings
B. add init params
C. set asyncSupported to true
D. add Listeners
Answer: A,B
Explanation:
Questions 74. A web application wants to register a new servlet at runtime using one of the
servletContext.addServlet methods.
In the implementation of which method is it legal to perform this operation?
A. AsyncListner.oncomplete
B. Servlet.init
C. ServletContextListener.contextInitialize
D. ServletrequestListener.contextInitialize
Answer: C
Explanation:
Questions 75. You want to create a filter for your web application and your filter will
implement
.servlet.Filter.
Which two statements are true? (Choose two)
A. Your filter class must implement an init method and a destroy method.
B. Your filter class must also implement javax.sarvlat.FilterChain.
C. When your filter chains to the next filter, it should pass the same arguments it received
in its doFilter method.
D. The method that your filter invokes on the object it received that implements javax ?
servlet.Filterchain can invoke either another filter or a servlet.
E. Your filter class must implement a doFilter method that takes, among other things, an
HttpServletRequest object and an HttpServletresponse object.
Answer: A,D
Explanation:
Questions 76. Which three are true about the HttpServletRequestWrapper class? (Choose
three.)
A. The HttpServletRequestWrapper is an example of the Decorator pattern.
B. The HttpServletRequestWrapper can be used to extend the functionality of a servlet
request.
parameter. To do this additional processing, you pass the request first to a servlet that is
mapped to the URL pattern /WEB ? INF / retrieveOrder.do. in the deployment descriptor.
This servlet takes two request parameters, the ordered and the jspID and the jspURL. It
handles the database calls to retrieve and build the complex order objects and then it
dispatches to the jspURL.
Which code snippet in the Front Controller servlet dispatches the request to the order
retrieval servlet?
A. = context.getRequestDispathcher ("/WEB ? INF / retrieveOrder.do");
view.forward(request, response)
B. = request.getDispatcher (".WEB ? INF / retrieveOrder.do"); View.forwardRequest
(request, response);
C. View.forward (request, response) ;
D. View.forwardRequest (request, response) ;
Answer: C
Explanation:
Questions 79. In ServletContext.getNamedDispatcher(string arg0) arg0 is the
A. url of a servlet relative to the ServletRequest
B. url of a servlet relative to the Context
C. name of a servlet
D. absolute url to any servlet in any Context
Answer: B
Explanation:
Questions 80. Servlet A forwarded a request to servlet B using the forward method of
RequestDispatcher. What attribute in B's request object contains the URI of the original
request received by servlet A?
A. REQUEST_URI
B. javax.servlet.forward.request_uri
C. javax.servlet.forward.REQUEST_URI
D. javax.servlet.request_dispatcher.request_uri
E. javax.servlet.request_dispatcher.REQUEST_URI
Answer: B
Explanation:
Questions 81. View the Exhibit.
Assume the product attribute does NOT yet exist in any scope. Which two create an
instance of com.example.Product and initialize the name and price properties to the name
and price request parameters? (Choose two)
D. AsyncContext.start(runnable);
E. RequestDispatcher.fotward("/url");
F. RequestDispatcher.forward(servletContext, "/url");
G. RequestDispatcher.include("/url");
Answer: C
Explanation:
Questions 83. Which describes a trigger that causes a call to an AsyncListener?
A. Completion of processing
B. Receipt of a new request from the same client
C. Addition of a new filter to the processing stream for this request
D. Completion of each timer interval
Answer: B
Explanation:
Questions 84. Refer to the Exhibit.
A servlet sets a session-scoped attribute product with an instance of com.example.product
an forward to a JSP. Which two output the name of the product in the response? (Choose
two)
A. id
B. name
C. type
D. param
E. property
F. reqParam
G. attribute
Answer: B,D,E
Explanation:
Questions 87. A developer wants to make a name attribute available to all servlets
associated with a particular user, across multiple requests from that user, from the same
browser instance. Which two provide this capability from within a tag handler? (Choose
two)
A. pageContext.setAttribute("name", theValue);
B. pageContext.setAttribute("name", getSession() );
C. pageContext.getRequest().setAttribute("name", theValue);
D. pageContext.getSession().setAttribute("name", theValue);
E. pageContext.setAttribute("name", theValue, PageContext.PAGE_SCOPE);
F. pageContext.setAttribute("name", theValue, PageContext.SESSION_SCOPE);
Answer: D,F
Explanation:
Questions 88. Given that a web application consists of two HttpServlet classes, ServletA
and ServletB, and the ServerletA.service method:
20. String key = "com.example.data";
21. session.setAttribute(key, "Hello");
22. object value = session.getAttribute(key);
23.
Assume session is an HttpSession, and is not referenced anywhere else in ServletA. Which
two changes, taken together, ensure that value is equal to "Hello" on line 23? (Choose two)
A. ensure that the ServletB.service method is synchronized
B. ensure that the ServletA.service method is synchronized
C. ensure that ServletB synchronizes on the session object when setting session attributes
D. )
E. )
Answer: C,E
Explanation:
Questions 89. Given an HttpServletRequest request:
22. String id = request.getParameter("jsessionid");
23. // insert code here
24. String name = (String) session.getAttribute("name")
Which three can be placed at line 23 to retrieve an existing HttpSession object? (Choose
three)
A. HttpSession session = request.getSession();
B. HttpSession session = request.getSession(id);
C. HttpSession session = request.getSession(true);
D. HttpSession session = request.getSession(false);
E. HttpSession session = request.getSession("jsessionid");
Answer: A,C,D
Explanation:
Questions 90. As a convenience feature, your web pages include an Ajax request every five
minutes to a special servlet that monitors the age of the user's session. The client-side
JavaScript that handles the Ajax callback displays a message on the screen as the session
ages. The Ajax call does NOT pass any cookies, but it passes the session ID in a request
parameter called sessionI
D. In addition, assume that your webapp keeps a hasmap of session objects by the I
D. Here is a partial implementation of this servlet:
10. public class SessionAgeServlet extends HttpServlet {
11. public void service(HttpServletRequest request, HttpServletResponse) throws
IOException {
12. String sessionID = request.getParameter("sessionID");
13. HttpSession session = getSession(sessionID);
14. long age = // your code here
15. response.getWriter().print(age);
16. }
... // more code here
47. }
Which code snippet on line 14, will determine the age of the session?
A. session.getMaxInactiveInterval();
B. session.getLastAccessed().getTime() ? session.getCreationTime().getTime();
C. session.getLastAccessedTime().getTime() ? session.getCreationTime().getTime();
D. session.getLastAccessed() - session.getCreationTime();
E. session.getMaxInactiveInterval() ? session.getCreationTime();
F. session.getLastAccessedTime() ? session.getCreationTime();
Answer: F
Explanation:
Questions 91. Given the definition of Myobject and that an instance of Myobject
is bound as a session attribute:
8. package com.example;
9. public class Myobject implements
10. javax.servlet.http.HttpSessionBindingListener {
11. // class body code here
12. }
Which is true?
A. Only a single instance of Myobject may exist within a session
B. The unbound method of the Myobject instance is called when the session to
which it is bound times out
C. The com.example.MyObject must be declared as a servlet event listener in
the web application deployment descriptor
D. The valueUnbound method of the Myobject instance is called when the
session to which it is bound times out
Answer: D
Explanation:
Questions 92. Your web application requires the adding and deleting of many
session attributes during a complex use case. A bug report has come in that
indicates that an important session attribute is being deleted too soon and a
D. authentication
Answer: D
Explanation:
Questions 96. Which java code snippet roles "MANAGER" and "EMPLOYEE" in a
given application?
A. public class MyServlet extends HttpServlet {}
B. public class MyServlet extends HttpServlet {}
C. public class MyServlet extends HttpServlet {}
D. public class MyServlet extends HttpServlet {}
Answer: A
Explanation:
Questions 97. Given the java code snippet in contextInitialized method of a
ServletContextListner:
ServletRegistration.Dynamic sr = (ServletRegistration.Dynamic)sc.addServlet
("myServlet", myServletClass);
sr.addMapping("/abc");
sr.setServletSecurityElement(servletSecurityElement); sr.addMapping("/def");
Which statement is true?
A. "/abc" is mapped to "myservlet". The servletSecurityElementy applies to
both "/abc" and "/def".
B. Both "/abc" and "/def" are mapped to "myservlet". The
servletSecurityElementy applies to "/abc".
C. Both "/abc" and "/def" are mapped to "myservlet". The
servletSecurityElementy applies to "/def".
D. Both "/abc" and "/def" are mapped to "myservlet". The
servletSecurityElementy applies to both "/abc" and "/def".
E. Both "/abc" and "/def" are mapped to "myservlet". The
servletSecurityElementy applies to "/abc", but the behavior for "/def" is not
specified.
Answer: E
Explanation:
Questions 98. Given:
3. class MyServlet extends HttpServlet {
4. public void doPut(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
5. // servlet code here
...
26. }
27. }
If the DD contains a single security constraint associated with MyServlet and its
Questions 101. A web application uses a cookies to track a client as it navigates through the
pages that constitutes the application. Which code snippet can be used by the web
application to reduce the chance of a cross-site scripting attack by setting some property of
the cookie before returning it to the client?
A. cookie.setHttpOnly(true)B. cookie.setMaxAge(3600)C. cookie.setPath("/")D.
cookie.setSecure(true)
Answer: A
Explanation:
Questions 102. Given the portion of a valid Java EE web application's directory structure:
You want to know whether File1.html, File2.html, and/or File3.html is protected from
direct access by your web client's browsers. What statement is true?
A. All three files are directly accessible.B. Only File1.html is directly accessible.C. Only
File2.html is directly accessible.D. Only File3.html is directly accessible.E. Only File1.html
and File2.html are directly accessible.F. Only File1.html and File3.html are directly
accessible.G. Only File2.html and File3.html are directly accessible.
Answer: B
Explanation:
Questions 103. Given a web fragment jar file, where should we put the web fragment.xml
inside the jar file?
A. WEB-INFB. META-INFC. WEB-INF/libD. WEB-INF/classesE. META-INF/services
Answer: C
Explanation:
Questions 105. You have built a web application that you license to small businesses. The
webapp uses a context parameter, called licenseExtension, which enables certain advanced
features based on your client's license package. When a client pays for a specific service,
you provide them with a license extension key that they insert into the <context-param> of
the deployment descriptor. Not every client will have this context parameter so you need to
create a context listener to set up a default value in the licenseExtension parameter.
Which code snippet will accomplish this goal?
A. You cannot do this because context parameters CANNOT be altered
programmatically.B. }
C. }
D. context.resetInitParameter(`licenseExtension' DEFAULT); }
E. context.setInitParameter(`licenseExtension' DEFAULT); }
Answer: A
Explanation:
Questions 108. When using the @WebListener annotation, the class on which the
annotation is applied to must also implement at least one o the following interfaces ?
(Choose two):
A. RequestListenerB. AttributeListenerC. ServletContextListenerD. HttpSessionListenerE.
SessionAttributeListenerF. AsyncListener
Answer: C,D
Explanation:
1.You are creating a JSP page to display a collection of data. This data can be displayed in several different
ways so the architect on your project decided to create a generic servlet that generates a commadelimited
string so that various pages can render the data in different ways. This servlet takes on request parameter:
objectID.
Assume that this servlet is mapped to the URL pattern: /WEBINF/data.
In the JSP you are creating, you need to split this string into its elements separated by commas and
generate an HTML <ul> list from the data.
Which JSTL code snippet will accomplish this goal?
A.<c:import varReader='dataString' url='/WEBINF/data'>
<c:param name='objectID' value='${currentOID}' />
</c:import>
<ul>
<c:forTokens items'${dataString.split(",")}' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
B.<c:import varReader='dataString' url='/WEBINF/data'>
<c:param name='objectID' value='${currentOID}' />
</c:import>
<ul>
<c:forTokens items'${dataString}' delims=',' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
C.<c:import var='dataString' url='/WEBINF/data'>
<c:param name='objectID' value='${currentOID}' />
</c:import>
<ul>
<c:forTokens items'${dataString.split(",")}' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
D.<c:import var='dataString' url='/WEBINF/data'>
<c:param name='objectID' value='${currentOID}' />
</c:import>
<ul>
<c:forTokens items'${dataString}' delims=',' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
Answer:D
2.You web application uses a lot of Java enumerated types in the domain model of the application. Built into
each enum type is a method, getDisplay(), which returns a localized, useroriented string. There are many
uses for presenting enums within the web application, so your manager has asked you to create a custom
tag that iterates over the set of enum values and processes the body of the tag once for each value setting
the value into a pagescoped attribute called, enumValue.
Here is an example of how this tag is used:
10: <select name='season'>
11: <t:everyEnum type='com.example.Season'>
12: <option value='${enumValue}'>${enumValue.display}</option>
13: </t:everyEnum>
14: </select>
You have decided to use the Simple tag model to create this tag handler.
Which tag handler method will accomplish this goal?
A.public void doTag() throw JspException {
try {
for ( Enum value : getEnumValues() ) { pageContext.setAttribute("enumValue", value)
getJspBody().invoke(getOut())
}
} (Exception e) { throw new JspException(e) }
}
B.public void doTag() throw JspException {
try {
for ( Enum value : getEnumValues() ) { getJspContext().setAttribute("enumValue", value)
getJspBody().invoke(null)
}
} (Exception e) { throw new JspException(e) }
}
C.public void doTag() throw JspException {
try {
for ( Enum value : getEnumValues() ) { getJspContext().setAttribute("enumValue", value)
getJspBody().invoke(getJspContext().getWriter())
}
} (Exception e) { throw new JspException(e) }
}
D.public void doTag() throw JspException {
try {
for ( Enum value : getEnumValues() ) { pageContext.setAttribute("enumValue", value)
getJspBody().invoke(getJspContext().getWriter())
}
} (Exception e) { throw new JspException(e) }
}
Answer:B
3.Which two are characteristics of the Service Locator pattern? (Choose two.)
A.It encapsulates component lookup procedures.
B.It increases source code duplication and decreases reuse.
C.It improves client performance by caching context and factory objects.
D.It degrades network performance due to increased access to distributed lookup services.
Answer:A, C
4.Which three are valid URL mappings to a servlet in a web deployment descriptor? (Choose three.)
A.*/*
B.*.do
C.MyServlet
D./MyServlet
E./MyServlet/*
F.MyServlet/*.jsp
Answer:B, D, E
5.Which two are true regarding a web application class loader? (Choose two.)
A.A web application may override the web container's implementation classes.
B.A web application running in a J2EE product may override classes in the javax.* namespace.
C.A web application class loader may NOT override any classes in the java.* and javax.* namespaces.
D.Resources in the WAR class directory or in any of the JAR files within the library directory may be accessed
14: }
15: }
Click the Exhibit button .
The Appliance class is a Singleton that loads a set of properties into a Map from an external data source.
Assume:
? An instance of the Appliance class exists in the applicationscoped attribute, appl
? The appliance object includes __________________________________
the name property that _________________________________________ maps to the value Cobia
? The requestscoped attribute, prop, has the value name.
Which two EL code snippets will display the string Cobia? (Choose two.)
A.${appl.properties.name}
B.${appl.properties.prop}
C.${appl.properties[prop]}
D.${appl.properties[name]}
E.${appl.getProperties().get(prop)}
F.${appl.getProperties().get('name')}
Answer:A, C
12.1: package com:example
2:
3: public class Product {
4: private String name
5: private double price
6:
7: public Product() {
8: this( "Default", 0:0 )
9: }
10:
11: public Product( String name, double price ) {
12: this:name = name
13: this:price = price
14: }
15:
16: public String getName() {
17: return name
18: }
19:
20: public void setName(String name) {
21: this:name = name
22: }
23:
24: public double getPrice() {
25: return price
26: }
27:
28: public void setPrice(double price) {
29: this:price = price
30: }
31: }
Click the Exhibit button. Given:
10: <form action='create_product.jsp'>
<ul>
<c:forTokens items'${dataString}' delims=',' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
Answer:D
21.In a JSPcentric shopping cart application, you need to
move a client's home address of the Customer object into the shipping address of the Order object. The
address data is stored in a value object class called Address with properties for: street address, city,
province, country, and postal code.
Which two JSP code snippets can be used to accomplish this goal? (Choose two.)
A. <c:set var='order' property='shipAddress'
value='${client.homeAddress}' />
B. <c:set target='${order}'
property='shipAddress
'
value='${client.homeAddress}' />
C. <jsp:setProperty name='${order}' property='shipAddress'
value='${client.homeAddress}' />
D. <c:set var='order' property='shipAddress'>
<jsp:getProperty name='client' property='homeAddress' />
</c:store>
E. <c:set target='${order}' property='shipAddress'>
<jsp:getProperty name='client' property='homeAddress' />
</c:set>
F. <c:setProperty name='${order}' property='shipAddress'>
<jsp:getProperty name='client' property='homeAddress' />
</c:setProperty>
Answer:B, E
22.Given:
10: public void service(ServletRequest request,
11: ServletResponse response) {
12: ServletInputStream sis =
13: // insert code here
14: }
binary input stream on line 13?
A. request.getWriter()
B. request.getReader()
C. request.getInputStream()
D. request.getResourceAsStream()
E. request.getResourceAsStream(ServletRequest.REQUEST)
Answer:C
23.You need to retrieve the username cookie from an HTTP request. If this cookie does NOT exist, then the c
variable will be null.
Which code snippet must be used to retrieve this cookie object?
C. response.getOutputWriter()
D. response.getWriter().getOutputStream()
E. response.getWriter(Writer.OUTPUT_TEXT)
Answer:A, B
27.Given an HttpServletRequest request and HttpServletResponse response, which sets a cookie "username"
with the value "joe" in a servlet?
A. request.addCookie("username", "joe")
B. request.setCookie("username", "joe")
C. response.addCookie("username", "joe")
D. request.addHeader(new Cookie("username", "joe"))
E. request.addCookie(new Cookie("username", "joe"))
F. response.addCookie(new Cookie("username", "joe"))
G. response.addHeader(new Cookie("username", "joe"))
Answer:F
28.Your company has a corporate policy that prohibits storing a customer's credit card number in any
corporate database. However, users have complained that they do NOT want to reenter their credit card
number for each transaction. Your management has decided to use clientside cookies to record the user's
credit card number for 120 days. Furthermore, they also want to protect this information during transit from
the web browser to the web container so the cookie must only be transmitted over HTTPS.
Which code snippet creates the "creditCard" cookie and dds it to the out going response to be stored on the
user's web browser?
A. 10: Cookie c = new Cookie("creditCard", usersCard)
11: c.setSecure(true)
12: c.setAge(10368000)
13: response.addCookie(c)
B. 10: Cookie c = new Cookie("creditCard", usersCard)
11: c.setHttps(true)
12: c.setMaxAge(10368000)
13: response.setCookie(c)
C. 10: Cookie c = new Cookie("creditCard", usersCard)
11: c.setSecure(true)
12: c.setMaxAge(10368000)
13: response.addCookie(c)
D. 10: Cookie c = new Cookie("creditCard", usersCard)
11. c.setHttps(true)
12: c.setAge(10368000)
13: response.addCookie(c)
E. 10: Cookie c = new Cookie("creditCard", usersCard)
11: c.setSecure(true)
12: c.setAge(10368000)
13: response.setCookie(c)
Answer:C
29.You are creating a servlet that generates stock market graphs. You want to provide the web browser with
precise information about the amount of data being sent in the response stream.
Which two HttpServletResponse methods will
you use to provide this information? (Choose two.)
A. response.setLength(numberOfBytes)
B. response.setContentLength(numberOfBytes)
C. response.setHeader("Length", numberOfBytes)
D. response.setIntHeader("Length", numberOfBytes)
E. response.setHeader("ContentLength", numberOfBytes)
F. response.setIntHeader("ContentLength", numberOfBytes)
Answer:B, F
30.Which two prevent a servlet from handling requests? (Choose two.)
A. The servlet's init method returns a nonzero status.
B. The servlet's init method throws a ServletException.
C. The servlet's init method sets the ServletResponse's content length to 0.
D. The servlet's init method sets the ServletResponse's content type to null.
E. The servlet's init method does NOT return within a time period defined by the servlet container.
Answer: B, E
31.Given an HttpSession session, a ServletRequest request, and a ServletContext context, which retrieves a
URL to /WEBINF/myconfig.xml within a web application?
A. session.getResource("/WEBINF/myconfig.xml")
B. request.getResource("/WEBINF/myconfig.xml")
C. context.getResource("/WEBINF/myconfig.xml")
D. getClass().getResource("/WEBINF/myconfig.xml")
Answer:C
32.1: package com.example
2:
3: import javax.servlet.http.*
4:
5: public class MyWebDAV extends HttpServlet {
6: private String resourceDirectory
7:
8: public MyWebDAV(String resDir) {
9: this.resourceDirectory = resDir
10: }
11: public void doPut(HttpServletRequest req,
12: HttpServletResponse resp) {
13: // store file to resourceDirectory (code not shown)
20: }
21: public void doDelete(HttpServletRequest req,
22: HttpServletResponse resp) {
23: // remove file from resourceDirectory (code not shown)
30: }
31: }
Click the Exhibit button.
As a maintenance feature, you have created this servlet to allow you to upload and remove files on your web
server.
Unfortunately, while testing this servlet, you try to upload a file using an HTTP request and on this servlet,
the web container returns a 404 status.
What is wrong with this servlet?
A. HTTP does NOT support file upload operations.
B. The servlet constructor must NOT have any parameters.
C. The servlet needs a service method to dispatch the requests to the helper methods.
D. The doPut and doDelete methods do NOT map to the proper HTTP methods.
Answer: B
ability to repopulate the form field with the request parameters from the user's last request. For example, if
the user entered "Samantha" in the text field called firstName, then the form is repopulated like this:
<input type='text' name='firstName' value='Samantha' />
Which tag handler method will accomplish this goal?
A. public int doStartTag() throws JspException { JspContext ctx = getJspContext()
String value = ctx.getParameter(this.name)
if ( value == null ) value = ""
JspWriter out = pageContext.getOut()
try {
out.write(String.format(INPUT, this.name, value))
} (Exception e) { throw new JspException(e) }
return SKIP_BODY
}
private static String INPUT
= "<input type='text' name='%s' value='%s' />"
B. public void doTag() throws JspException { JspContext ctx = getJspContext()
String value = ctx.getParameter(this.name)
if ( value == null ) value = ""
JspWriter out = pageContext.getOut()
try {
out.write(String.format(INPUT, this.name, value))
} (Exception e) { throw new JspException(e) }
}
private static String INPUT
= "<input type='text' name='%s' value='%s' />"
C. public int doStartTag() throws JspException {
ServletRequet request = pageContext.getRequest()
String value =
request
.getParameter(this.name)
if ( value == null ) value = ""
JspWriter out = pageContext.getOut()
try {
out.write(String.format(INPUT, this.name, value))
} (Exception e) { throw new JspException(e) }
return SKIP_BODY
}
private static String INPUT
= "<input type='text' name='%s' value='%s' />"
D. public void doTag() throws JspException {
ServletRequet request = pageContext.getRequest() String value = request.getParameter(this.name)
if ( value == null ) value = ""
JspWriter out = pageContext.getOut()
try {
out.write(String.format(INPUT, this.name, value))
} (Exception e) { throw new JspException(e) }
}
private static String INPUT
= "<input type='text' name='%s' value='%s' />"
Answer:C
40.The tl:taskList and tl:task tags output a set of tasks to the response and are used as follows:
11: <tl:taskList>
the tag handler for n:recurse to output the nesting depth of the deepest n:recurse tag?
A. It is impossible to determine the deepest nesting depth because it is impossible for tag handlers that
extend SimpleTagSupport to communicate with their parent and child tags.
B. Create a private nonstatic attribute in the tag handler class called count of type int initialized to 0.
Increment count in the doTag method. If the tag has a body, invoke the fragment for that body. Otherwise,
output the value of count.
C. Start a counter at 1. Call getChildTags(). If it returns null, output the value of the counter. Otherwise,
increment counter and continue from where getChildTags() is called. Skip processing of the body.
D. If the tag has a body, invoke the fragment for that body.Otherwise, start a counter at 1. Call getParent().
If it returns null, output the value of the counter Otherwise, increment the counter and continue from where
getParent() is called.
Answer: D
43.You are creating a content management system (CMS) with a web application frontend. The JSP that
displays a given document in the CMS has the following general structure:
1: <% tag declaration %>
2: <t:document>
...
11: <t:paragraph>... <t:citation docID='xyz' /> ...</t:paragraph>
...
99: </t:document>
The citation tag must store information in the document tag for the document tag to generate a reference
section at the end of the generated web page.
The document tag handler follows the Classic tag model and the citation tag handler follows the Simple tag
model. Furthermore, the citation tag could also be embedded in other custom tags that could have either the
Classic or Simple tag handler model.
Which tag handler method allows the citation tag to access the document tag?
A. public void doTag() {
JspTag docTag = findAncestorWithClass(this, DocumentTag.class)
((DocumentTag)docTag).addCitation(this.docID)
}
B. public void doStartTag() {
JspTag docTag = findAncestorWithClass(this, DocumentTag.class)
((DocumentTag)docTag).addCitation(this.docID)
}
C. public void doTag() {
Tag docTag = findAncestor(this, DocumentTag.class) ((DocumentTag)docTag).addCitation(this.docID)
}
D. public void doStartTag() {
Tag docTag = findAncestor(this, DocumentTag.class) ((DocumentTag)docTag).addCitation(this.docID)
}
Answer: A
44.Assume the tag handler for a st:simple tag extends SimpleTagSupport.
In what way can scriptlet code be used in the body of st:simple?
A. set the body content type to JSP in the TLD
B. Scriptlet code is NOT legal in the body of st:simple.
C. add scriptingenabled="true" to the start tag for the st:simple element
D. add a passthrough Classic tag with a body content type of JSP to the body of st:simple, and place the
scriptlet code in the body of that tag
Answer: B
45.
1:
2:
3:
7: 1.0
8: h
9: http://example.com/tld/highlight
10:
11: highlight
12: com.example.HighlightTag
13: scriptless
14:
15: color
16: true
17:
18: true
19:
20:
Click the Exhibit button.
The h:highlight tag renders its body, highlighting an arbitrary number of words, each of which is passed as
an attribute (word1, word2, ...). For example, a JSP page can invoke the h:highlight tag as follows:
11: <h:highlight color="yellow" word1="high" word2="low">
12: high medium low
13: </h:highlight>
Given that HighlightTag extends SimpleTagSupport, which three steps are necessary to implement the tag
handler for the highlight tag? (Choose three).
A. add a doTag method
B. add a doStartTag method
C. add a getter and setter for the color attribute
D. create and implement a TagExtraInfo class
E. implement the DynamicAttributes interface
F. add a getter and setter for the word1 and word2 attributes
Answer: A, C, E
46.You are building a web application that will be used throughout the European Union therefore, it has
significant internationalization requirements. You have been tasked to create a custom tag that generates a
message using the java.text.MessageFormat class. The tag will take the resourceKey attribute and a variable
number of argument attributes with the format, arg<N>. Here is an example use of this tag and its output:
<t:message resourceKey='diskFileMsg' arg0='MyDisk' arg1='1247' />
generates:
The disk "MyDisk" contains 1247 file(s).
Which Simple tag class definition accomplishes this goal of handling a variable number of tag attributes?
A. public class MessageTag extends SimpleTagSupport implements VariableAttributes {
private Map attributes = new HashMap() public void setVariableAttribute(String uri, String name, Object
value) {
this.attributes.put(name, value)
}
// more tag handler methods
}
B. The Simple tag model does NOT support a variable number of attributes.
C. public class MessageTag extends SimpleTagSupport
implements DynamicAttributes {
private Map attributes = new HashMap()
E. scriptless
F. tagdependent
Answer:C, E, F
Q25.You need to store a Java long primitive attribute, called customerOID, into the
session scope. Which two code snippets allow you to insert this value into the session?
(Choose two.)
A. long customerOID = 47L;
session.setAttribute("customerOID", new Long(customerOID));
B. long customerOID = 47L;
session.setLongAttribute("customerOID", new Long(customerOID));
C. long customerOID = 47L;
session.setAttribute("customerOID", customerOID);
D. long customerOID = 47L;
session.setNumericAttribute("customerOID", new Long(customerOID));
E. long customerOID = 47L;
session.setLongAttribute("customerOID", customerOID);
F. long customerOID = 47L;
session.setNumericAttribute("customerOID", customerOID);
Answer: A, C
Q26. Your web application uses a simple architecture in which servlets handle
requests and then forward to a JSP using a request dispatcher. You need to pass
information calculated in the servlet to the JSP for view generation. This information
must NOT be accessible to any other servlet, JSP or session in the webapp. Which two
techniques can you use to accomplish this goal?
(Choose two.)
A. Add attributes to the session object. B. Add attributes on the request object.
C. Add parameters to the request object.
D. Use the pageContext object to add request attributes.
E. Add parameters to the JSP's URL when generating the request dispatcher.
Answer: B, E
Q 27. Which three are true about servlet filters? (Choose three.)
A. A filter must implement the destroy method.
B. A filter must implement the doFilter method.
C. A servlet may have multiple filters associated with it.
D. A servlet that is to have a filter applied to it must implement the javax.servlet.
FilterChain interface.
E. A filter that is part of a filter chain passes control to the next filter in the chain by
invoking the FilterChain.forward method.
F. For each <filter> element in the web application deployment descriptor, multiple
instances of a filter may be created by the web container.
Answer: A, B, C
Q1.Servlet A receives a request that it forwards to servlet B within another web
application in the same web container. Servlet A needs to share data with servlet B
and that data must not be visible to other servlets in A's web application. In which
object can the data that A shares with B
be stored?
A. HttpSession
C. ServletContext
E. HttpServletResponse
B. ServletConfig
D. HttpServletRequest
Answer: D
Q2.our web site has many user-customizable features, for example font and color
preferences on web pages. Your IT department has already built a subsystem for user
preferencessing the Java SE platform's lang.util.prefs package APIs, and you have
been ordered to reuse this subsystem in your web application. You need to create an
event listener that constructs the preferences actory and stores it in the application
scope for later use. Furthermore, this factory requires that the URL to a database
must be declared in the deployment descriptor like this:
42. <context-param>
43. <param-name>prefsDbURL</param-name>
44. <param-value>
45. jdbc:pointbase:server://dbhost:4747/prefsDB
46. </param-value>
47. </context-param>
Which partial listener class will accomplish this goal?
A. public class PrefsFactoryInitializer implements ContextListener {
public void contextInitialized(ServletContextEvent e) {
ServletContext ctx = e.getContext();
String prefsURL = ctx.getParameter("prefsDbURL");
PreferencesFactory myFactory = makeFactory(prefsURL);
ctx.putAttribute("myPrefsFactory", myFactory);
}
// more code here
}
B. public class PrefsFactoryInitializer implements ServletContextListener {
public void contextCreated(ServletContext ctx) {
String prefsURL = ctx.getInitParameter("prefsDbURL");
PreferencesFactory myFactory = makeFactory(prefsURL);
ctx.setAttribute("myPrefsFactory", myFactory);
}
// more code here
}
C. public class PrefsFactoryInitializer implements ServletContextListener {
public void contextInitialized(ServletContextEvent e) {
ServletContext ctx = e.getServletContext();
String prefsURL = ctx.getInitParameter("prefsDbURL");
PreferencesFactory myFactory = makeFactory(prefsURL);
ctx.setAttribute("myPrefsFactory", myFactory);
}
// more code here
}
D. public class PrefsFactoryInitializer implements ContextListener {
public void contextCreated(ServletContext ctx) {
String prefsURL = ctx.getParameter("prefsDbURL");
PreferencesFactory myFactory = makeFactory(prefsURL);
ctx.putAttribute("myPrefsFactory", myFactory);
}
// more code here
}
Answer: C
Q3.developer wants a web application to be notified when the application is about to
be shut down. Which two actions are necessary to accomplish this goal? (Choose two.)
A. include a listener directive in a JSP page
B. configure a listener in the TLD file using the <listener> element
C. include a <servlet-destroy> element in the web application deployment descriptor
D. configure a listener in the application deployment descriptor, using the <listener>
element
E. include a class implementing ServletContextListener as part of the web application
deployment
F. include a class implementing ContextDestroyedListener as part of the web application
deployment
G. include a class implementing HttpSessionAttributeListener as part of the web
application deployment
Answer: D, E
Q4.You want to create a filter for your web application and your filter will
implement javax.servlet.Filter.
Which two statements are true? (Choose two.)
A. Your filter class must implement an init method and a destroy method.
B. Your filter class must also implement javax.servlet.FilterChain.
C. When your filter chains to the next filter, it should pass the same arguments it received
in its doFilter method.
D. The method that your filter invokes on the object it received that implements
javax.servlet.FilterChain can invoke either another filter or a servlet.
E. Your filter class must implement a doFilter method that takes, among other things, an
HTTPServletRequest object and an HTTPServletResponse object.
Answer: A, D
Q5.Which three are true about the HttpServletRequestWrapper class? (Choose three.)
A. The HttpServletRequestWrapper is an example of the Decorator pattern.
B. The HttpServletRequestWrapper can be used to extend the functionality of a servlet
request.
C. A subclass of HttpServletRequestWrapper CANNOT modify the behavior of the
getReader method.
D. An HttpServletRequestWrapper may be used only by a class implementing the
javax.servlet.Filter interface.
E. An HttpServletRequestWrapper CANNOT be used on the request passed to the
RequestDispatcher.include method.
F. An HttpServletRequestWrapper may modify the header of a request within an object
implementing the javax.servlet.Filter interface.
Answer: A, B, F
Q6.A developer wants to make a name attribute available to all servlets
associated with a particular user, across multiple requests from that user, from the
same browser instance.
Which two provide this capability from within a tag handler? (Choose two.)
A. pageContext.setAttribute("name", theValue);
B. pageContext.setAttribute("name", getSession());
C. pageContext.getRequest().setAttribute("name", theValue);
D. pageContext.getSession().setAttribute("name", theValue);
E. pageContext.setAttribute("name", theValue,
PageContext.PAGE_SCOPE);
F. pageContext.setAttribute("name", theValue,
PageContext.SESSION_SCOPE);
Answer: D, F
Q7.Click the Exhibit button.
The resource requested by the RequestDispatcher is available and implemented by the
DestinationServlet.
What is the result?
19. session.getAttribute("myAttribute"));
20. }
21. }
What is the result when a request is sent to MyServlet?
A. An IllegalStateException is thrown at runtime.
B. An InvalidSessionException is thrown at runtime.
C. The string "value=null" appears in the response stream.
D. The string "value=myAttributeValue" appears in the response stream.
Answer: A
Q9.You need to store a Java long primitive attribute, called customerOID, into the
session scope. Which two code snippets allow you to insert this value into the session?
(Choose two.)
A. long customerOID = 47L;
session.setAttribute("customerOID", new Long(customerOID));
B. long customerOID = 47L;
session.setLongAttribute("customerOID", new Long(customerOID));
C. long customerOID = 47L;
session.setAttribute("customerOID", customerOID);
D. long customerOID = 47L;
session.setNumericAttribute("customerOID", new Long(customerOID));
E. long customerOID = 47L;
session.setLongAttribute("customerOID", customerOID);
F. long customerOID = 47L;
session.setNumericAttribute("customerOID", customerOID);
Answer: A, C
Q10.Your web application requires the adding and deleting of many session attributes
during a complex use case. A bug report has come in that indicates that an important
session attribute is being deleted too soon and a NullPointerException is being thrown
several interactions after the fact. You have decided to create a session event listener
that will log when attributes are being deleted so you can track down when the
attribute is erroneously being deleted.
Which listener class will accomplish this debugging goal?
A. Create an HttpSessionAttributeListener class and implement the attributeDeleted method
and log the attribute name using the getName method on the event object.
A. request.setAttribute("orderID", orderID);
request.setAttribute("jspURL", jspURL);
RequestDispatcher view
= context.getRequestDispatcher("/WEB-INF/retreiveOrder.do");
view.forward(request, response);
B. request.setParameter("orderID", orderID);
request.setParameter("jspURL", jspURL);
Dispatcher view
= request.getDispatcher("/WEB-INF/retreiveOrder.do");
view.forwardRequest(request, response);
C. String T="/WEB-INF/retreiveOrder.do?orderID=%d&jspURL=%s";
String url = String.format(T, orderID, jspURL);
RequestDispatcher view
= context.getRequestDispatcher(url);
view.forward(request, response);
D. String T="/WEB-INF/retreiveOrder.do?orderID=%d&jspURL=%s";
String url = String.format(T, orderID, jspURL);
Dispatcher view = context.getDispatcher(url);
view.forwardRequest(request, response);
Answer: C
Q13.You want to create a filter for your web application and your filter will
implement javax.servlet.Filter.
Which two statements are true? (Choose two.)
A. Your filter class must implement an init method and a destroy method.
B. Your filter class must also implement javax.servlet.FilterChain.
C. When your filter chains to the next filter, it should pass the same arguments it received
in its doFilter method.
D. The method that your filter invokes on the object it received that implements
javax.servlet.FilterChain can invoke either another filter or a servlet.
E. Your filter class must implement a doFilter method that takes, among other things, an
HTTPServletRequest object and an HTTPServletResponse object.
Answer: A, D
Q14. Given the web application deployment descriptor elements:
11. <filter>
12. <filter-name>ParamAdder</filter-name>
13. <filter-class>com.example.ParamAdder</filter-class>
14. </filter>
...
24. <filter-mapping>
25. <filter-name>ParamAdder</filter-name>
26. <servlet-name>MyServlet</servlet-name>
27. <!-- insert element here -->
28. </filter-mapping>
Which element, inserted at line 27, causes the ParamAdder filter to be applied when
MyServlet is invoked by another servlet using the RequestDispatcher.include method?
A. <include/>
B. <dispatcher>INCLUDE</dispatcher>
C. <dispatcher>include</dispatcher>
D. <filter-condition>INCLUDE</filter-condition>
E. <filter-condition>include</filter-condition>
Answer: B
Q15. Your web application uses a simple architecture in which servlets handle
requests and then forward to a JSP using a request dispatcher. You need to pass
information calculated by the servlet to the JSP; furthermore, that JSP uses a custom
tag and must also process this information. This information must NOT be accessible
to any other servlet, JSP or session in the webapp. How can you accomplish this goal?
A. Store the data in a public instance variable in the servlet.
B. Add an attribute to the request object before using the request dispatcher.
C. Add an attribute to the context object before using the request dispatcher.
D. This CANNOT be done as the tag handler has no means to extract this data.
Answer: B
Q16. A developer chooses to avoid using SingleThreadModel but wants to ensure that
data is updated in a thread-safe manner. Which two can support this design goal?
(Choose two.)
A. Store the data in a local variable.
B. Store the data in an instance variable.
C. Store the data in the HttpSession object.
D. Store the data in the ServletContext object.
E. Store the data in the ServletRequest object.
Answer: A, E
Q17. Your web application uses a simple architecture in which servlets handle
requests and then forward to a JSP using a request dispatcher. You need to pass
information calculated in the servlet to the JSP for view generation. This information
must NOT be accessible to any other servlet, JSP or session in the webapp. Which two
techniques can you use to accomplish this goal?(Choose two.)
A. Add attributes to the session object.
B. Add attributes on the request object.
C. Add parameters to the request object.
D. Use the pageContext object to add request attributes.
E. Add parameters to the JSP's URL when generating the request dispatcher.
Answer: B
Q18. Given:
String value = getServletContext().getInitParameter("foo");
in an HttpServlet and a web application deployment descriptor that contains:
<context-param>
<param-name>foo</param-name>
<param-value>frodo</param-value>
</context-param>
Which two are true? (Choose two.)
A. The foo initialization parameter CANNOT be set programmatically.
B. Compilation fails because getInitParameter returns type Object.
C. The foo initialization parameter is NOT a servlet initialization parameter.
D. Compilation fails because ServletContext does NOT have a getInitParameter method.
E. The foo parameter must be defined within the <servlet> element of the deployment
descriptor.
F. The foo initialization parameter can also be retrieved using
getServletConfig().getInitParameter("foo").
Answer: A, C
Q19. Click the Exhibit button. Given the web application deployment descriptor
elements:
11. <filter>
12. <filter-name>ParamAdder</filter-name>
13. <filter-class>com.example.ParamAdder</filter-class>
14. </filter>
31. <filter-mapping>
32. <filter-name>ParamAdder</filter-name>
33. <servlet-name>Destination</servlet-name>
34. </filter-mapping>
...
55. <servlet-mapping>
56. <servlet-name>Destination</servlet-name>
57. <url-pattern>/dest/Destination</url-pattern>
58. </servlet-mapping>
What is the result of a client request of the Source servlet with no query string?
Answer: A
Q20.Given a Filter class definition with this method:
21. public void doFilter(ServletRequest request,
22. ServletResponse response,
23. FilterChain chain)
24. throws ServletException, IOException {
25. // insert code here
26. }
Which should you insert at line 25 to properly invoke the next filter in the chain, or
the target servlet if there are no more filters?
A. chain.forward(request, response);
B. chain.doFilter(request, response);
C. request.forward(request, response);
D. request.doFilter(request, response);
Answer: B
Q21. Servlet A forwarded a request to servlet B using the forward method of
RequestDispatcher. What attribute in B's request object contains the URI of the
original request received by servlet A?
A. REQUEST_URI
B. javax.servlet.forward.request_uri
C. javax.servlet.forward.REQUEST_URI
D. javax.servlet.request_dispatcher.request_uri
E. javax.servlet.request_dispatcher.REQUEST_URI
Answer: B
Q22.One of the use cases in your web application uses many session-scoped attributes.
At the end of the use case, you want to clear out this set of attributes from the session
object. Assume that this static variable holds this set of attribute names:
201. private static final Set<String> USE_CASE_ATTRS;
202. static {
203. USE_CASE_ATTRS.add("customerOID");
204. USE_CASE_ATTRS.add("custMgrBean");
205. USE_CASE_ATTRS.add("orderOID");
206. USE_CASE_ATTRS.add("orderMgrBean");
207. }
Which code snippet deletes these attributes from the session object?
A. session.removeAll(USE_CASE_ATTRS);
B. for ( String attr : USE_CASE_ATTRS ) {
session.remove(attr);
}
C. for ( String attr : USE_CASE_ATTRS ) {
session.removeAttribute(attr);
}
D. for ( String attr : USE_CASE_ATTRS ) {
session.deleteAttribute(attr); }
E. session.deleteAllAttributes(USE_CASE_ATTRS);
Answer: C
Q23. You need to store a floating point number, called Tsquare, in the session scope.
Which two code snippets allow you to retrieve this value? (Choose two.)
A. float Tsquare = session.getFloatAttribute("Tsquare");
B. float Tsquare = (Float) session.getAttribute("Tsquare");
C. float Tsquare = (float) session.getNumericAttribute("Tsquare");
D. float Tsquare = ((Float) session.getAttribute.("Tsquare")).floatValue();
E. float Tsquare = ((Float) session.getFloatAttribute.("Tsquare")).floatValue;
F. float Tsquare = ((Float) session.getNumericAttribute.("Tsquare")).floatValue;
Answer: B, D
Q24. You need to store a floating point number, called Tsquare, in the session scope.
Which two code snippets allow you to retrieve this value? (Choose two.)
A. float Tsquare = session.getFloatAttribute("Tsquare");
B. float Tsquare = (Float) session.getAttribute("Tsquare");
C. float Tsquare = (float) session.getNumericAttribute("Tsquare");
D. float Tsquare = ((Float) session.getAttribute.("Tsquare")).floatValue();
E. float Tsquare = ((Float) session.getFloatAttribute.("Tsquare")).floatValue;
F. float Tsquare = ((Float) session.getNumericAttribute.("Tsquare")).floatValue;
Answer: B, D
Q 28. Click the Task button.
Place the XML elements in the web application deployment descriptor solution to
Answers:
<listener>
<listener-class>com.example.MyListener< listener-class>
</listener>
Q 29. Which is true about the web container request processing model?
A. The init method on a filter is called the first time a servlet mapped to that filter is
invoked.
B. A filter defined for a servlet must always forward control to the next resource in the
filter chain.
C. Filters associated with a named servlet are applied in the order they appear in the web
application deployment descriptor file.
D. If the init method on a filter throws an UnavailableException, then the container will
make no further attempt to execute it.
Answer: C