SCWCD(310-083) 101~150

Q: 101 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
解析:HttpSessionListener类只有sessionCreated和sessionDestroyed方法

Q: 102 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
解析:监听会话添加属性用HttpSessionAttributeListener

Q: 103 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
解析:
encodeURL和encodeRedirectURL都可用于URL重新
encodeRedirectURL用于sendRedirect方法

Q: 104 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
解析:HttpSession的setMaxInactiveInterval方法设置最长持续时间

Q: 105 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
解析:
HttpServletRequest接口和HttpSessionBindingEvent类提供getSession方法,
HttpSessionContext也提供,但该类的方法已经被废除,
没有HttpSessionAttributeEvent这个类

Q: 106 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
解析:(同40题)E.只有DEVELOPER有POST的访问权,但不是只有。

Q: 107 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
解析:使用加密通道POST(HTTPS)保证信息的真实性。

Q: 108 Which mechanism requires the client to provide its public key certificate?
A.HTTP Basic Authentication
B.Form Based Authentication
C.HTTP Digest Authentication
D.HTTPS Client Authentication
Answer: D
解析:HTTPS要求客户端提供安全证书。

Q: 109 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-constraint>
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
解析:两个安全限制有同样的内容,即SALES不用设置了(SALES设置貌似重复了)。
A.标签体内容为空,即谁也不能访问。
C.声明ANY用户可以访问

Q: 110 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>
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
解析:Admin链接到Administrator,判断Admin实际是判断Administrator.

Q: 111 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
解析:
B.使用Basic安全认证的,目标服务是非认证的。
D.非安全的访问只能访问公开资源。
Q: 112 Given:
11. <%
12. request.setAttribute("vals", new String[]{"1","2","3","4"});
13. request.setAttribute("index", "2");
14. %>
15. <%-- insert code here --%>
Which three EL expressions, inserted at line 15, are valid and evaluate to "3"? (Choose three.)
A.${vals.2}
B.${vals["2"]}
C.${vals.index}
D.${vals[index]}
E.${vals}[index]
F.${vals.(vals.index)}
G.${vals[vals[index-1]]}
Answer: B, D, G
解析:EL格式,G.先获取字符串的"2",再获取下标为"2"的值"3".

Q: 113 Given:
11. <% java.util.Map map = new java.util.HashMap();
12. request.setAttribute("map", map);
13. map.put("a", "true");
14. map.put("b", "false");
15. map.put("c", "42"); %>
Which three EL expressions are valid and evaluate to true? (Choose three.)
A.${not map.c}
B.${map.b or map.a}
C.${map.a and map.b}
D.${map.false or map.true}
E.${map.a and map.b or map.a}
F.${map['true'] or map['false']}
Answer: A, B, E
解析:
A.not false =true(强制转换Boolean.valueOf("42")为false)
B.true or false = true
E.true and false or true =true

Q: 114 Given:
http://com.example/myServlet.jsp?num=one&num=two&num=three
Which two produce the output "one, two and three"? (Choose two.)
A. ${param.num[0],[1] and [2]}
B.${paramValues[0],[1] and [2]}
C.${param.num[0]}, ${param.num[1]} and ${param.num[2]}
D.${paramValues.num[0]}, ${paramValues.num[1]} and ${paramValues.num[2]}
E.${paramValues["num"][0]}, ${paramValues["num"][1]} and ${paramValues["num"][2]}
F.${parameterValues.num[0]}, ${parameterValues.num[1]} and ${parameterValues.num[2]}
G.${parameterValues["num"]["0"]}, ${parameterValues["num"]["1"]} and ${parameterValues["num"]["2"]}
Answer: D, E
解析:
${paramValues.num}等于request.getParameterValues("num")
${param.num}等于request.getParameter("num")

Q: 115 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?
A.${userName}
B.${cookie.userName}
C.${cookie.user.name}
D.${cookies.userName[0]}
E.${cookies.userName}[1]
F.${cookies.get('userName')}
Answer: B
解析:EL表达式能直接访问属性。相当于request.getCookies.getuserName

Q: 116 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>
Which two are true? (Choose two.)
A. The function method must have the signature:
public String spin().
B. The method must be mapped to the logical name "spin" in the web.xml file.
C. The function method must have the signature:
public String spinIt().
D. The function method must have the signature
public static String spin().
E. The function method must have the signature:
public static String spinIt().
F. The function class must be named Spinner, and must be in the package com.example.
Answer: E, F
解析:
E.从声明中可知标记方法为为String spinIt(),静态调用所以是static标记的。
F.见声明中的function-class

Q: 117 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.
Assuming an n:recurse tag can either contain an empty body or another n:recurse tag, which strategy
allows the tag handler for n:recurse to output the nesting depth of the deepest n:recurse tag?
A. It is impossible to determine the deepest nesting depth because it is impossible for tag handlers that extend
SimpleTagSupport to communicate with their parent and child tags.
B. Create a private 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.
C. Start a counter at 1. Call getChildTags(). If it returns null, output the value of the counter. Otherwise,
increment counter and continue from where getChildTags() is called. Skip processing of the body.
D. If the tag has a body, invoke the fragment for that body.Otherwise, start a counter at 1. Call getParent(). If it
returns null, output the value of the counter Otherwise, increment the counter and continue from where
getParent() is called.
Answer: D
解析:从最里面有标签体的算起,调用父节点计算层次。

Q: 118 Click the Exhibit button.
The h:highlight tag renders its body, highlighting an arbitrary number of words, each of which is passed
as an attribute (word1, word2, ...). For example, a JSP page can invoke the h:highlight tag as follows:
11. <h:highlight color="yellow" word1="high" word2="low">
12. high medium low
13. </h:highlight>
Given that HighlightTag extends SimpleTagSupport, which three steps are necessary to implement the
tag handler for the highlight tag? (Choose three).

<?xml version="1.0" encoding="UTF-8"?>
<taglib xml="http://java.sun.com/xml/ns/j2ee"
xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"  version="2.0">
    <tlib-version>1.0</tlib-version>
    <short-name>h</short-name>
    <uri>http://example.com/tld/highlight</uri>
    <tag>
        <name>highlight</name>
        <tag-class>com.example.HighlightTag</tag-class>
        <body-content>scriptless</body-content>
        <attribute>
            <name>color</name>
            <required>true</required>
        </attribute>
        <dynamic-attributes>true</dynamic-attributes>
    </tag>
</taglib>

A.add a doTag method
B.add a doStartTag method
C.add a getter and setter for the color attribute
D.create and implement a TagExtraInfo class
E.implement the DynamicAttributes interface
F.add a getter and setter for the word1 and word2 attributes
Answer: A, C, E
解析:
A.继承SimpleTagSupport应实现doTag方法
C.设置颜色属性
E.实现动态属性接口

Q: 119 Given:
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?
A. JspWriter w = pageContext.getOut();
   w.print("foo");
B. JspWriter w = pageContext.getWriter();
   w.print("foo");
C. JspWriter w = new JspWriter(pageContext.getWriter());
   w.print("foo");
D. JspWriter w = new JspWriter(pageContext.getResponse());
   w.print("foo");
Answer: A
解析:PageContext继承JspContext
JspContext的getOut返回JspWriter类型
PageContext和JspContext都没有getWriter方法。

Q: 120 Given:
6. <myTag:foo bar='42'>
7. <%="processing" %>
8. </myTag:foo>
and a custom tag handler for foo which extends TagSupport.
Which two are true about the tag handler referenced by foo? (Choose two.)
A.The doStartTag method is called once.
B.The doAfterBody method is NOT called.
C.The EVAL_PAGE constant is a valid return value for the doEndTag method.
D.The SKIP_PAGE constant is a valid return value for the doStartTag method.
E.The EVAL_BODY_BUFFERED constant is a valid return value for the doStartTag method.
Answer: A, C
解析:
A.doStartTag最早执行
B.doAfterBody在执行标签体后执行。
C.EVAL_PAGE继续处理页面,可供doEndTag()使用
D.SKIP_PAGE忽略对余下页面的处理,可供doEndTag()使用
E.EVAL_BODY_BUFFERED申请缓冲区,有setBodyContext()函数得到BodyContext对象(处理在doStartTag之后)

Q: 121 Which three are valid values for the body-content attribute of a tag
directive in a tag file? (Choose three.)
A.EL
B.JSP
C.empty
D.dynamic
E.scriptless
F.tagdependent
Answer: C, E, F
解析:
标签文件中可用的指令有empty、scriptless(java语法)和tagdependent(tag依赖)

Q: 122 The Squeaky Bean company has decided to port their web application to a
new J2EE 1.4 container. While reviewing the application, a developer realizes that in multiple places
within the current application, nearly duplicate code exists that finds enterprise beans. Which pattern
should be used to eliminate this duplicate code?
A.Transfer Object
B.Front Controller
C.Service Locator
D.Intercepting Filter
E.Business Delegate
F.Model-View-Controller
Answer: C
解析:(同56题)Service Locator利用统一的服务器访问方法,减少重复。
 
Q: 123 A developer is designing a web application that makes many fine-grained
remote data requests for each client request. During testing, the developer discovers that the volume of
remote requests significantly degrades performance of the application. Which design pattern provides a
solution for this problem?
A.Flyweight
B.Transfer Object
C.Service Locator
D.Dispatcher View
E.Business Delegate
F.Model-View-Controller
Answer: B
解析:
B.传输对象,减少颗粒度。

Q: 124 In an n-tier application, which two invocations are typically remote, not
local? (Choose two.)
A.JSP to Transfer Object
B.Service Locator to JNDI
C.Controller to request object
D.Transfer Object to Entity Bean
E.Controller to Business Delegate
F.Business Delegate to Service Locator
Answer: B, D
解析:
B.服务器定位调用JNDI。
D.调用实体bean。

Q: 125 A developer has created a special servlet that is responsible for generating
XML content that is sent to a data warehousing subsystem. This subsystem uses HTTP to request these
large data files, which are compressed by the servlet to save internal network bandwidth. The developer
has received a request from management to create several more of these data warehousing servlets. The
developer is about to copy and paste the compression code into each new servlet. Which design pattern
can consolidate this compression code to be used by all of the data warehousing servlets?
A.Facade
B.View Helper
C.Transfer Object
D.Intercepting Filter
E.Composite Facade
Answer: D
解析:(同58题)拦截器过滤,预处理数据。

Q: 126 A developer is designing the presentation tier for a web application which
requires a centralized request handling to complete common processing required by each request. Which
design pattern provides a solution to this problem?
A.Remote Proxy
B.Front Controller
C.Service Activator
D.Intercepting Filter
E.Business Delegate
F.Data Access Object
Answer: B
解析:Front Controller(前端控制器)在web应用的前端(Front)设置一个
入口控制器(Controller),统一处理所以请求。

Q: 127 You are designing an n-tier Java EE application. You have already
decided that some of your JSPs will need to get data from a Customer entity bean. You are trying to
decide whether to use a Customer stub object or a Transfer Object. Which two statements are true?
(Choose two.)
A.The stub will increase network traffic.
B.The Transfer Object will decrease data staleness.
C.The stub will increase the logic necessary in the JSPs.
D.In both cases, the JSPs can use EL expressions to get data.
E.Only the Transfer Object will need to use a Business Delegate.
F.Using the stub approach allows you to design the application without using a Service Locator.
Answer: A, D
解析:
A.传输对象能减少颗粒度,但会增加网络浏览。
D.JSP可以使用EL表达式获得数据。

Q: 128 You have a simple web application that has a single Front Controller
servlet that 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
解析:
使用fromat设置带参数的url地址
服务器重定向方法:
javax.servlet.RequestDispatcher的forward方法
javax.servlet.http.HttpServletResponse的sendRedirect方法

Q: 129 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
解析:上下文参数(context parameters)不能在部署文件插入内容。

Q: 130 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
解析:
HttpSessionListenter的sessionCreated()和sessionDestroyed()监听当前session的创建和销毁情况
HttpSessionBindingListener的valueBound()和valueUnbound()监听数据的绑定和取消绑定(removeAttribute会触发valueUnbound事件)

Q: 131 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
解析:
A.过滤器必须实现初始化和销毁方法
D.FilterChain能够调用下一个过滤器或者servlet

Q: 132 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
解析:
HttpSessionListener监听session的创建和销毁
HttpSessionEvent只有getSession()方法。
(另外HttpSessionEvent没有getServletContext方法,HttpSession才有,可能题目有误)

Q: 133 Given the web application deployment descriptor elements:
11.<filter>
12.<filter-name>ParamAdder</filter-name>
13.<filter-class>com.example.ParamAdder</filter-class>
14.</filter>
...
24.<filter-mapping>
25.<filter-name>ParamAdder</filter-name>
26.<servlet-name>MyServlet</servlet-name>
27.<!-- insert element here -->
28.</filter-mapping>
Which element, inserted at line 27, causes the ParamAdder filter to be applied when MyServlet is
invoked by another servlet using the RequestDispatcher.include method?
A.<include/>
B.<dispatcher>INCLUDE</dispatcher>
C.<dispatcher>include</dispatcher>
D.<filter-condition>INCLUDE</filter-condition>
E.<filter-condition>include</filter-condition>
Answer: B
解析:
<dispatcher></dispatcher>指定被过滤的方法,
有四个可能值:REQUEST,FORWARD,INCLUDE和ERROR,默认为REQUEST。

Q: 134 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
解析:从servlet向jsp传送数据,而且不能被其它servlet访问,可以跳转前添加到request作用域。

Q: 135 A JSP page needs to set the property of a given JavaBean to a value that is
calculated with the JSP page. Which three jsp:setProperty attributes must be used to perform this
initialization? (Choose three.)
A.id
B.val
C.name
D.param
E.value
F.property
G.attribute
Answer: C, E, F
解析:
jsp:setProperty有四个属性:
name:必须,要设置属性的bean
property:必须,要设置的属性
value:可选,指定bean的属性的值
param:可选,指定请求参数作为bean属性的值
(value和param二选一)

Q: 136 Your web application views all have the same header, which includes the
<title> tag in the <head> element of the rendered HTML. You have decided to remove this redundant
HTML code from your JSPs and put it into a single JSP called /WEB-INF/jsp/header.jsp. However, the
title of each page is unique, so you have decided to use a variable called pageTitle to parameterize this in
the header JSP, like this:
10. <title>${param.pageTitle}<title>
Which JSP code snippet should you use in your main view JSPs to insert the header and pass the
pageTitle variable?
A. <jsp:insert page='/WEB-INF/jsp/header.jsp'>
   ${pageTitle='Welcome Page'}
   </jsp:insert>
B. <jsp:include page='/WEB-INF/jsp/header.jsp'>
   ${pageTitle='Welcome Page'}
   </jsp:include>
C. <jsp:include file='/WEB-INF/jsp/header.jsp'>
   ${pageTitle='Welcome Page'}
   </jsp:include>
D. <jsp:insert page='/WEB-INF/jsp/header.jsp'>
   <jsp:param name='pageTitle' value='Welcome Page' />
   </jsp:insert>
E. <jsp:include page='/WEB-INF/jsp/header.jsp'>
   <jsp:param name='pageTitle' value='Welcome Page' />
   </jsp:include>
Answer: E
解析:El表达式不能用来赋值。
<jsp:include page="">动态调用页面。
jsp:param将一个参数加入当前参数组。

Q: 137 A JSP page needs to instantiate a JavaBean to be used by only that page.
Which two jsp:useBean attributes must be used to access this attribute in the JSP page? (Choose two.)
A.id
B.type
C.name
D.class
E.scope
F.create
Answer: A, D
解析:
jsp:useBean属性
id 引用该Bean的变量。
class 该Bean的完整包名。

Q: 138 Click the Exhibit button.
Given the HTML form:
1. <html>
2. <body>
3. <form action="submit.jsp">
4. Name: <input type="text" name="i1"><br>
5. Price: <input type="text" name="i2"><br>
6. <input type="submit">
7. </form>
8. </body>
9. </html>
Assume the product attribute does NOT yet exist in any scope.
Which code snippet, in submit.jsp, instantiates an instance of com.example.Product that contains the
results of the form submission?

package com.example;

public class Product{
    private String name;
    private double price;
    public Product(){
    this("Default",0.0);
    }
    public Product(String name,double price){
    this.name=name;
    this.price=price;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getPrice() {
    return price;
    }
    public void setPrice(double price) {
    this.price = price;
    }
}

A. <jsp:useBean id="com.example.Product" />
   <jsp:setProperty name="product" property="*" />
B. <jsp:useBean id="product" class="com.example.Product" />
   ${product.name = param.i1}
   ${product.price = param.i2}
C. <jsp:useBean id="product" class="com.example.Product">
   <jsp:setProperty name="product" property="name"  param="i1" />
   <jsp:setProperty name="product" property="price"  param="i2" />
   </jsp:useBean>
D. <jsp:useBean id="product" type="com.example.Product">
   <jsp:setProperty name="product" property="name" value="<%= request.getParameter( "i1" ) %>" />
   <jsp:setProperty name="product" property="price" value="<%= request.getParameter( "i2" ) %>" />
   </jsp:useBean>
Answer: C
解析:
jsp:useBean必须有id和class(包名)
jsp:setProperty设置bean属性,name为bean名,property为属性,param将请求参数作为指定属性的值。

Q: 139 Click the Task button.
Place the events in the order they occur.
Answer: Check ExamWorx eEngine, Download from Member Center

解析:Servlet执行顺序。


Q: 140 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
解析:设置头文件
HttpServletResponse.addHeader(java.lang.String name,java.lang.String value)
HttpServletResponse.setHeader(java.lang.String name,java.lang.String value)

Q: 141 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
解析:
HttpServletRequest.getHeaderNames 以Enumeration返回所有请求头的名字。
没有getRequestHeaders()方法。

Q: 142 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
解析:
设置cookie用HttpServletResponse.addCookie(Cookie cookie)

Q: 143 Click the Task button.
Given a request from mybox.example.com, with an IP address of 10.0.1.11 on port 33086, place the
appropriate ServletRequest methods onto their corresponding return values.
Answer: Check ExamWorx eEngine, Download from Member Center

解析:
getServerPort返回请求所使用端口
getServerAddr返回请求所指向主机地址(API没有该方法)
getServerName返回请求所指向主机名
getRemotePort返回客户端端口
getRemoteAddr返回客户端ip
getRemoteHost返回客户端主机名

Q: 144 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
解析:
PUT 请求服务器存储一个资源
DELETE 请求服务器删除资源

Q: 145 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. Which JSP code snippet accomplishes this goal?
A.<%@ import file='/common/menu.html' %>
B.<%@ page import='/common/menu.html' %>
C.<%@ import page='/common/menu.html' %>
D.<%@ include file='/common/menu.html' %>
E.<%@ page include='/common/menu.html' %>
F.<%@ include page='/common/menu.html' %>
Answer: D
<%@include file="">编译时导入该页面,即静态调用。

Q: 146 For manageability purposes, you have been told to add a "count" instance
variable to a critical JSP Document so that a JMX MBean can track how frequent this JSP is being
invoked. Which JSP code snippet must you use to declare this instance variable in the JSP Document?
A. <jsp:declaration>
int count = 0;
<jsp:declaration>
B. <%! int count = 0; %>
C. <jsp:declaration.instance>
int count = 0;
<jsp:declaration.instance>
D. <jsp:scriptlet.declaration>
int count = 0;
<jsp:scriptlet.declaration>
Answer: A
解析:jspx声明方法为<jsp:declaration></jsp:declaration>(题中结束标记有误)

Q: 147 You have a new IT manager that has mandated that all JSPs must be
refactored to include no scritplet code. The IT manager has asked you to enforce this. Which deployment
descriptor element will satisfy this constraint?
A. <jsp-property-group>
   <url-pattern>*.jsp</url-pattern>
   <permit-scripting>false</permit-scripting>
   </jsp-property-group>
B. <jsp-config>
   <url-pattern>*.jsp</url-pattern>
   <permit-scripting>false</permit-scripting>
   </jsp-config>
C. <jsp-config>
   <url-pattern>*.jsp</url-pattern>
   <scripting-invalid>true</scripting-invalid>
   </jsp-config>
D. <jsp-property-group>
   <url-pattern>*.jsp</url-pattern>
   <scripting-invalid>true</scripting-invalid>
   </jsp-property-group>
Answer: D
解析:
<jsp-property-group>对多个具有相同属性的JSP统一定义
<url-pattern>设置值影响的范围
<scripting-incalid>若为true表示不支持scripting语法

Q: 148 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?
A. MY_ARRAY = new Array();
<% for ( int i = 0; i < serverArray.length; i++ ) {
MY_ARRAY[<%= i %>] = '<%= serverArray[i] %>';
} %>
B. MY_ARRAY = new Array();
<% for ( int i = 0; i < serverArray.length; i++ ) {
MY_ARRAY[${i}] = '${serverArray[i]}';
} %>
C. MY_ARRAY = new Array();
<% for ( int i = 0; i < serverArray.length; i++ ) { %>
MY_ARRAY[<%= i %>] = '<%= serverArray[i] %>';
<% } %>
D. MY_ARRAY = new Array();
<% for ( int i = 0; i < serverArray.length; i++ ) { %>
MY_ARRAY[${i}] = '${serverArray[i]}';
<% } %>
Answer: C
解析:
scripting中不能包含scripting
EL不能获取scripting中的属性

Q: 149 You are building a Front Controller using a JSP page and you need to
determine if the user's session has NOT been created yet and perform some special processing for this
case. Which scriptlet code snippet will perform this test?
A. <% if ( request.getSession(false) == null ) {
// special processing
} %>
B. <% if ( request.getHttpSession(false) == null ) {
// special processing
} %>
C. <% if ( requestObject.getSession(false) == null ) {
// special processing
} %>
D. <% if ( requestObject.getHttpSession(false) == null ) {
// special processing
} %>
Answer: A
解析:
getSession都是返回当前用户的会话对象,参数的区别在于
参数为true,如果“当前用户的会话对象”为空(第一次访问时)则创建一个新的会话对象返回
参数为false,如果“当前用户的会话对象”为空,则返回null(即不自动创建会话对象)


Q: 150 You are creating a new JSP page and you need to execute some code that
acts when the page is first executed, but only once. Which three are possible mechanisms for performing
this initialization code? (Choose three.)
A.In the init method.
B.In the jspInit method.
C.In the constructor of the JSP's Java code.
D.In a JSP declaration, which includes an initializer block.
E.In a JSP declaration, which includes a static initializer block.
Answer: B, D, E
解析:(同89题)
A.只有servlet才有init方法
C.jsp没有构造方法。
D.动态块,初始化是运行一次,相当于构造方法
E.静态块,运行时只执行一次。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值