Your deployment descriptor will need to contain this tag:
<auth-method>CUSTOM</auth-method>.
The related custom HTML login page must be named loginPage.html.
When you use this type of authentication, SSL is turned on automatically.
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.
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?
String[] getHeaderNames()
String[] getRequestHeaders()
java.util.Iterator getHeaderNames()
java.util.Iterator getRequestHeaders()
java.util.Enumeration getHeaderNames()
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:
10. public class SessionAgeServlet extends HttpServlet {
11. public void service(HttpServletRequest request, HttpServletResponse) throws IOException {
12. String sessionID = request.getParameter("sessionID");
13. HttpSession session = getSession(sessionID);
14. long age = // your code here
15. response.getWriter().print(age);
16. }
... // more code here
47. }
session.getMaxInactiveInterval();
session.getLastAccessed().getTime() - session.getCreationTime().getTime();
session.getLastAccessedTime().getTime() - session.getCreationTime().getTime();
session.getLastAccessed() - session.getCreationTime();
session.getMaxInactiveInterval() - session.getCreationTime();
The developer must ensure that every URL is properly encoded using the appropriate URL rewriting APIs.
The developer must provide an alternate mechanism for managing sessions and abandon the HttpSession mechanism entirely.
The developer can ignore this issue. Web containers are required to support automatic URL rewriting when cookies are not supported.
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.)
Store the data in a local variable.
Store the data in an instance variable.
Store the data in the HttpSession object.
Store the data in the ServletContext object.
It can be invoked only from the doGet or doPost methods.
It can be used independently of the getRemoteUser method.
Can return "true" even when its argument is NOT defined as a valid role name in the deployment descriptor.
Using the isUserInRole method overrides any declarative authentication related to the method in which it is invoked.
You want to create a valid directory structure for your Java EE web application, and your application uses tag files and a JAR file. Which three must be located directly in your WEB-INF directory (NOT in a subdirectory of WEB-INF)? (Choose three.)
The JAR file
A directory called lib
A directory called tags
A directory called TLDs
A directory called classes
Given:
3. class MyServlet extends HttpServlet {
4. public void doPut(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
5. // servlet code here
...
26. }
27. }
If the DD contains a single security constraint associated with MyServlet and its only <http-method> tags and <auth-constraint> tags are:
<http-method>GET</http-method>
<http-method>PUT</http-method>
<auth-constraint>Admin</auth-constraint>
A user whose role is Admin can perform a PUT.
A user whose role is Admin can perform a GET.
A user whose role is Admin can perform a POST.
A user whose role is Member can perform a PUT.
A user whose role is Member can perform a POST.
It provides centralized request handling for incoming requests.
It forces resource authentication to be distributed across web components.
It reduces coupling between presentation-tier clients and underlying business services.
It can be added and removed unobtrusively, without requiring changes to existing code.
response.setLength(numberOfBytes);
response.setContentLength(numberOfBytes);
response.setHeader("Length", numberOfBytes);
response.setIntHeader("Length", numberOfBytes);
response.setHeader("Content-Length", numberOfBytes);
Assume that a news tag library contains the tags lookup and item:
lookup Retrieves the latest news headlines and executes the tag body once for each headline.
Exposes a NESTED page-scoped attribute called headline of type com.example.Headline containing details for that headline.
<table>
<tr>
<td>
<news:lookup />
<news:item info="${headline}" />
</td>
</tr>
</table>
<td><news:item info="${headline}" /></td>
<news:lookup>
</news:lookup>
Which element of a web application deployment descriptor
<realm-name>
<security-role>
Which is a benefit of precompiling a JSP page?
It avoids initialization on the first request.
It provides the ability to debug runtime errors in the application.
It provides better performance on the first request for the JSP page.
The sl:shoppingList and sl:item tags output a shopping list to the response and are used as follows:
11. <sl:shoppingList>
12. <sl:item name="Bread" />
13. <sl:item name="Milk" />
14. <sl:item name="Eggs" />
15. </sl:shoppingList>
The tag handler for sl:shoppingList is ShoppingListTag and the tag handler for sl:item is ItemSimpleTag.
ShoppingListTag extends BodyTagSupport and ItemSimpleTag extends SimpleTagSupport.
ItemSimpleTag can find the enclosing instance of ShoppingListTag by calling getParent() and casting the result to ShoppingListTag.
ShoppingListTag can find the child instances of ItemSimpleTag by calling super.getChildren() and casting each to an ItemSimpleTag.
It is impossible for ItemSimpleTag and ShoppingListTag to find each other in a tag hierarchy because one is a Simple tag and the other is a Classic tag.
ShoppingListTag can find the child instances of ItemSimpleTag by calling getChildren() on the Page Context and casting each to an ItemSimpleTag.
ItemSimpleTag can find the enclosing instance of ShoppingListTag by calling findAncestor WithClass() on the PageContext and casting the result to ShoppingListTag.
Flyweight
Service Locator
Given tutorial.jsp:
2. <h1>EL Tutorial</h1>
3. <h2>Example 1</h2>
4. <p>
5. Dear ${my:nickname(user)}
6. </p>
<jsp-config>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-config>
<isELIgnored>true</isELIgnored>
<jsp-property-group>
<el-ignored>*.jsp</el-ignored>
</jsp-property-group>
<isElIgnored>true</isElIgnored>
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. }
session.removeAll(USE_CASE_ATTRS);
for ( String attr : USE_CASE_ATTRS ) {
session.remove(attr);
}
session.removeAttribute(attr);
session.deleteAttribute(attr); }
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.
User user = // retrieve the User object from the database
session.setDurationInterval(user.getSessionDuration());
session.setMaxDuration(user.getSessionDuration());
session.setInactiveInterval(user.getSessionDuration());
session.setDuration(user.getSessionDuration());
session.setMaxInactiveInterval(user.getSessionDuration());
<env-entry>
<env-entry-type>java.lang.Boolean</env-entry-type>
<env-entry-value>true</env-entry-value>
</env-entry>
<env-entry-name>param/MyExampleString</env-entry-name>
<env-entry-value>This is an Example</env-entry-value>
<env-entry-type>int</env-entry-type>
<env-entry-value>10</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
Given an HttpServletRequest request and an HttpServletResponse response:
41. HttpSession session = null;
42. // insert code here
43. if(session == null) {
44. // do something if session does not exist
45. } else {
46. // do something if session exists
session = response.getSession();
session = request.getSession();
session = request.getSession(true);
session = request.getSession(false);
EL
JSP
empty
dynamic
scriptless
<tld>
<uri>dbtags</uri>
<location>/WEB-INF/tlds/dbtags.tld</location>
</tld>
<taglib>
</taglib>
<tld-uri>dbtags</tld-uri>
<tld-location>/WEB-INF/tlds/dbtags.tld</tld-location>
<taglib-uri>dbtags</taglib-uri>
<taglib-location>
/WEB-INF/tlds/dbtags.tld
</taglib-location>
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>
MANAGER can do a GET on resources in the /Bar/Baz directory.
MANAGER can do a POST on any resource in the /Bar/Baz directory.
MANAGER can do a TRACE on any resource in the /Bar/Baz directory.
DEVELOPER can do a GET on resources in the /Bar/Baz directory.
DEVELOPER can do only a POST on resources in the /Bar/Baz directory.
Which two are true concerning the objects available to developers creating tag files? (Choose two.)
The session object must be declared explicitly.
The request and response objects are available implicitly.
The output stream is available through the implicit outStream object.
The servlet context is available through the implicit servletContext object.
11. <% java.util.Map map = new java.util.HashMap();
12. request.setAttribute("map", map);
13. map.put("a", "b");
14. map.put("b", "c");
15. map.put("c", "d"); %>
16. <%-- insert code here --%>
${map.c}
${map[c]}
${map["c"]}
${map.map.b}
${map[map.b]}
6. <myTag:foo bar='42'>
7. <%="processing" %>
8. </myTag:foo>
and a custom tag handler for foo which extends TagSupport.
The doStartTag method is called once.
The doAfterBody method is NOT called.
The EVAL_PAGE constant is a valid return value for the doEndTag method.
The SKIP_PAGE constant is a valid return value for the doStartTag method.
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.)
10. <context-param>
11. <param-name>footerEmail</param-name>
12. <param-value>joe@estates-r-us.biz</param-value>
13. </context-param>
Which EL code snippet will insert this context parameter into the footer?
<a href='mailto:${footerEmail}'>Contact me</a>
<a href='mailto:${initParam@footerEmail}'>Contact me</a>
<a href='mailto:${initParam.footerEmail}'>Contact me</a>
<a href='mailto:${contextParam@footerEmail}'>Contact me</a>
You want to create a filter for your web application and your filter will implement javax.servlet.Filter.
Your filter class must implement an init method and a destroy method.
Your filter class must also implement javax.servlet.FilterChain.
When your filter chains to the next filter, it should pass the same arguments it received in its doFilter method.
The method that your filter invokes on the object it received that implements
javax.servlet.FilterChain can invoke either another filter or a servlet.
Given the element from the web application deployment descriptor:
<url-pattern>/main/page1.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
and given that /main/page1.jsp contains:
<% int i = 12; %>
<b><%= i %></b>
<b></b>
<b>12</b>
The JSP fails to execute.
<% int i = 12 %>
REQUEST_URI
javax.servlet.forward.request_uri
javax.servlet.forward.REQUEST_URI
javax.servlet.request_dispatcher.request_uri
Given the definition of MyServlet:
11. public class MyServlet extends HttpServlet {
12. public void service(HttpServletRequest request,
13. HttpServletResponse response)
14. throws ServletException, IOException {
15. HttpSession session = request.getSession();
16 session.setAttribute("myAttribute","myAttributeValue");
17. session.invalidate();
18. response.getWriter().println("value=" +
19. session.getAttribute("myAttribute"));
20. }
21. }
What is the result when a request is sent to MyServlet?
An IllegalStateException is thrown at runtime.
An InvalidSessionException is thrown at runtime.
The string "value=null" appears in the response stream.
You are creating a JSP page to display a collection of data. This data can be displayed in several different ways so the architect on your project decided to create a generic servlet that generates a comma-delimited string so that various pages can render the data in different ways. This servlet takes on request parameter: objectID. Assume that this servlet is mapped to the URL pattern: /WEB-INF/data.
In the JSP you are creating, you need to split this string into its elements separated by commas and generate an HTML <ul> list from the data.
<c:import varReader='dataString' url='/WEB-INF/data'>
<c:param name='objectID' value='${currentOID}' />
</c:import>
<ul>
<c:forTokens items'${dataString.split(",")}' var='item'>
<li>${item}</li>
</c:forTokens>
</ul>
<c:forTokens items'${dataString}' delims=',' var='item'>
<c:import var='dataString' url='/WEB-INF/data'>
JSP to Transfer Object
Controller to request object
<c:if test='<%= (X > 42) %>'>
<c:then>big number</c:then>
<c:else>small number</c:else>
</c:if>
<c:if>
<c:then test='<%= (X > 42) %>'>big number</c:then>
<c:choose test='<%= (X > 42) %>'>
<c:then>big number</c:when>
<c:else>small number</c:otherwise>
</c:choose>
<c:when>big number</c:when>
<c:otherwise>small number</c:otherwise>
<c:choose>
<c:when test='<%= (X > 42) %>'>big number</c:when>
What do you need to do to reuse this tag library?
Simply rename the legacy WAR file as a JAR file and place it in your webapp's library directory.
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.
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.
http://com.example/myServlet.jsp?num=one&num=two&num=three
${param.num[0],[1] and [2]}
${paramValues[0],[1] and [2]}
${param.num[0]}, ${param.num[1]} and ${param.num[2]}
${paramValues["num"][0]}, ${paramValues["num"][1]} and ${paramValues["num"][2]}
${parameterValues.num[0]}, ${parameterValues.num[1]} and ${parameterValues.num[2]}
16. } ... // more code here
11. <servlet>
12. <servlet-name>catalog</servlet-name>
13. <jsp-file>/catalogTemplate.jsp</jsp-file>
14. <load-on-startup>10</load-on-startup>
15. </servlet>
Which two are true? (Choose two.)
Line 13 is not valid for a servlet declaration.
Line 14 is not valid for a servlet declaration.
One instance of the servlet will be loaded at startup.
Ten instances of the servlet will be loaded at startup.
You are creating a library of custom tags that mimic the HTML form tags.
When the user submits a form that fails validation, the JSP form is forwarded back to the user. The <t:textField> tag must support the ability to re-populate the form field with the request parameters from the user's last request. For example, if the user entered "Samantha" in the text field called firstName, then the form is re-populated like this:
<input type='text' name='firstName' value='Samantha' />
public int doStartTag() throws JspException {
JspContext ctx = getJspContext();
String value = ctx.getParameter(this.name);
if ( value == null ) value = "";
JspWriter out = pageContext.getOut();
try {
out.write(String.format(INPUT, this.name, value));
} (Exception e) { throw new JspException(e); }
return SKIP_BODY;
private static String INPUT
= "<input type='text' name='%s' value='%s' />";
public void doTag() throws JspException {
ServletRequet request = pageContext.getRequest();
String value = request.getParameter(this.name);
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:
Which code snippet deletes these attributes from the session object?
session.deleteAttribute(attr);
Transfer Object
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?
Add attributes to the session object.
Add parameters to the request object.
Use the pageContext object to add request attributes.
Which two JSTL URL-related tags perform URL rewriting?
(Choose two.)
url
param
<jsp:declaration>
int count = 0;
<%! int count = 0; %>
<jsp:declaration.instance>
<jsp:scriptlet.declaration>
Given the two security constraints in a deployment descriptor:
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 -->
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.)
<auth-constraint/>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
<role-name>ANY</role-name>
<role-name>MARKETING</role-name>
Add attributes on the request object.
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionValueListener
javax.servlet.http.HttpSessionBindingListener
For a given ServletResponse response, which two retrieve an object for writing text data? (Choose two.)
response.getWriter()
response.getOutputStream()
response.getOutputWriter()
response.getWriter().getOutputStream()
javax.servlet.http.HttpSessionAttributeListener
For an HttpServletResponse response, which two create a custom header?(Choose two.)
response.setHeader("X-MyHeader", "34");
response.addHeader("X-MyHeader", "34");
response.setHeader(new HttpHeader("X-MyHeader", "34"));
response.addHeader(new HttpHeader("X-MyHeader", "34"));
response.addHeader(new ServletHeader("X-MyHeader", "34"));
Given that a scoped attribute cart exists only in a user's session, which two, taken independently, ensure the scoped attribute cart no longer exists? (Choose two.)
${cart = null}
<c:remove var="cart" />
<c:remove var="${cart}" />
<c:remove var="cart" scope="session" />
<c:remove scope="session">cart</c:remove>
<c:remove var="${cart}" scope="session" />
${productID}
${params.productID}
${paramValues.productID}
Assume the tag handler for a st:simple tag extends SimpleTagSupport. In
set the body content type to JSP in the TLD
Scriptlet code is NOT legal in the body of st:simple.
add scripting-enabled="true" to the start tag for the st:simple element
add a pass-through Classic tag with a body content type of JSP to the body of st:simple, and place the scriptlet code in the body of that tag
You are building a dating service web site. Part of the form to submit a
client's profile is a group of radio buttons for the person's hobbies:
20. <input type='radio' name='hobbyEnum' value='HIKING'>Hiking <br>
21. <input type='radio' name='hobbyEnum' value='SKIING'>Skiing <br>
22. <input type='radio' name='hobbyEnum' value='SCUBA'>SCUBA Diving
23. <!-- and more options -->
After the user submits this form, a confirmation screen is displayed with these hobbies listed. Assume
that an application-scoped variable, hobbies, holds a map between the Hobby enumerated type and the
display name.
${hobbies[hobbyEnum[N]}
${hobbies[paramValues.hobbyEnum[N]]}
${hobbies[paramValues@'hobbyEnum'@N]}
${hobbies.get(paramValues.hobbyEnum[N])}
<jsp:insert page='${bodyURL}' />
<jsp:insert file='${bodyURL}' />
<jsp:include page='${bodyURL}' />
<jsp:include file='${bodyURL}' />
<jsp:insert page='<%= bodyURL %>' />
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?
getCreationTime
You need to retrieve the username cookie from an HTTP request. If this cookie does NOT exist, then the c variable will be null.
10. Cookie c = request.getCookie("username");
10. Cookie c = null;
11. for ( Iterator i = request.getCookies();
12. i.hasNext(); ) {
13. Cookie o = (Cookie) i.next();
14. if ( o.getName().equals("username") ) {
15. c = o;
16. break;
17. }
18. }
11. for ( Enumeration e = request.getCookies();
12. e.hasMoreElements(); ) {
13. Cookie o = (Cookie) e.nextElement();
11. Cookie[] cookies = request.getCookies();
12. for ( int i = 0; i < cookies.length; i++ ) {
13. if ( cookies[i].getName().equals("username") ) {
14. c = cookies[i];
15. break;
tag
page
taglib
include
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.
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
public class UserPrefLoader implements SessionListener {
public void sessionCreated(SessionEvent se) {
MyPrefsFactory myFactory = (MyPrefsFactory) se.getContext().getAttribute("myPrefsFactory");
se.getSession().addAttribute("prefs", userPrefs);
public void sessionInitialized(HttpSessionEvent se) {
se.getHttpSession().setAttribute("prefs", userPrefs);
public void sessionInitialized(SessionEvent se) {
Given an EL function declared with:
11. <function>
12. <name>spin</name>
13. <function-class>com.example.Spinner</function-class>
14. <function-signature>
15. java.lang.String spinIt()
16. </function-signature>
17. </function>
The function method must have the signature:
public String spin().
The method must be mapped to the logical name "spin" in the web.xml file.
public String spinIt().
The function method must have the signature
public static String spin().
public static String spinIt().
Classic tag handlers and tag files CANNOT reside in the same tag library.
A file named foo.tag, located in /WEB-INF/tags/bar, is recognized as a tag file by the container.
A file named foo.tag, bundled in a JAR file but NOT defined in a TLD, triggers a container translation error.
A file named foo.tag, located in a web application's root directory, is recognized as a tag file by the container.
You need to create a JSP that generates some JavaScript code to populate an array of strings used on the client-side. Which JSP code snippet will create this array?
MY_ARRAY = new Array();
<% for ( int i = 0; i < serverArray.length; i++ ) {
MY_ARRAY[<%= i %>] = '<%= serverArray[i] %>';
} %>
MY_ARRAY[${i}] = '${serverArray[i]}';
<% for ( int i = 0; i < serverArray.length; i++ ) { %>
<% } %>
A web application contains a tag file called beta.tag in /WEB-INF/tags/alpha.
A JSP page called sort.jsp exists in the web application and contains only this JSP code:
1. <%@ taglib prefix="x"
2. tagdir="/WEB-INF/tags/alpha" %>
3. <x:beta />
The sort.jsp page is requested.
Tag files can only be accessed using a tagdir attribute.
The sort.jsp page translates successfully and invokes the tag defined by beta.tag.
The sort.jsp page produces a translation error because a taglib directive must always have a uri attribute.
Tag files can only be placed in /WEB-INF/tags, and NOT in any subdirectories of /WEB-INF/tags.
The tagdir attribute in line 2 can be replaced by a uri attribute if a TLD referring to beta.tag is created and added to the web application.
Front Controller and Transfer Object
Front Controller and Service Locator
Business Delegate and Transfer Object
Business Delegate and Intercepting Filter
<c:import url="foo.jsp"/>
<c:import page="foo.jsp"/>
<c:include url="foo.jsp"/>
<c:include page="foo.jsp"/>
Given a web application in which the cookie userName is expected to contain the name of the user. Which EL expression evaluates to that user name?
${userName}
${cookie.userName}
${cookie.user.name}
${cookies.userName[0]}
${cookies.userName}[1]
15. // insert code here
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?
response.setError(302);
response.sendError(302);
response.setStatus(302);
response.sendRedirect(302);
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.
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.
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.
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.
In a JSP-centric web application, you need to create a catalog browsing JSP page. The catalog is stored as a List object in the catalog attribute of the webapp's ServletContext object.
Which scriptlet code snippet gives you access to the catalog object?
<% List catalog = config.getAttribute("catalog"); %>
<% List catalog = context.getAttribute("catalog"); %>
<% List catalog = application.getAttribute("catalog"); %>
10. public void service(ServletRequest request,
11. ServletResponse response) {
12. ServletInputStream sis =
13. // insert code here
14. }
Which retrieves the binary input stream on line 13?
request.getWriter();
request.getReader();
request.getInputStream();
request.getResourceAsStream();
authorization
You are creating a content management system (CMS) with a web
application front-end. The JSP that displays a given document in the CMS has the following general
structure:
1. <%-- tag declaration --%>
2. <t:document>
11. <t:paragraph>... <t:citation docID='xyz' /> ...</t:paragraph>
99. </t:document>
The citation tag must store information in the document tag for the document tag to generate a reference section at the end of the generated web page.
The document tag handler follows the Classic tag model and the citation tag handler follows the Simple
tag model. Furthermore, the citation tag could also be embedded in other custom tags that could have
either the Classic or Simple tag handler model.
public void doTag() {
JspTag docTag = findAncestorWithClass(this, DocumentTag.class);
((DocumentTag)docTag).addCitation(this.docID);
public void doStartTag() {
Tag docTag = findAncestor(this, DocumentTag.class);
Access to session-scoped attributes is guaranteed to be thread-safe by the web container.
To activate URL rewriting, the developer must use the HttpServletResponse. setURLRewriting method.
If the web application uses HTTPS, then the web container may use the data on the HTTPS request stream to identify the client.
<permit-scripting>false</permit-scripting>
Given a JSP page:
11. <n:recurse>
12. <n:recurse>
13. <n:recurse>
14. <n:recurse />
15. </n:recurse>
16. </n:recurse>
17. </n:recurse>
The tag handler for n:recurse extends SimpleTagSupport.
It is impossible to determine the deepest nesting depth because it is impossible for tag handlers that extend SimpleTagSupport to communicate with their parent and child tags.
Create a private non-static attribute in the tag handler class called count of type int initialized to 0. Increment count in the doTag method. If the tag has a body, invoke the fragment for that body. Otherwise, output the value of count.
Start a counter at 1. Call getChildTags(). If it returns null, output the value of the counter. Otherwise, increment counter and continue from where getChildTags() is called. Skip processing of the body.
Given in a single JSP page:
<%@ taglib prefix='java' uri='myTags' %>
<%@ taglib prefix='JAVA' uri='moreTags' %>
The prefix 'java' is reserved.
The URI 'myTags' must be properly mapped to a TLD file by the web container.
A translation error occurs because the prefix is considered identical by the web container.
You are building a web application with a scheduling component. On the JSP, you need to show the current date, the date of the previous week, and the date of the next week. To help you present this information, you have created the following EL functions in the 'd' namespace:
name: curDate; signature: java.util.Date currentDate()
name: addWeek; signature: java.util.Date addWeek(java.util.Date, int)
name: dateString; signature: java.util.String getDateString(java.util.Date)
${d:dateString(addWeek(curDate(), -1))}
${d:dateString[addWeek[curDate[], -1]]}
${d:dateString[d:addWeek[d:curDate[], -1]]}
The <body-content> element in the echo tag TLD must have the value JSP.
The echo tag handler must define the setAttribute(String key, String value) method.
The <dynamic-attributes>true</dynamic-attributes> element must appear in the echo tag TLD.
The class implementing the echo tag handler must implement the javax.servlet.jsp.tagext.Dynamic Attributes interface.
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?
Create an HttpSessionAttributeListener class and implement the attributeDeleted method and log the attribute name using the getName method on the event object.
Create an HttpSessionAttributeListener class and implement the attributeRemoved method and log the attribute name using the getName method on the event object.
Create an SessionAttributeListener class and implement the attributeRemoved method and log the attribute name using the getAttributeName method on the event object.
Create an SessionAttributeListener class and implement the attributeDeleted method and log the attribute name using the getAttributeName method on the event object.
In the init method.
In the constructor of the JSP's Java code.
In a JSP declaration, which includes an initializer block.
5. public class MyTagHandler extends TagSupport {
6. public int doStartTag() throws JspException {
7. try {
8. // insert code here
9. } catch(Exception ex) { /* handle exception */ }
10. return super.doStartTag();
11. }
42. }
Which code snippet, inserted at line 8, causes the value foo to be output?
JspWriter w = pageContext.getOut();
w.print("foo");
JspWriter w = pageContext.getWriter();
JspWriter w = new JspWriter(pageContext.getWriter());
JspWriter w = new JspWriter(pageContext.getResponse());
Every page of your web site must include a common set of navigation menus at the top of the page. This menu is static HTML and changes frequently, so you have decided to use JSP's static import mechanism.
<%@ import file='/common/menu.html' %>
<%@ page import='/common/menu.html' %>
<%@ import page='/common/menu.html' %>
<%@ include file='/common/menu.html' %>
<%@ page include='/common/menu.html' %>
Proxy
Front Controller
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.)
Given this fragment in a servlet:
23. if(req.isUserInRole("Admin")) {
24. // do stuff
25. }
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>
Line 24 can never be reached.
The deployment descriptor is NOT valid.
If line 24 executes, the user's role will be Admin.
If line 24 executes, the user's role will be Administrator.
A developer is designing a web application that must support multiple
interfaces, including:
an XML web service for B2B
HTML for web-based clients
WML for wireless customers
Session Fa�ade
Data Access Object
Which two are characteristics of the Transfer Object design pattern? (Choose two.)
It reduces network traffic by collapsing multiple remote requests into one.
It increases the complexity of the remote interface by removing coarse-grained methods.
It increases the complexity of the design due to remote synchronization and version control issues.
Assume a JavaBean com.example.GradedTestBean exists and has two attributes. The attribute name is of type java.lang.String and the attribute score is of type java.lang.Integer.
An array of com.example.GradedTestBean objects is exposed to the page in a request-scoped attribute called results. Additionally, an empty java.util.HashMap called resultMap is placed in the page scope.
A JSP page needs to add the first entry in results to resultMap, storing the name attribute of the bean as the key and the score attribute of the bean as the value.
${resultMap[results[0].name] = results[0].score}
<c:set var="${resultMap}" key="${results[0].name}"
value="${results[0].score}" />
<c:set var="resultMap" property="${results[0].name}">
${results[0].value}
</c:set>
<c:set var="resultMap" property="${results[0].name}"
<c:set target="${resultMap}" property="${results[0].name}"
You are building a dating web site. The client's date of birth is collected along with lots of other information. You have created an EL function with the signature: calcAge(java.util.Date):int and it is assigned to the name, age, in the namespace, funct. In one of your JSPs you need to print a special message to clients who are younger than 25. Which EL code snippet will return true for this condition?
${calcAge(client.birthDate) < 25}
${funct:age(client.birthDate) < 25}
<jsp:import file='foo.jsp' />
<jsp:import page='foo.jsp' />
<jsp:include page='foo.jsp' />
<jsp:include file='foo.jsp' />
<jsp:import>foo.jsp</jsp:import>
<html xmlns:jsp="http://java.sun.com/JSP/Page"
version="2.0">
<jsp:directive.taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" />
<!-- page content -->
</html>
version="2.0"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
</jsp:root>
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.)
The method that your filter invokes on the object it received that implements javax.servlet.FilterChain can invoke either another filter or a servlet.
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpSessionContext
javax.servlet.http.HttpServletResponse
javax.servlet.http.HttpSessionBindingEvent