Nearby lessons

26 of 34

Servlet - MCQ Quiz (Question Bank)

📌 What You Will Learn
  • Test your knowledge across all the servlet units
  • Practise the OCWCD-style question bank
  • Find out which topics need more revision

Test yourself with the complete Servlet MCQ quiz — questions from the OCWCD question bank covering the servlet model, web.xml, the web container, session management and security.

Exam Objectives

  • For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method. Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request. Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response. Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.
  • Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (d) JAR files, and (e) Java class files; and describe how to protect resource files from HTTP access.
  • Describe the purpose and semantics of the deployment descriptor.
  • Construct the correct structure of the deployment descriptor. Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed
  • For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters. 2.For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope.
  • Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.
  • Describe the Web container life cycle event model for requests, sessions, and web applications;create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.
  • Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.
  • String key = "com.example.data";
  • session.setAttribute(key, "Hello");
  • 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.)
  • 1) Write servlet code to store objects into a session object and retrieve objects from a session object.
  • 2) Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.
  • 3) Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.
  • 4) Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.
  • Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality.
  • In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.
  • Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type.
  • Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality.
  • In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.
  • Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type.

Ordering Questions

Q10. Click the Task button. Place the events in the order they occur.

  1. 1st:web container loads the servlet class.
  2. 2nd:web container instantiates the servlet
  3. 3rd. web container calls the servlets init() method.
  4. 4th: web container calls the servlets service() method.'
  5. 5th: web container calls the servlets destroy() methos.

Q13. Click the Task button. Given a request from mybox.example.com, with an IP address of 10.0.1.11 on port 33086, place theappropriate ServletRequest methods onto their corresponding return values.

  1. Mybox.example.com : getRemoteHost
  2. 10.0.1.11 : getRemoteAddr

Q16. Click the Task button. Given a servlet mapped to /control, place the correct URI segment returned as a String on the corresponding HttpServletRequest method call for the URI: /myapp/control/processorder.

  1. getServletpath( ) --------/processorder
  2. getPathInfo ( ) ----- /Control
  3. getContext ( ) ----- /myapp

Q2. Click the Task button. Place the appropriate element names on the left on the web application deployment descriptor on the right so that files ending in ".mpg" are associated with the MIME type "video/mpeg."

  1. <mime-mapping>
  2. <mime-type>mpg</mime-type>
  3. <extension>vedio/mpeg</extension>
  4. </mime-mapping>

Q7.Click the Task button. Given a servlet mapped to /control, place the correct URI segment returned as a String on thecorresponding HttpServletRequest method call for the URI: /myapp/control/processorder.

  1. getServletPath()--->/control
  2. getPathInfo() --->/processorder
  3. getContext()---->/myapp

Q16. Click the Task button. Place the corresponding resources and directories in the proper web application deployment structure.

  1. WEB-INF
  2. Classses
  3. Java and Servlet classes
  4. Lib
  5. JAR Files
  6. web.xml

Q 25. Click the Task button. Place the servlet name onto every request URL, relative to the web application context root, that will invoke that servlet. Every request URL must be filled.

  1. /data/ --->DataServlet
  2. /data/index.jsp --->DataServlet
  3. /secure/command.do --->ControlServlet
  4. /data/command.do --->DataServlet
  5. /data.do --->ControlServlet

Q 28. Click the Task button. Place the XML elements in the web application deployment descriptor solution to configure a servlet context event listener named com.example.MyListener.

  1. <listener>
  2. <listener-class>com.example.MyListener</listener-class>
  3. </listener>

Unit-1: The Servlet Technology Model

Which HTTP method is used when sending this request from the browser?

A. GET B. PUT

C. POST D. SEND

E. FORM

Answer: A

Q2. Given a header in an HTTP request: X-Retries: 4

Which two retrieve the value of the header from a given HttpServletRequest request? (Choose

two.)

A. request.getHeader("X-Retries")

B. request.getIntHeader("X-Retries")

C. request.getRequestHeader("X-Retries")

D. request.getHeaders("X-Retries").get(0)

E. request.getRequestHeaders("X-Retries").get(0)

Answer: A, B

Q3. For a given ServletResponse response, which two retrieve an object for

writing text data? (Choose two.)

A. response.getWriter()

B. response.getOutputStream()

C. response.getOutputWriter()

D. response.getWriter().getOutputStream()

E. response.getWriter(Writer.OUTPUT_TEXT)

Answer: A, B

Q4. 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

Q5. Your web page includes a Java SE v1.5 applet with the following declaration:

Example03
JCode Cell
1 
2<form action="sendOrder.jsp">
3<input type="text" name="creditCard">
4<input type="text" name="expirationDate">
5<input type="submit">
6</form>
7

Unit-1: The Servlet Technology Model

Which HTTP method is used to retrieve the applet code?

A. GET B. PUT

C. POST D. RETRIEVE

Answer: A

Q6. 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("Content-Length", numberOfBytes);

F. response.setIntHeader("Content-Length", numberOfBytes);

Answer: B, F

Q7. 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?

A. 10. Cookie c = request.getCookie("username");

B. 10. Cookie c = null;

Example04
JCode Cell
1 
2<object classid='clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA'
3width='200' height='200'>
4<param name='code' value='Applet.class' />
5</object>
6

Unit-1: The Servlet Technology Model

C. 10. Cookie c = null;

Example05
JCode Cell
1 
2for ( Iterator i = request.getCookies();
3i.hasNext(); ) {
4Cookie o = (Cookie) i.next();
5if ( o.getName().equals("username") ) {
6c = o;
7break;
8}
9}
10

Unit-1: The Servlet Technology Model

D. 10. Cookie c = null;

Example06
JCode Cell
1 
2for ( Enumeration e = request.getCookies();
3e.hasMoreElements(); ) {
4Cookie o = (Cookie) e.nextElement();
5if ( o.getName().equals("username") ) {
6c = o;
7break;
8}
9}
10

Unit-1: The Servlet Technology Model

Answer: D

Q8. Given:

Example07
JCode Cell
1 
2Cookie[] cookies = request.getCookies();
3for ( int i = 0; i < cookies.length; i++ ) {
4if ( cookies[i].getName().equals("username") ) {
5c = cookies[i];
6break;
7}
8}
9

Unit-1: The Servlet Technology Model

Which retrieves the 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

Q9. 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

Q10. Click the Task button.

Place the events in the order they occur.

Answer:

1st:web container loads the servlet class.

2nd:web container instantiates the servlet

3rd. web container calls the servlets init() method.

4th: web container calls the servlets service() method.'

5th: web container calls the servlets destroy() methos.

Q11. For an HttpServletResponse response, which two create a custom header?(Choose two.)

A. response.setHeader("X-MyHeader", "34");

B. response.addHeader("X-MyHeader", "34");

C. response.setHeader(new HttpHeader("X-MyHeader", "34"));

D. response.addHeader(new HttpHeader("X-MyHeader", "34"));

E. response.addHeader(new ServletHeader("X-MyHeader", "34"));

F. response.setHeader(new ServletHeader("X-MyHeader", "34"));

Answer: A, B

Q12 .You need to create a servlet filter that stores all request headers to a

database for all requests to the web application's home page "/index.jsp". Which

HttpServletRequest method allows you to retrieve all of the request headers?

A. String[] getHeaderNames()

B. String[] getRequestHeaders()

C. java.util.Iterator getHeaderNames()

D. java.util.Iterator getRequestHeaders()

E. java.util.Enumeration getHeaderNames()

F. java.util.Enumeration getRequestHeaders()

Answer: E

Q13. Click the Task button.

Given a request from mybox.example.com, with an IP address of 10.0.1.11 on port 33086, place

theappropriate ServletRequest methods onto their corresponding return values.

Answer: :

Mybox.example.com : getRemoteHost

10.0.1.11 : getRemoteAddr

Q: 14 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

Q15. Which retrieves all cookies sent in a given HttpServletRequest request?

A. request.getCookies()

B. request.getAttributes()

C. request.getSession().getCookies()

D. request.getSession().getAttributes()

Answer: A

Q16. Click the Task button.

Given a servlet mapped to /control, place the correct URI segment returned as a String on the

corresponding HttpServletRequest method call for the URI: /myapp/control/processorder.

Answer: :

getServletpath( ) --------/processorder

getPathInfo ( ) ----- /Control

getContext ( ) ----- /myapp

Q17. 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

Answer: D F. OPTIONS

Q 18. 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("Content-Length", numberOfBytes);

F. response.setIntHeader("Content-Length", numberOfBytes);

Answer: B, F

Q19. Which two prevent a servlet from handling requests? (Choose two.)

A. The servlet's init method returns a non-zero 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

Example08
JCode Cell
1 
2public void service(ServletRequest request,
3ServletResponse response) {
4ServletInputStream sis =
5// insert code here
6}
7

Unit- 2: The Structure and Deployment of Web Applications

and this element in the web application's deployment descriptor:

<error-page>

<error-code>302</error-code>

<location>/html/error.html</location>

</error-page>

Which, inserted at line 15, causes the container to redirect control to the error.html resource?

A. response.setError(302);

B. response.sendError(302);

C. response.setStatus(302);

D. response.sendRedirect(302);

E. response.sendErrorRedirect(302);

Answer: B

Q12. Which element of the web application deployment descriptor defines the servlet class

associated with a servlet instance?

A. <class>

B. <webapp>

C. <servlet>

D. <codebase>

E. <servlet-class>

F. <servlet-mapping>

Answer: E

Q13. Within the web application deployment descriptor, which defines a valid JNDI environment

entry?

A. <env-entry>

<env-entry-type>java.lang.Boolean</env-entry-type>

<env-entry-value>true</env-entry-value>

</env-entry>

B. <env-entry>

<env-entry-name>param/MyExampleString</env-entry-name>

<env-entry-value>This is an Example</env-entry-value>

</env-entry>

C. <env-entry>

<env-entry-name>param/MyExampleString</env-entry-name>

<env-entry-type>int</env-entry-type>

<env-entry-value>10</env-entry-value>

</env-entry>

D. <env-entry>

<env-entry-name>param/MyExampleString</env-entry-name>

<env-entry-type>java.lang.String</env-entry-type>

<env-entry-value>This is an Example</env-entry-value>

</env-entry>

Answer: D

Q14. Which three are described in the standard web application deployment descriptor? (Choose

three.)

A. session configuration

B. MIME type mappings

C. context root for the application

D. servlet instance pool configuration

E. web container default port bindings

F. ServletContext initialization parameters

Answer: A, B, F

Q15. 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 using the J2SE semantics of getResource.

E. Resources in the WAR class directory or in any of the JAR files within the library directory

CANNOT be accessed using the J2SE semantics of getResource.

Answer: C, D

Q16. Click the Task button.

Place the corresponding resources and directories in the proper web application deployment

structure.

Answer: : JSP Files Static Content

WEB-INF

Classses

Java and Servlet classes

Lib

JAR Files

web.xml

Q17. You want to create a valid directory structure for your Java EE web application, and you want

to put your web application into a WAR file called MyApp.war. Which two are true about the WAR

file? (Choose two.)

A. At deploy time, Java EE containers add a directory called META-INF directly into the

MyApp directory.

B. At deploy time, Java EE containers add a file called MANIFEST.MF directly into the MyApp

directory.

C. It can instruct your Java EE container to verify, at deploy time, whether you have properly

configured your application's classes.

D. At deploy time, Java EE containers add a directory call META-WAR directly into the MyApp

directory.

Answer: A, C

Q18. Which two from the web application deployment descriptor are valid?(Choose two.)

A. <error-page>

<exception-type>*</exception-type>

<location>/error.html</location>

</error-page>

B. <error-page>

<exception-type>java.lang.Error</exception-type>

<location>/error.html</location>

</error-page>

C. <error-page>

<exception-type>java.lang.Throwable</exception-type>

<location>/error.html</location>

</error-page>

D. <error-page>

<exception-type>java.io.IOException</exception-type>

<location>/error.html</location>

</error-page>

E. <error-page>

<exception-type>NullPointerException</exception-type>

<location>/error.html</location>

</error-page>

Answer: C, D

Q19. After a merger with another small business, your company has inherited a legacy WAR file

but the original source files were lost. After reading the documentation of that web application,

you discover that the WAR file contains a useful tag library that you want to reuse in your own

webapp packaged as a WAR file.What do you need to do to reuse this tag library?

A. Simply rename the legacy WAR file as a JAR file and place it in your webapp's library directory.

B. Unpack the legacy WAR file, move the TLD file to the META-INF directory, repackage the whole

thing as a JAR file, and place that JAR file in your webapp's library directory.

C. Unpack the legacy WAR file, move the TLD file to the META-INF directory, move the class

files to the top-level directory, repackage the whole thing as a JAR file, and place that JAR file in

your webapp's library directory.

D. Unpack the legacy WAR file, move the TLD file to the META-INF directory, move the class

files to thetop-level directory, repackage the WAR, and place that WAR file in your webapp's WEB-

INF directory.

Answer: C

Q 20. Which path is required to be present within a WAR file?

A. /classesB. /index.html
C. /MANIFEST-INFD. /WEB-INF/web.xml
E. /WEB-INF/classesF. /WEB-INF/index.html

G. /META-INF/index.xml

Answer: D

Q21. Given:

Example09
JCode Cell
1 
2public class MyServlet extends HttpServlet {
3public void service(HttpServletRequest request,
4HttpServletResponse response)
5throws ServletException, IOException {
6// insert code here
7}
8}
9

Unit- 2: The Structure and Deployment of Web Applications

Which two are true? (Choose two.)

A. Line 13 is not valid for a servlet declaration.

B. Line 14 is not valid for a servlet declaration.

C. One instance of the servlet will be loaded at startup.

D. Ten instances of the servlet will be loaded at startup.

E. The servlet will be referenced by the name catalog in mappings.

Answer: C, E

Q22. You have built a web application with tight security. Several directories of your webapp are

used for internal purposes and you have overridden the default servlet to send an HTTP 403 status

code for any request that maps to one of these directories. During testing, the Quality Assurance

director decided that they did NOT like seeing the bare response page generated by Firefox and

Internet Explorer. The director recommended that the webapp should return a more user-friendly

web page that has the same look-and-feel as the webapp plus links to the webapp's search engine.

You have created this JSP page in the /WEB-INF/jsps/error403.jsp file. You do NOT want to alter

the complex logic of the default servlet. How can you declare that the web container must send

this JSP page whenever a 403 status is generated?

A. <error-page>

<error-code>403</error-code>

<url>/WEB-INF/jsps/error403.jsp</url>

</error-page>

B. <error-page>

<status-code>403</status-code>

<url>/WEB-INF/jsps/error403.jsp</url>

</error-page>

C. <error-page>

<error-code>403</error-code>

<location>/WEB-INF/jsps/error403.jsp</location>

</error-page>

D. <error-page>

<status-code>403</status-code>

<location>/WEB-INF/jsps/error403.jsp</location>

</error-page>

Answer: C

Q23. Given a portion of a valid Java EE web application's directory structure:

MyApp

|

|-- Directory1

| |-- File1.html

|

|-- META-INF

| |-- File2.html

|

|-- WEB-INF

|-- File3.html

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

Q24. A web component accesses a local EJB session bean with a component interface of

com.example.Account with a home interface of com.example.AccountHome and a JNDI reference

of ejb/Account. Which makes the local EJB component accessible to the web components in the

web application deployment descriptor?

A. <env-ref>

<ejb-ref-name>ejb/Account</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<local-home>com.example.AccountHome</local-home>

<local>com.example.Account</local>

</env-ref>

B. <resource-ref>

<ejb-ref-name>ejb/Account</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<local-home>com.example.AccountHome</local-home>

<local>com.example.Account</local>

</resource-ref>

C. <ejb-local-ref>

<ejb-ref-name>ejb/Account</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<local-home>com.example.AccountHome</local-home>

<local>com.example.Account</local>

</ejb-local-ref>

D. <ejb-remote-ref>

<ejb-ref-name>ejb/Account</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<local-home>com.example.AccountHome</local-home>

<local>com.example.Account</local>

</ejb-remote-ref>

Answer: C

Q 25. Click the Task button.

Place the servlet name onto every request URL, relative to the web application context root, that

will invoke that servlet. Every request URL must be filled.

Answer: :

/data/ --->DataServlet

/data/index.jsp --->DataServlet

/secure/command.do --->ControlServlet

/data/command.do --->DataServlet

/data.do --->ControlServlet

Q26. Given a portion of a valid Java EE web application's directory structure:

MyApp

|

|-- File1.html

|

|-- Directory1

| |-- File2.html |

|-- META-INF

|-- File3.html

You want to know whether File1.html, File2.html, and/or File3.html will be directly accessible by

your web client's browsers.

Which 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: E

Q 27. You have created a servlet that generates weather maps. The data for these maps is

calculated by a remote host. The IP address of this host is usually stable, but occasionally does

have to change as the corporate network grows and changes. This IP address used to be hard

coded, but after the fifth change to the IP address in two years, you have decided that this value

should be declared in the deployment descriptor so you do NOT have the recompile the web

application every time the IP address changes. Which deployment descriptor snippet accomplishes

this goal?

A. <serlvet-param>

<name>WeatherServlet.hostIP</name>

<value>127.0.4.20</value>

</servlet-param>

B. <init-param>

<name>WeatherServlet.hostIP</name>

<value>127.0.4.20</value>

</init-param>

C. <servlet>

<!-- servlet definition here -->

<param-name>WeatherServlet.hostIP</param-name>

<param-value>127.0.4.20</param-value>

</servlet>

D. <init-param>

<param-name>WeatherServlet.hostIP</param-name>

<param-value>127.0.4.20</param-value>

</init-param>

E. <serlvet-param>

<param-name>WeatherServlet.hostIP</param-name>

<param-value>127.0.4.20</param-value>

</servlet-param>

Answer: D

Q 28. In which two locations can library dependencies be defined for a web application? (Choose

two.)

A. the web application deployment descriptor

B. the /META-INF/dependencies.xml file

C. the /META-INF/MANIFEST.MF manifest file

D. the /META-INF/MANIFEST.MF manifest of a JAR in the web application classpath

Answer: C, D

Q29. Which two about WAR files are true? (Choose two.)

A. WAR files must be located in the web application library directory.

B. WAR files must contain the web application deployment descriptor.

C. WAR files must be created by using archive tools designed specifically for that purpose.

D. The web container must serve the content of any META-INF directory located in a WAR

file.

E. The web container must allow access to resources in JARs in the web application library

directory.

Answer: B, E

Q30. Given this fragment from a Java EE deployment descriptor:

341. <error-page>

342. <exception-type>java.lang.Throwable</exception-type>

343. <location>/mainError.jsp</location>

344. </error-page>

345. <error-page>

346. <exception-type>java.lang.ClassCastException</exception-type>

347. <location>/castError.jsp</location>

348. </error-page>

If the web application associated with the fragment above throws a ClassCastException.

Which statement is true?

A. The deployment descriptor is invalid.

B. The container invokes mainError.jsp.

C. The container invokes castError.jsp.

D. Neither mainError.jsp nor castError.jsp is invoked.

Answer: C

Q31. Which defines the welcome files in a web application deployment descriptor?

A. <welcome>

<welcome-file>/welcome.jsp</welcome-file>

</welcome>

<welcome>

<welcome-file>/index.html</welcome-file>

</welcome>

B. <welcome-file-list>

<welcome-file>welcome.jsp</welcome-file>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

C. <welcome>

<welcome-file>welcome.jsp</welcome-file>

</welcome>

<welcome>

<welcome-file>index.html</welcome-file>

</welcome>

D. <welcome-file-list>

<welcome-file>/welcome.jsp</welcome-file>

<welcome-file>/index.html</welcome-file>

</welcome-file-list>

E. <welcome>

<welcome-file>

www.TestsNow.com

- 120 -

<welcome-name>Welcome</welcome-name>

<location>welcome.jsp</location>

</welcome-file>

<welcome-file>

<welcome-name>Index</welcome-name>

<location>index.html</location>

</welcome-file>

</welcome>

Answer: B

Q32. In which three directories, relative to a web application's root, may a tag library descriptor

file reside when deployed directly into a web application? (Choose three.)

A. /WEB-INFB. /META-INF
C. /WEB-INF/tldsD. /META-INF/tlds

E. /WEB-INF/resources F. /META-INF/resources

Answer: A, C, E

Example10
JCode Cell
1 
2<servlet>
3<servlet-name>catalog</servlet-name>
4<jsp-file>/catalogTemplate.jsp</jsp-file>
5<load-on-startup>10</load-on-startup>
6</servlet>
7

Unit- 3: The Web Container Model

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?

A. An exception is thrown at runtime by SourceServlet.

B. An exception is thrown at runtime by DestinationServlet.

C. Only "hello from dest" appears in the response output stream.

D. Both "hello from source" and "hello from dest" appear in the response output stream.

Answer: A

Q8.Given the definition of MyServlet:

Example11
JCode Cell
1 
2<context-param>
3<param-name>prefsDbURL</param-name>
4<param-value>
5jdbc:pointbase:server://dbhost:4747/prefsDB
6</param-value>
7</context-param>
8

Unit- 3: The Web Container Model

16 session.setAttribute("myAttribute","myAttributeValue");

Example12
JCode Cell
1 
2public class MyServlet extends HttpServlet {
3public void service(HttpServletRequest request,
4HttpServletResponse response)
5throws ServletException, IOException {
6HttpSession session = request.getSession();
7

Unit- 3: The Web Container Model

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.

B. Create an HttpSessionAttributeListener class and implement the attributeRemoved method and

log the attribute name using the getName method on the event object.

C. Create an SessionAttributeListener class and implement the attributeRemoved method and log

the attribute name using the getAttributeName method on the event object.

D. Create an SessionAttributeListener class and implement the attributeDeleted method and log

the attribute name using the getAttributeName method on the event object.

Answer: B

Q11.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

Q12. You have a simple web application that has a single Front Controller servlet hat dispatches

to JSPs to generate a variety of views. Several of these views require further database processing

to retrieve the necessary order object using the orderID request parameter. To do this additional

processing, you pass the request first to a servlet that is mapped to the URL pattern WEB-

INF/retreiveorder.do in the deployment descriptor. This servlet takes two request parameters, the

orderID 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. 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:

Example13
JCode Cell
1 
2session.invalidate();
3response.getWriter().println("value=" +
4session.getAttribute("myAttribute"));
5}
6}
7

Unit- 3: The Web Container Model

...

Example14
JCode Cell
1 
2<filter>
3<filter-name>ParamAdder</filter-name>
4<filter-class>com.example.ParamAdder</filter-class>
5</filter>
6

Unit- 3: The Web Container Model

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:

Example15
JCode Cell
1 
2<filter-mapping>
3<filter-name>ParamAdder</filter-name>
4<servlet-name>MyServlet</servlet-name>
5<!-- insert element here -->
6</filter-mapping>
7

Unit- 3: The Web Container Model

...

Example16
JCode Cell
1 
2<filter>
3<filter-name>ParamAdder</filter-name>
4<filter-class>com.example.ParamAdder</filter-class>
5</filter>
6<filter-mapping>
7<filter-name>ParamAdder</filter-name>
8<servlet-name>Destination</servlet-name>
9</filter-mapping>
10

Unit- 3: The Web Container Model

What is the result of a client request of the Source servlet with no query string?

A. The output "filterAdded = null" is written to the response stream.

B. The output "filterAdded = addedByFilter" is written to the response stream.

C. An exception is thrown at runtime within the service method of the Source servlet.

D. An exception is thrown at runtime within the service method of the Destination servlet.

Answer: A

Q20.Given a Filter class definition with this method:

Example17
JCode Cell
1 
2<servlet-mapping>
3<servlet-name>Destination</servlet-name>
4<url-pattern>/dest/Destination</url-pattern>
5</servlet-mapping>
6

Unit- 3: The Web Container Model

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

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

Q 28. Click the Task button.

Place the XML elements in the web application deployment descriptor solution to configure a

servlet context event listener named com.example.MyListener.

Answer: :

<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

Q30. Your IT department is building a lightweight Front Controller servlet that invokes an

application logic object with the interface:

public interface ApplicationController {

public String invoke(HttpServletRequest request)

}

The return value of this method indicates a symbolic name of the next view. From this name, the

Front Controller servlet looks up the JSP URL in a configuration table. This URL might be an

absolute path or a path relative to the current request. Next, the Front Controller servlet must

send the request to this JSP to generate the view. Assume that the servlet variable request is

assigned the current HttpServletRequest object and the variable context is assigned the webapp's

ServletContext.

Which code snippet of the Front Controller servlet accomplishes this goal?

A. Dispatcher view

= context.getDispatcher(viewURL);

view.forwardRequest(request, response);

B. Dispatcher view

= request.getDispatcher(viewURL);

view.forwardRequest(request, response);

C. RequestDispatcher view

= context.getRequestDispatcher(viewURL);

view.forward(request, response);

D. RequestDispatcher view = request.getRequestDispatcher(viewURL);

view.forward(request, response);

Answer: D

Q31. Given that a web application consists of two HttpServlet classes, ServletA and ServletB, and

Example18
JCode Cell
1 
2public void doFilter(ServletRequest request,
3ServletResponse response,
4FilterChain chain)
5throws ServletException, IOException {
6// insert code here
7}
8

the ServletA.service method

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. enclose lines 21-22 in a synchronized block:

synchronized(this) {

session.setAttribute(key, "Hello");

value = session.getAttribute(key);

}

E. enclose lines 21-22 in a synchronized block:

synchronized(session) {

session.setAttribute(key, "Hello");

value = session.getAttribute(key); }

Answer: C, E

Example19
JCode Cell
1 
2String key = "com.example.data";
3session.setAttribute(key, "Hello");
4Object value = session.getAttribute(key);
5

Unit-4: Session Management

object was created, and describe the mechanisms used to destroy the session object, and

when it was destroyed.

Example20
JCode Cell
1 
2Write servlet code to store objects into a session object and retrieve objects from a sessionobject.
3Given a scenario describe the APIs used to access the session object, explain when the session
4

Unit-4: Session Management

session, and write code to respond to an event when a session object migrates from one VM

to another.

Example21
JCode Cell
1 
2Using session listeners, write code to respond to an event when an object is added to a
3

Unit-4: Session Management

employ, how cookies might be used to manage sessions, how URL rewriting might be used to

manage sessions, and write servlet code to perform URL rewriting.

Q1. A developer for the company web site has been told that users may turn off cookie support in

their browsers. What must the developer do to ensure that these customers can still use the web

application?

A. The developer must ensure that every URL is properly encoded using the appropriate URL

rewriting APIs.

B. The developer must provide an alternate mechanism for managing sessions and abandon the

HttpSession mechanism entirely.

C. The developer can ignore this issue. Web containers are required to support automatic

URL rewriting when cookies are not supported.

D. The developer must add the string id=<sessionid> to the end of every URL to ensure that

the conversation with the browser can continue.

Answer: A

Q2. 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 sessionID. In addition,

assume that your webapp keeps a hashmap of session objects by the ID. Here is a partial

implementation of this servlet:

Example22
JCode Cell
1 
2Given a scenario, describe which session management mechanism the Web container could
3

Unit-4: Session Management

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

Q3.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

Q4. 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 re-enter their

credit card number for each transaction. Your management has decided to use client-side 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 adds it to the out

going response to be stored on the user's web browser?

A.10. Cookie c = new Cookie("creditCard", usersCard);

Example23
JCode Cell
1 
2public class SessionAgeServlet extends HttpServlet {
3public void service(HttpServletRequest request, HttpServletResponse) throws IOException {
4String sessionID = request.getParameter("sessionID");
5HttpSession session = getSession(sessionID);
6long age = // your code here
7response.getWriter().print(age);
8} ... // more code here
9}
10

Unit-4: Session Management

B. 10. Cookie c = new Cookie("creditCard", usersCard);

Example24
JCode Cell
1 
2c.setSecure(true);
3c.setAge(10368000);
4response.addCookie(c);
5

Unit-4: Session Management

C. 10. Cookie c = new Cookie("creditCard", usersCard);

Example25
JCode Cell
1 
2c.setHttps(true);
3c.setMaxAge(10368000);
4response.setCookie(c);
5

Unit-4: Session Management

D. 10. Cookie c = new Cookie("creditCard", usersCard);

Example26
JCode Cell
1 
2c.setSecure(true);
3c.setMaxAge(10368000);
4response.addCookie(c);
5

Unit-4: Session Management

E. 10. Cookie c = new Cookie("creditCard", usersCard);

Example27
JCode Cell
1 
2c.setHttps(true);
3c.setAge(10368000);
4response.addCookie(c);
5

Unit-4: Session Management

Answer: C

Q5. 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?

A. 10. Cookie c = request.getCookie("username");

B. 10. Cookie c = null;

Example28
JCode Cell
1 
2c.setSecure(true);
3c.setAge(10368000);
4response.setCookie(c);
5

Unit-4: Session Management

C. 10. Cookie c = null;

Example29
JCode Cell
1 
2for ( Iterator i = request.getCookies();
3i.hasNext(); ) {
4Cookie o = (Cookie) i.next();
5if ( o.getName().equals("username") ) {
6c = o;
7break;
8}
9}
10

Unit-4: Session Management

D. 10. Cookie c = null;

Example30
JCode Cell
1 
2for ( Enumeration e = request.getCookies();
3e.hasMoreElements(); ) {
4Cookie o = (Cookie) e.nextElement();
5if ( o.getName().equals("username") ) {
6c = o;
7break;
8}
9}
10

Unit-4: Session Management

Answer: D

Q6. What is the purpose of session management?

A. To manage the user's login and logout activities.

B. To store information on the client-side between HTTP requests.

C. To store information on the server-side between HTTP requests.

D. To tell the web container to keep the HTTP connection alive so it can make subsequent requests

without the

delay of making the TCP connection.

Answer: C

Q7. The Squeaky Beans Inc. shopping application was initially developed for a non-distributed

environment. The company recently purchased the Acme Application Server, which supports

distributed HttpSession objects. When deploying the application to the server, the deployer marks

it as distributable in the web application deployment descriptor to take advantage of this feature.

Given this scenario, which two must be true? (Choose two.)

A. The J2EE web container must support migration of objects that implement Serializable.

B. The J2EE web container must use the native JVM Serialization mechanism for distributing

HttpSession objects.

C. As per the specification, the J2EE web container ensures that distributed HttpSession

objects will be stored in a database.

D. Storing references to Enterprise JavaBeans components in the HttpSession object might NOT be

supported by J2EE web containers.

Answer: A, D

Q8. In your web application, you need to execute a block of code whenever the session object is

first created. Which design will accomplish this goal?

A. Create an HttpSessionListener class and implement the sessionInitialized method with that

block of code.

B. Create an HttpSessionActivationListener class and implement the sessionCreated method with

that block of code.

C. Create a Filter class, call the getSession(false) method, and if the result was null, then

execute that block of code.

D. Create an HttpSessionListener class and implement the sessionCreated method with that

block of code.

E. Create a Filter class, call the getSession(true) method, and if the result was NOT null, then

execute that block of code.

Answer: D

Q9. Which interface must a class implement so that instances of the class are notified after any

object is added to a session?

A. javax.servlet.http.HttpSessionListener

B. javax.servlet.http.HttpSessionValueListener

C. javax.servlet.http.HttpSessionBindingListener

D. javax.servlet.http.HttpSessionAttributeListener

Answer: D

Q10. Which method must be used to encode a URL passed as an argument to

HttpServletResponse.sendRedirect when using URL rewriting for session tracking?

A. ServletResponse.encodeURL

B. HttpServletResponse.encodeURL

C. ServletResponse.encodeRedirectURL

D. HttpServletResponse.encodeRedirectURL

Answer: D

Q11. Users of your web application have requested that they should be able to set the duration of

their sessions. So for example, one user might want a webapp to stay connected for an hour rather

than the webapp's default of fifteen minutes; another user might want to stay connected for a

whole day. Furthermore, you have a special login servlet that performs user authentication and

retrieves the User object from the database. You want to augment this code to set up the user's

specified session duration.

Which code snippet in the login servlet will accomplish this goal?

A. User user = // retrieve the User object from the database

session.setDurationInterval(user.getSessionDuration());

B. User user = // retrieve the User object from the database

session.setMaxDuration(user.getSessionDuration());

C. User user = // retrieve the User object from the database

session.setInactiveInterval(user.getSessionDuration());

D. User user = // retrieve the User object from the database

session.setDuration(user.getSessionDuration());

E. User user = // retrieve the User object from the database

session.setMaxInactiveInterval(user.getSessionDuration());

F. User user = // retrieve the User object from the database

session.setMaxDurationInterval(user.getSessionDuration());

Answer: E

Q12. Which two classes or interfaces provide a getSession method? (Choose two.)

A. javax.servlet.http.HttpServletRequest

B. javax.servlet.http.HttpSessionContext

C. javax.servlet.http.HttpServletResponse

D. javax.servlet.http.HttpSessionBindingEvent

E. javax.servlet.http.HttpSessionAttributeEvent

Answer: A, D

Q13.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. String ext = context.getParameter('licenseExtension');

if ( ext == null ) {

context.setParameter('licenseExtension', DEFAULT);

}

C. String ext = context.getAttribute('licenseExtension');

if ( ext == null ) {

context.setAttribute('licenseExtension', DEFAULT);

}

D. String ext = context.getInitParameter('licenseExtension');

if ( ext == null ) {

context.resetInitParameter('licenseExtension', DEFAULT);

}

E. String ext = context.getInitParameter('licenseExtension');

if ( ext == null ) {

context.setInitParameter('licenseExtension', DEFAULT);

}

Answer: A

Q14. You have a use case in your web application that adds several session-scoped attributes. At

the end of the use case, one of these objects, the manager attribute, is removed and then it needs

to decide which of the other session-scoped attributes to remove. How can this goal be

accomplished?

A. The object of the manager attribute should implement the HttpSessionBindingListener and it

should call the removeAttribute method on the appropriate session attributes.

B. The object of the manager attribute should implement the HttpSessionListener and it should

call the removeAttribute method on the appropriate session attributes.

C. The object of the manager attribute should implement the HttpSessionBindingListener and it

should call the deleteAttribute method on the appropriate session attributes.

D. The object of the manager attribute should implement the HttpSessionListener and it should

call the deleteAttribute method on the appropriate session attributes.

Answer: A

Q15. Your 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 preferences using Java

SE'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 stores the user's Preference object when an

HTTP session is created. Also, note that user identification information is stored in an HTTP cookie.

Which partial listener class can accomplish this goal?

A. public class UserPrefLoader implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent se) {

MyPrefsFactory myFactory = (MyPrefsFactory)

se.getServletContext().getAttribute("myPrefsFactory");

User user = getUserFromCookie(se);

myFactory.setThreadLocalUser(user);

Preferences userPrefs = myFactory.userRoot();

se.getSession().setAttribute("prefs", userPrefs);

}

// more code here

}

B. public class UserPrefLoader implements SessionListener {

public void sessionCreated(SessionEvent se) {

MyPrefsFactory myFactory = (MyPrefsFactory) se.getContext().getAttribute("myPrefsFactory");

User user = getUserFromCookie(se);

myFactory.setThreadLocalUser(user);

Preferences userPrefs = myFactory.userRoot();

se.getSession().addAttribute("prefs", userPrefs);

}

// more code here

}

C. public class UserPrefLoader implements HttpSessionListener {

public void sessionInitialized(HttpSessionEvent se) {

MyPrefsFactory myFactory = (MyPrefsFactory)

se.getServletContext().getAttribute("myPrefsFactory");

User user = getUserFromCookie(se);

myFactory.setThreadLocalUser(user);

Preferences userPrefs = myFactory.userRoot();

se.getHttpSession().setAttribute("prefs", userPrefs);

}

// more code here

}

D. public class UserPrefLoader implements SessionListener {

public void sessionInitialized(SessionEvent se) {

MyPrefsFactory myFactory = (MyPrefsFactory)

se.getServletContext().getAttribute("myPrefsFactory");

User user = getUserFromCookie(se);

myFactory.setThreadLocalUser(user);

Preferences userPrefs = myFactory.userRoot();

se.getSession().addAttribute("prefs", userPrefs);

}

// more code here

}

Answer: A

Q16. For which three events can web application event listeners be registered?(Choose three.)

A. when a session is createdB. 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

Q17. Given an HttpServletRequest request:

Example31
JCode Cell
1 
2Cookie[] cookies = request.getCookies();
3for ( int i = 0; i < cookies.length; i++ ) {
4if ( cookies[i].getName().equals("username") ) {
5c = cookies[i];
6break;
7}
8}
9

Unit-4: Session Management

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

Q18. A developer for the company web site has been told that users may turn off cookie support

in their browsers. What must the developer do to ensure that these customers can still use the

web application?

A. The developer must ensure that every URL is properly encoded using the appropriate URL

rewriting APIs.

B. The developer must provide an alternate mechanism for managing sessions and abandon the

HttpSession mechanism entirely.

C. The developer can ignore this issue. Web containers are required to support automatic

URL rewriting when cookies are not supported.

D. The developer must add the string ?id=<sessionid> to the end of every URL to ensure that

the conversation with the browser can continue.

Answer: A

Q19. Given the definition of MyObject and that an instance of MyObject is

bound as a session attribute:

Example32
JCode Cell
1 
2String id = request.getParameter("jsessionid");
3// insert code here
4String name = (String) session.getAttribute("name");
5

Unit-4: Session Management

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

Q 20. 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 sessionID. In addition,

assume that your webapp keeps a hashmap of session objects by the ID. Here is a partial

implementation of this servlet:

Example33
JCode Cell
1 
2package com.example;
3public class MyObject implements
4javax.servlet.http.HttpSessionBindingListener {
5// class body code here
6}
7

Unit-4: Session Management

... // more code here

Example34
JCode Cell
1 
2public class SessionAgeServlet extends HttpServlet {
3public void service(HttpServletRequest request, HttpServletResponse) throws IOException {
4String sessionID = request.getParameter("sessionID");
5HttpSession session = getSession(sessionID);
6long age = // your code here
7response.getWriter().print(age);
8}
9

Unit-4: Session Management

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

Q21. 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

Q22. Given an HttpServletRequest request and an HttpServletResponse response:

Example35
JCode Cell
1 
2}
3

Unit-4: Session Management

To implement the design intent, which statement must be inserted at line 42?

A. session = response.getSession();

B. session = request.getSession();

C. session = request.getSession(true);

D. session = request.getSession(false);

E. session = request.getSession("jsessionid");

Answer: D

Q 23. A web application uses the HttpSession mechanism to determine if a user is "logged in."

When a user supplies a valid user name and password, an HttpSession is created for that user.The

user has access to the application for only 15 minutes after logging in. The code must determine

how long the user has been logged in, and if this time is greater than 15 minutes, must destroy the

HttpSession.

Which method in HttpSession is used to accomplish this?

A. getCreationTimeB. invalidateAfter

C. getLastAccessedTime D. getMaxInactiveInterval

Answer: A

Q 24. Which method must be used to encode a URL passed as an argument to

HttpServletResponse.sendRedirect when using URL rewriting for session tracking?

A. ServletResponse.encodeURL

B. HttpServletResponse.encodeURL

C. ServletResponse.encodeRedirectURL

D. HttpServletResponse.encodeRedirectURL

Answer: D

Q25.Which interface must a session attribute implement if it needs to be notified when a web

container persists a session?

A. javax.servlet.http.HttpSessionListener

B. javax.servlet.http.HttpSessionBindingListener

C. javax.servlet.http.HttpSessionAttributeListener

D. javax.servlet.http.HttpSessionActivationListener

Answer: D

Q26.What is the purpose of session management?

A. To manage the user's login and logout activities.

B. To store information on the client-side between HTTP requests.

C. To store information on the server-side between HTTP requests.

D. To tell the web container to keep the HTTP connection alive so it can make subsequent requests

without the delay of making the TCP connection.

Answer: C

Q27. 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 re-enter

their credit card number for each transaction. Your management has decided to use client-side

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

adds it to the out going response to be stored on the user's web browser?

A. 10. Cookie c = new Cookie("creditCard", usersCard);

Example36
JCode Cell
1 
2HttpSession session = null;
3// insert code here
4if(session == null) {
5// do something if session does not exist
6} else {
7// do something if session exists
8}
9

Unit-4: Session Management

Answer: C

Example37
JCode Cell
1 
2c.setSecure(true);
3c.setAge(10368000);
4response.setCookie(c);
5

Unit-5 : Web Application Security

IOException {

Example38
JCode Cell
1 
2class MyServlet extends HttpServlet {
3public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
4

Unit-5 : Web Application Security

If the DD contains a single security constraint associated with MyServlet and its only <http-

method> tags

and <auth-constraint> tags are:

<http-method>GET</http-method>

<http-method>PUT</http-method>

<auth-constraint>Admin</auth-constraint>

Which four requests would be allowed by the container? (Choose four.)

A. A user whose role is Admin can perform a PUT.

B. A user whose role is Admin can perform a GET.

C. A user whose role is Admin can perform a POST.

D. A user whose role is Member can perform a PUT.

E. A user whose role is Member can perform a POST.

F. A user whose role is Member can perform a GET.

Answer: A, B, C, E

Q2. What is true about Java EE authentication mechanisms?

a) If your deployment descriptor correctly declares an authentication type of CLIENT_CERT, your

users must have a certificate from an official source before they can use your application.

b) If your deployment descriptor correctly declares an authentication type of BASIC, the

container automatically requests a user name and password whenever a user starts a new

session.

c) If you want your web application to support the widest possible array of browsers, and you

want to perform authentication, the best choice of Java EE authentication mechanisms is

DIGEST.

d) To use Java EE FORM authentication, you must declare two HTML files in your deployment

descriptor, and you must use a predefined action in the HTML file that handles your user's

login.

Answer: D

Q3. If you want to use the Java EE platform's built-in type of authentication that uses a custom

HTML page for authentication, which two statements are true? (Choose two.)

A. Your deployment descriptor will need to contain this tag:

<auth-method>CUSTOM</auth-method>.

B. The related custom HTML login page must be named loginPage.html.

C. When you use this type of authentication, SSL is turned on automatically.

D. You must have a tag in your deployment descriptor that allows you to point to both a login

HTML page and an HTML page for handling any login errors.

E. In the HTML related to authentication for this application, you must use predefined variable

names for the variables that store the user and password values.

Answer: D, E

Q4. Given this fragment in a servlet:

Example39
JCode Cell
1 
2// servlet code here ...
3}
4}
5

Unit-5 : Web Application Security

And the following fragment from the related Java EE deployment descriptor:

812. <security-role-ref>

813. <role-name>Admin</role-name>

814. <role-link>Administrator</role-link>

815. </security-role-ref>

900. <security-role>

901. <role-name>Admin</role-name>

902. <role-name>Administrator</role-name>

903. </security-role>

What is the result?

A. Line 24 can never be reached.

B. The deployment descriptor is NOT valid.

C. If line 24 executes, the user's role will be Admin.

D. If line 24 executes, the user's role will be Administrator.

E. If line 24 executes the user's role will NOT be predictable.

Answer: D

Q5. Given the security constraint in a DD:

101. <security-constraint>

102. <web-resource-collection>

103. <web-resource-name>Foo</web-resource-name>

104. <url-pattern>/Bar/Baz/*</url-pattern>

105. <http-method>POST</http-method>

106. </web-resource-collection>

107. <auth-constraint>

108. <role-name>DEVELOPER</role-name>

109. </auth-constraint>

110. </security-constraint>

And given that "MANAGER" is a valid role-name, which four are true for this security

constraint?(Choose four.)

A. MANAGER can do a GET on resources in the /Bar/Baz directory.

B. MANAGER can do a POST on any resource in the /Bar/Baz directory.

C. MANAGER can do a TRACE on any resource in the /Bar/Baz directory.

D. DEVELOPER can do a GET on resources in the /Bar/Baz directory.

E. DEVELOPER can do only a POST on resources in the /Bar/Baz directory.

F. DEVELOPER can do a TRACE on any resource in the /Bar/Baz directory.

Answer: A, C, D, F

Q6. Given the security constraint in a DD:

101. <security-constraint>

102. <web-resource-collection>

103. <web-resource-name>Foo</web-resource-name>

104. <url-pattern>/Bar/Baz/*</url-pattern>

105. <http-method>POST</http-method>

106. </web-resource-collection>

107. <auth-constraint>

108. <role-name>DEVELOPER</role-name>

109. </auth-constraint>

110. </security-constraint>

And given that "MANAGER" is a valid role-name, which four are true for this security

constraint?(Choose four.)

A. MANAGER can do a GET on resources in the /Bar/Baz directory.

B. MANAGER can do a POST on any resource in the /Bar/Baz directory.

C. MANAGER can do a TRACE on any resource in the /Bar/Baz directory.

D. DEVELOPER can do a GET on resources in the /Bar/Baz directory.

E. DEVELOPER can do only a POST on resources in the /Bar/Baz directory.

F. DEVELOPER can do a TRACE on any resource in the /Bar/Baz directory.

Answer: A, C, D, F

Q7. Which activity supports the data integrity requirements of an application?

A. using HTTPS as a protocol

B. using an LDAP security realm

C. using HTTP Basic authentication

D. using forms-based authentication

Answer: A

Q8. Which mechanism requires the client to provide its public key certificate?

A. HTTP Basic AuthenticationB. Form Based Authentication
C. HTTP Digest AuthenticationD. HTTPS Client Authentication

Answer: D

Q9. Given the two security constraints in a deployment descriptor:

101. <security-constraint>

102. <!--a correct url-pattern and http-method goes here-->

103. <auth-constraint><role-name>SALES</role-name></auth-

103. <auth-constraint>

104. <role-name>SALES</role-name>

105. </auth-constraint>

106. </security-constraint>

107. <security-constraint>

108. <!--a correct url-pattern and http-method goes here-->

109. <!-- Insert an auth-constraint here -->

110. </security-constraint>

If the two security constraints have the same url-pattern and http-method, which two, inserted

independently at line 109, will allow users with role names of either SALES or MARKETING to

access

this resource? (Choose two.)

A. <auth-constraint/>

B. <auth-constraint>

<role-name>*</role-name>

</auth-constraint>

C. <auth-constraint>

<role-name>ANY</role-name>

</auth-constraint>

D. <auth-constraint>

<role-name>MARKETING</role-name>

</auth-constraint>

Answer: B, D

Q10. Given this fragment in a servlet:

Example40
JCode Cell
1 
2if(req.isUserInRole("Admin")) {
3// do stuff
4}
5

Unit-5 : Web Application Security

And the following fragment from the related Java EE deployment descriptor:

812. <security-role-ref>

813. <role-name>Admin</role-name>

814. <role-link>Administrator</role-link>

815. </security-role-ref>

900. <security-role>

901. <role-name>Admin</role-name>

902. <role-name>Administrator</role-name>

903. </security-role>

What is the result?

A. Line 24 can never be reached.

B. The deployment descriptor is NOT valid.

C. If line 24 executes, the user's role will be Admin.

D. If line 24 executes, the user's role will be Administrator.

E. If line 24 executes the user's role will NOT be predictable.

Answer: D

Q11.Which two are true about authentication? (Choose two.)

A. Form-based logins should NOT be used with HTTPS.

B. When using Basic Authentication the target server is NOT authenticated.

C. J2EE compliant web containers are NOT required to support the HTTPS protocol.

D. Web containers are required to support unauthenticated access to unprotected web

resources.

E. Form-based logins should NOT be used when sessions are maintained by cookies or SSL

session information.

Answer: B, D

Q12. If you want to use the Java EE platform's built-in type of authentication that uses a custom

HTML page for authentication, which two statements are true? (Choose two.)

A. Your deployment descriptor will need to contain this tag:

<auth-method>CUSTOM</auth-method>.

B. The related custom HTML login page must be named loginPage.html.

C. When you use this type of authentication, SSL is turned on automatically.

D. You must have a tag in your deployment descriptor that allows you to point to both a login

HTML page and an HTML page for handling any login errors.

E. In the HTML related to authentication for this application, you must use predefined

variable names for the variables that store the user and password values.

Answer: D, E

Q13. Given the two security constraints in a deployment descriptor:

101. <security-constraint>

102. <!--a correct url-pattern and http-method goes here-->

103. <auth-constraint><role-name>SALES</role-name></auth-

103. <auth-constraint>

104. <role-name>SALES</role-name>

105. </auth-constraint>

106. </security-constraint>

107. <security-constraint>

108. <!--a correct url-pattern and http-method goes here-->

109. <!-- Insert an auth-constraint here -->

110. </security-constraint>

If the two security constraints have the same url-pattern and http-method, which two, inserted

independently at line 109, will allow users with role names of either SALES or MARKETING to

access this resource? (Choose two.)

A. <auth-constraint/>

B. <auth-constraint>

<role-name>*</role-name>

</auth-constraint>

C. <auth-constraint>

<role-name>ANY</role-name>

</auth-constraint>

D. <auth-constraint>

<role-name>MARKETING</role-name>

</auth-constraint>

Answer: B, D

Q14. Which two are valid values for the <transport-guarantee> element inside a <security-

constraint> element of a web application deployment descriptor? (Choose two.)

A. NULL B. SECURE

C. INTEGRALD. ENCRYPTED

E. CONFIDENTIAL

Answer: C, E

Q15. Which basic authentication type is optional for a J2EE 1.4 compliant web container?

A. HTTP Basic Authentication B. Form Based Authentication

C. HTTP Digest Authentication D. HTTPS Client Authentication

Answer: C

Q16. Which security mechanism uses the concept of a realm?

A. authorizationB. data integrity
C. confidentialityD. authentication

Answer: D

Q17. Which two security mechanisms can be directed through a sub-element of the <user-data-

constraint> element in a web application deployment descriptor? (Choose two.)

A. authorizationB. data integrity
C. confidentialityD. authentication

Answer: B, C

Q18. Which two statements are true about the security-related tags in a valid Java EE deployment

descriptor? (Choose two.)

A. Every <security-constraint> tag must have at least one <http-method> tag.

B. A <security-constraint> tag can have many <web-resource-collection> tags.

C. A given <auth-constraint> tag can apply to only one <web-resource-collection> tag.

D. A given <web-resource-collection> tag can contain from zero to many <url-pattern> tags.

E. It is possible to construct a valid <security-constraint> tag such that, for a given resource,

no user roles can access that resource.

Answer: B, E

Q19. Which element of a web application deployment descriptor

<security-constraint> element is required?

A. <realm-name>B. <auth-method>
C. <security-role>D. <transport-guarantee>

E. <web-resource-collection>

Answer: E

Q 20 Which two are required elements for the <web-resource-collection> element of a web

application deployment descriptor? (Choose two.)

A. <realm-name>B. <url-pattern>
C. <description>D. <web-resource-name>

E. <transport-guarantee>

Answer: B, D

Q21. Given:

Example41
JCode Cell
1 
2if(req.isUserInRole("Admin")) {
3// do stuff
4}
5

Unit-5 : Web Application Security

HttpServletResponse resp)

throws ServletException, IOException {

Example42
JCode Cell
1 
2class MyServlet extends HttpServlet {
3public void doPut(HttpServletRequest req,
4

Unit-5 : Web Application Security

...

Example43
JCode Cell
1 
2// servlet code here
3

Unit-5 : Web Application Security

If the DD contains a single security constraint associated with MyServlet and its only <http-

method> tags and <auth-constraint> tags are:

<http-method>GET</http-method>

<http-method>PUT</http-method>

<auth-constraint>Admin</auth-constraint>

Which four requests would be allowed by the container? (Choose four.)

A. A user whose role is Admin can perform a PUT.

B. A user whose role is Admin can perform a GET.

C. A user whose role is Admin can perform a POST.

D. A user whose role is Member can perform a PUT.

E. A user whose role is Member can perform a POST.

F. A user whose role is Member can perform a GET.

Answer: A, B, C, E

Q22. What is true about Java EE authentication mechanisms?

A. If your deployment descriptor correctly declares an authentication type of CLIENT_CERT, your

users must have a certificate from an official source before they can use your application.

B. If your deployment descriptor correctly declares an authentication type of BASIC, the

container automatically requests a user name and password whenever a user starts a new session.

C. If you want your web application to support the widest possible array of browsers, and

you want to perform authentication, the best choice of Java EE authentication mechanisms is

DIGEST.

D. To use Java EE FORM authentication, you must declare two HTML files in your deployment

descriptor, and you must use a predefined action in the HTML file that handles your user's login.

Answer: D

Q23. Which two statements are true about using the isUserInRole method to implement security

in a Java EE application? (Choose two.)

A. It can be invoked only from the doGet or doPost methods.

B. It can be used independently of the getRemoteUser method.

C. Can return "true" even when its argument is NOT defined as a valid role name in the

deployment descriptor.

D. Using the isUserInRole method overrides any declarative authentication related to the

method in which it is invoked.

E. Using the isUserInRole method overrides any declarative authorization related to the

method in which it is invoked.

Answer: B, C

Q24.developer has used this code within a servlet:

Example44
JCode Cell
1 
2}
3}
4

Unit-5 : Web Application Security

What else must the developer do to ensure that the intended security goal is achieved?

A. create a user called vip in the security realm

B. define a group within the security realm and call it vip

C. define a security-role named vip in the deployment descriptor

D. declare a security-role-ref for vip in the deployment descriptor

Answer: D

Example45
JCode Cell
1 
2if(request.isUserInRole("vip")) {
3// VIP-related logic here
4}
5

Unit-5 : Web Application Security

If the DD contains a single security constraint associated with MyServlet and its only <http-

method> tags

and <auth-constraint> tags are:

<http-method>GET</http-method>

<http-method>PUT</http-method>

<auth-constraint>Admin</auth-constraint>

Which four requests would be allowed by the container? (Choose four.)

A. A user whose role is Admin can perform a PUT.

B. A user whose role is Admin can perform a GET.

C. A user whose role is Admin can perform a POST.

D. A user whose role is Member can perform a PUT.

E. A user whose role is Member can perform a POST.

F. A user whose role is Member can perform a GET.

Answer: A, B, C, E

Q2. What is true about Java EE authentication mechanisms?

A. If your deployment descriptor correctly declares an authentication type of CLIENT_CERT,

your users must have a certificate from an official source before they can use your application.

B. If your deployment descriptor correctly declares an authentication type of BASIC, the

container automatically requests a user name and password whenever a user starts a new session.

C. If you want your web application to support the widest possible array of browsers, and

you want to perform authentication, the best choice of Java EE authentication mechanisms is

DIGEST.

D. To use Java EE FORM authentication, you must declare two HTML files in your deployment

descriptor, and you must use a predefined action in the HTML file that handles your user's login.

Answer: D

Q3. If you want to use the Java EE platform's built-in type of authentication that uses a custom

HTML page for authentication, which two statements are true? (Choose two.)

A. Your deployment descriptor will need to contain this tag:

<auth-method>CUSTOM</auth-method>.

B. The related custom HTML login page must be named loginPage.html.

C. When you use this type of authentication, SSL is turned on automatically.

D. You must have a tag in your deployment descriptor that allows you to point to both a login

HTML page and an HTML page for handling any login errors.

E. In the HTML related to authentication for this application, you must use predefined variable

names for the variables that store the user and password values.

Answer: D, E

Q4. Given this fragment in a servlet:

Example46
JCode Cell
1 
2// servlet code here ...
3}
4}
5

Unit-5 : Web Application Security

...

Example47
JCode Cell
1 
2// servlet code here
3
📝 Key Takeaways
  • Questions come from the servlet question bank in the training material
  • Aim to answer each question before revealing the answer
  • Revisit any weak topic from the sidebar

🧠 Test Your Knowledge

124 Questions
Progress: 0 / 124