You are on page 1of 51

1.

Why does the JSP code shown in the above sample code cause a compilation error? y and x are out of scope The value of x is not initialized. The value of y is not initialized. y and x are not declared. Neither the value of x nor the value of y are initialized.

ANS: The value of y is not initialized.

2.

You are tasked with developing a multi-user application. The application stores a list of the current users in the ServletContext. You are writing a Servlet as part of the application that modifies the lists of current users. Referring to the scenario above, how do you ensure that your Servlet is thread safe? Synchronize access to the list of users with a "synchronized(getServletContext().getAttribute("userList") )" block. Implement the SingleThreadModel interface. Synchronize access to the ServletContext with a synchronize( getServletContext() ) block. Lock access to the list of users with a lock(getServletContext().getAttribute("userList") ) block. Extend the SingleThreadModel class.

ANS: Implement the SingleThreadModel interface. (http://www.oopreserch.com/poolps_3_0.html)

3.

What is the purpose of using a factory method pattern? It separates the construction of a complex object from its representation so that the same construction process can create different objects. It provides an object that allows you to add or remove object functionality without changing the external appearance or function of the object.

It provides an interface that acts as an intermediary between two classes, converting the interface of one class so that it can be used with the other. It provides a general purpose interface for creating an object, but lets the subclasses decide which class to instantiate. It provides an object to create customized objects without knowing their exact class or the details of how to create them.

ANS: It provides a general purpose interface for creating an object, but lets the subclasses decide which class to instantiate. (http://www.jguru.com/forums/view.jsp?EID=1311320) 4. How do you enable session tracking for JSP pages if the browser has disabled cookies? Use URL rewriting. Enclose the cookie within a Java Bean. Use <%@ page cookies="false" %>. Use server-side cookies. Use <%@ page session="false" %>.

ANS:

Use URL rewriting.( http://www.jguru.com/faq/view.jsp?EID=1045)

5.

Assuming you have the appropriate taglib directives, which one of the following is NOT a valid example of custom tag usage? <jsp:setProperty name="x" property="y" value="z" /> <stand:out value="xxx" /> <j:tag></j:tag> <jtag value="xxx" /> <candy:bar />

ANS: 6.

<jtag value="xxx" /> (Correct)

The basic syntax for a SimpleTag is: public interface SimpleTag extends JspTag

For the SimpleTag interface shown in the sample code above, which one of the following methods is called when SimpleTag is invoked by the JSP container? doTag() initTag() and startTag()

doStartTag() and doEndTag() initTag() doStartTag()

ANS: doTag() (Correct)

7.

package mycorp; public class EmployeeBean { private int salary = 0; private int age = 0; private String name = null; EmployeeBean() {} EmployeeBean(int salary, int age, String name) { setSalary(salary); setAge(age); setName(name); } public int getSalary() {return salary;} public void setSalary(int salary) {this.salary=salary;} public int getAge() { return age; } public void setAge(int age) {this.age=age;} public String getName() { return name; } public void setName(String name) {this.name=name;} } Referring to the sample code above, how do you store an instance of "EmployeeBean" in the session with a name of "David," age of 57, and a salary of $2,000,000?

getSession().setAttribute( new EmployeeBean(2000000, 57, "David") );

request.getSession().setAttribute( "emp", new EmployeeBean(2000000, 57, "David") );

HttpSession session = getSession(); EmployeeBean eb = EmployeeBean(2000000, 57, "David"); session.setAttribute( "emp", eb );

session.store( "emp", new EmployeeBean(2000000, 57, "David")

);

request.getSession().setParameter( new EmployeeBean(2000000, 57, "David");

ANS: request.getSession().setAttribute( "emp", new EmployeeBean(2000000, 57, "David") ); (Correct)

8.

Which JSP tag obtains a reference to an instance of a Java object defined within a given scope? <jsp:plugin> <jsp:useBean> <jsp:servlet> <jsp:forward> <jsp:include>

ANS:
9.

<jsp:useBean> (Correct)

For a tag handler that implements the IterationTag interface, what IterationTag method is called after the JSP container evaluates the tag body contents? doStartTag() doAfterBody() doAfterTag() doEvalBody() doEndTag()

ANS: doAfterBody() (http://docs.sun.com/app/docs/doc/819-3669/6n5sg7b8i? a=view)

10. What differentiates an in-process Servlet container? The Servlet container runs in its own process separate from the Web server. Java-based Web servers where the Web server and the Servlet container are integral parts of a single program. The container runs as a plug-in within the same address space of the main server. The Servlet container runs in the same process space as the JSP container. The container runs in its own process thread from the Web server.

ANS:

The Servlet container runs in the same process space as the JSP container.

(http://sawaal.ibibo.com/computers-and-technology/what-difference-between-inprocessoutofprocess-servlet-containers-531917.html)

11. public

class EmployeeBean {

... private int salary = 0;

... public int getSalary() { return salary; } public void setSalary(int salary) {this.salary = salary;} } And an HTML form: <form method="POST" action="myJSP.jsp"> Salary <input type="text" name="salary" /> </form> Your JSP page receives form data from the form, and you have a reference to an EmployeeBean instance named "employeeBean" with request scope. Referring to the sample code above, which one of the following does NOT properly set the value of salary in "employeeBean" from the form? <jsp:setProperty name="employeeBean" property="salary" param="salary"/> <% employeeBean.setSalary( request.getParameter("salary") ); %> <jsp:setProperty name="employeeBean" param="*"/> <jsp:setProperty name="employeeBean" property="*"/> <jsp:setProperty name="employeeBean" property="salary" value="<%= request.getParameter("salary") %>"/>

ANS: <jsp:setProperty name="employeeBean" param="*"/>

(http://java.sun.com/products/jsp/tags/11/syntaxref11.fm13.html)

12. What is the purpose of authorization? It identifies someone within the system. It verifies that someone has access to a given resource. It verifies that someone is accessing the system through a secure socket layer. It verifies that someone has the correct login and password. It verifies that someone is who he or she claims to be.

ANS:

It verifies that someone has access to a given resource.

(http://www.coderanch.com/t/292283/JSP/java/Authentication-Vs-Authorization) 13. What tier in 3-tier architecture is responsible for generating the user interface? GUI Application Integration

Enterprise Presentation

ANS:

Presentation (Correct)

14. Which one of the following JSP code snippets do you use to perform one-time initialization of instance variables defined in a JSP declaration prior to any other method being called? <%! public void jspInit() {} %> <%! public void init() {} %> <% ... one-time initialization code ... %> Override the JSP's base class init() method. <%! static { ... one-time initialization code ... } %>

Ans: <%! public void jspInit() {} %> (seems correct)

15. The invocation protocol used by SimpleTag is simplified from the one used for Classic tag handlers. Which one of the following statements is NOT true of the SimpleTag interface? SimpleTag provides no support for accessing body content. SimpleTag only has one lifecycle method, doTag() The javax.servlet.jsp.tagext.SimpleTagSupport class provides a default implementation for all methods in SimpleTag. SimpleTag does not have any inherent JSP/Servlet knowledge embedded within it. The SimpleTag interface extends directly from JspTag and does not extend Tag.

ANS:

SimpleTag provides no support for accessing body content.

[http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/SimpleTag.html]

It is important to note that that the SimpleTag interface extends directly from JspTag and doesn't extend Tag. This implies the fact that SimpleTag doesn't have any inherent JSP/Servlet knowledge embedded within it. Another difference that is worth noticing is that SimpleTag only has one lifecycle method, doTag() defined as:
[Note:]

public void doTag()throws JspException, java.io.IOException The doTag() method is called only once for any given tag invocation. This means that all code (includes tag logic, iteration, or body evaluations) related to this tag is contained in one nice and trim method http://www.oracle.com/technology/sample_code/tutorials/jsp20/simpleth.html

16. Which one of the following built-in JSP objects do you use to determine the scope of a given object? Response Config pageContext application session

ANS:

pageContext

17. <tag>
<name>pp</name> <tagclass>com.pp</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>t</name> <required>true</required> </attribute> </tag> The above sample code snippet from a Tag Library Descriptor (TLD) describes which one of the following? <pp t="w"/> <pp></pp> <t pp="h"/> <t/> <pp />

ANS:

<pp t="w"/> (Correct)

18. Which scope level for the <jsp:useBean> tag is required for the object reference to the bean to be placed in the page's ServletContext object?

Session Server Page Application Request

ANS: application

[Note: There are 4 scopes application session request and page in the order of thier significance. Application represent the ServletContext. The scope is accesible throught out the application. session represents HTTPSession object. This is valid till the user requests the application. Request represent the HTTPServletRequest and valdi to a particular request. A request may span a single JSP page or multiple depending upon teh situations. Page is the least valid scope. It is valid to the particular JSP page only This is some thing like private variable]

19. Which one of the following nests one custom tag within another? <stock:ticker><stock:price/></> <stock:ticker><jsp:param name="price"/></price></stock:ticker> <stock:ticker><stock:price></stock:ticker></stock:price> <stock:ticker><stock:price/></stock:ticker> <stock:ticker></stock:ticker><stock:price/><stock:price/>

ANS:

<stock:ticker><stock:price/></stock:ticker> (Correct)

20. Which one of the following HttpServletRequest methods allows you to determine whether or not a user is in a specific security role? getSecurityRole() getRemoteUser() inRole() isUserInRole() getUserPrincipal()

ANS: isUserInRole() (Correct)[ http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html]

21. A Web application is located in the directory /tomcat/webapps/doogle. Referring to the scenario above, what is the location of the application's deployment descriptor file? /tomcat/webapps/doogle /tomcat/webapps/doogle/WEB-INF/conf /tomcat/webapps/doogle/WEB-INF /tomcat/webapps/doogle/conf /tomcat/webapps/doogle/docs

ANS:

/tomcat/webapps/doogle/WEB-INF (Correct)

[http://tomcat.apache.org/tomcat-4.0-doc/appdev/deployment.html] 22. What type(s) of checked exceptions can be thrown by a Servlet's doGet() method? HttpServletException, IOException HttpServletException IOException Exception ServletException, IOException

ANS: ServletException, IOException (Correct) [http://www.wellho.net/resources/ex.php4?item=j601/demolet.java] 23. Which one of the following methods returns the values for a named request parameter? request.getParameterValues("parameterName"); page.getParameter("parameterName"); page.getParameterValues("parameterName"); request.getParameterValue("parameterName"); request.getParameter("parameterName");

ANS:

request.getParameter("parameterName");

24. Which one of the following page declarations ensures that each client request is processed in sequential order? <%@ page isThreadSafe="true" %> <%@ page isThreadSafe="0" %> <%@ page isThreadSafe="yes" %> <%@ page isThreadSafe="false" %> <%@ page isThreadSafe="null" %>

ANS:

<%@ page isThreadSafe="false" %> (Correct)[

http://www.roseindia.net/jsp/IsThreadSafe.shtml] 25. Where does an HTTP server read cookies from a client? Request body Request body

Response header Request header URL

ANS:
Note:

Request header [http://en.wikipedia.org/wiki/HTTP_cookie]

It is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server 26. <tag>
<name>ticker</name> <tagclass>stocks.Ticker</tagclass> <attribute> <!sub elements of attribute? -->

</attribute> </tag> Referring to the snippet shown in the above sample code from a tag library descriptor file, which one of the following is NOT a valid sub element of a tag <attribute>? <class> <required> <type> <description> <name>

ANS: <decription> <Class> [http://java.sun.com/javaee/5/docs/tutorial/doc/bnamu.html] Attributes are: description,name,required,rtexprvalue,type,fragment,deferredvalue,deferred-method.

27. The

following is part of a J2EE servlet deployment descriptor, <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> Referring to the sample code above, which one of the following is NOT true? The <servlet-name> is how the servlet is referenced by other classes in the application server. This would be in a file named web.xml. The <servlet-name> is how the servlet is referenced by other clauses in this deployment descriptor. The <servlet-name> and <servlet-class> must always be the same. The <servlet-class> must be in an archive file referenced by this deployment descriptor. The <servlet-name> and <servlet-class> must always be the same. (Correct)

ANS:

28. Which one of the following describes the HTTP protocol? Stateful, TCP/IP based Stateless, peer-to-peer, request/response Stateful, point-to-point Stateful, client/server, request/response Stateless, point-to-point, request/response

ANS:

Stateless, peer-to-peer, request/response

29. Which one of the following directives tells the JSP container to include the contents of another file, "footer.html", in the current page? <%@ import page="footer.html" %> <jsp:include file=<%= "footer.html" %> /> <%@ include file="footer.html" %> <%! include file="footer.html" %> <%@ include page="footer.html" %> ANS: <%@ include file="footer.html" %> (Correct) [http://www.roseindia.net/jsp/IncludeDir_Example.shtml]

30. When using FORM-based container managed authentication in a Java Servlet/JSP application, to which one of the following is the ACTION attribute set? Authentication j_login

servlet/AuthenticationServlet j_security_check The URL of your servlet

ANS:

j_security_check (Correct) [http://www.devarticles.com/c/a/Java/Securing-Struts-

Applications/3/] 31. Which one of the following code snippets do you use to define a JSP page in which the derived Servlet inherits the "myclasses.Myclass" class? <%@ page extends="myclasses.MyClass" %> <%@ page super="myclasses.MyClass" %> <%@ page inherits="myclasses.MyClass" %> <%@ inherits class= "myclasses.MyClass" %> <%@ extends class = "myclasses.MyClass" %>

ANS: <%@ page inherits="myclasses.MyClass" %>

32. Tag library descriptor: <taglib> ... <tag> <name>circle</name> <tagclass>tags.Circle</tagclass> <body-content>empty</body-content> <attribute> <name>radius</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>color</name> <type>String</type> </attribute> </tag> </taglib> JSP code: <%@ taglib uri="shapes.tld" prefix="s" %> Referring to the circle tag defined in the sample code above, and assuming that "radius" and "color" attributes are present in the request object, which one of the following is NOT a valid use of the circle tag library within your JSP page? <s:circle radius="<%= request.getParameter("radius") %>" color="<%= request.getParameter("color") %>"/> <s:circle radius="15" color="blue"/>

<s:circle radius="15"/> <s:circle radius="<%= request.getParameter("radius") %>" color="blue"/> <s:circle radius="<%= request.getParameter("radius") %>"/>

ANS: <s:circle radius="<%= request.getParameter("radius") %>" color="<%= request.getParameter("color") %>"/> (seems correct)

33. Directives provide general information about the JSP page to the JSP container. Which one of the following sets contain only valid JSP directives? page, include, taglib import, language, session page, import, tagdir contentType, isErrorPage, isThreadSafe include, page, lib

ANS: page,include,taglib (Correct)

34. Security realms are used to identify which one of the following? A collection of users and groups that are controlled by the same authentication policy A specific group that is controlled by an authorization policy A collection of users who have access to restricted URLs An individual associated with a security group A specific group that is controlled by an authentication policy

ANS: A collection of users and groups that are controlled by the same authentication policy

35. Which one of the following methods from javax.servlet.http.Cookie allows you to set a cookie's expiration time? updateMaxAge(int seconds) setMaxAge(int minutes) setMaxAge(int seconds) setMinAge(int seconds) setExpiration(int minutes)

ANS: setMaxAge(int seconds) (Correct)

36. What is the correct JSP structure for dynamically including a JSP page "included.jsp" and passing a request parameter "parameter1" with value "value1"? <%@ page file="included.jsp" param name="parameter1" value="value1" %> <jsp:include page="included.jsp"> <jsp:setPropery name="parameter1" value="value1" /> </jsp:include> <jsp:include page="included.jsp"> <jsp:param name="parameter1" value="value1" /> </jsp:include> <jsp:include page="included.jsp"> <jsp:param scope="request" name="parameter1" value="value1" /> </jsp:include> <%@ page="included.jsp" param name="parameter1" value="value1" %>

ANS: Option 3
<jsp:include page="included.jsp"> <jsp:param name="parameter1" value="value1" /> </jsp:include> 37. How does a custom tag introduce new scripting variables into a JSP page? It implements getScriptingVariables to the tag's class implementation. It implements getScriptingVariables on a TagInfo class. It adds <scripting-variable>..</scripting-variable> to the tag's Tag Library Descriptor (TLD) entry. It implements getVariableInfo() on a TagExtraInfo class. It implements a new TagAttributeInfo for each new Scripting Variable

ANS: It implements getVariableInfo() on a TagExtraInfo class. (Correct) [http://tomcat.apache.org/tomcat-4.1doc/servletapi/javax/servlet/jsp/tagext/TagExtraInfo.html]

38. Which one of the following authentication mechanisms is included in the HTTP protocol? FORM Client-Digest Message-Digest Basic

Client-Cert

ANS: Client-Digest

39. How are exceptions in J2EE Servlets handled? By the JavaScript debugger in the browser They are ignored by the J2EE server. By an exception handler in the Servlet container By the exception handler in the browser An exception handler needs to be written and specified in the deployment descriptor.

ANS: An exception handler needs to be written and specified in the deployment descriptor. (seems correct)

40. How do you dynamically include a file in your JSP page whose name is dynamically updated in the String "filename" variable for each request? <%@ include file="<%= filename %>"%> <%jsp:include file= getParameter("filename") %> <%@jsp:include page="<% filename %>" %> <jsp:include page="<%= filename %>"/> <% include page="filename"%>

ANS:

<jsp:include page="<%= filename %>"/> (correct)

41. Which class or interface do you use to retrieve the HttpSession object associated with the current user? ServletContext HttpServletRequest HttpServlet ServletConfig HttpServletResponse

ANS:

HttpServletRequest (Correct)

42. Which one of the following specifies the use of a tag library within a JSP page? <%! taglib url="dogs.tld" prefix="bark" %> <%@ taglib uri="dogs.tld" prefix="bark" %> <%@ taglib url="dogs.tld" prefix="bark" %> <%@ taglib name="dogs.tld" name="bark" %> <% taglib uri="dogs.tld" prefix="bark" %>

ANS: <%@ taglib uri="dogs.tld" prefix="bark" %> [http://www.roseindia.net/jsp/Declare_Tag_Library.shtml]

43.

Referring to the sample code above, which line of code added after "add code here" forwards your SQLException to the error page declared in web.xml? throw new

ServletException("wrapped sql exception", e); response.send( "wrapped sql exception", e ); throw new HttpServletException("wrapped sql exception", e); response.sendError("wrapped sql exception", e ); response.setStatus( "wrapped sql exception", e );

ANS: throw new ServletException("wrapped sql exception", e); (seems Correct)

44. <c:choose>
<c:when XXX="${ speed == 55 }"> Now you can set your cruise control. </c:when> <c:otherwise> Hit the accelerator </c:otherwise> </c:choose> ${track} </c:forEach> What is the name for the "XXX" attribute in the snippet of JSTL (JSP Standard Tab Library) shown in the sample code above? While True If Test boolean

ANS: test (Correct)

45. What method is called by the JSP container in order to provide a Custom Tag with access to built-in JSP
objects such as including request, session, pageContext? setPageContext() getContext() setContext() setPage() getServletContext()

ANS:

getServletContext() (Seems correct)

46. What is the purpose of security roles? They identify a collection of users and groups that are controlled by the same authentication policy. They provide the application with information on which JSP to display after authentication. They identify an individual associated with a security group.

They identify a collection of users that is controlled by an authorization and authentication policy. They provide an abstract name for the permission to access a particular set of resources in an application.

ANS: They provide an abstract name for the permission to access a particular set of resources in an application.

47. <tag>
<name>ticker</name> <tagclass>stocks.Ticker</tagclass> <attribute> <!-- subelements of attribute? --> </attribute> </tag> Referring to the snippet shown in the above sample code from a tag library descriptor file, which one of the following is NOT a valid subelement of a tag <attribute>? <description> <class> <required> <name> <type>

ANS: <Class>

48. In which one of the following directories do you place your web.xml application deployment descriptor file?
Webapps Web Lib WEB-INF Classes

ANS: WEB-INF (Correct) 49.

The flow diagram in the above diagram describes the life-cycle of a BodyTag, but it is missing a label. Which one of the following correctly describes what happens at "XXX"? Initialize Tag's Body Set Attributes Read in Tag's Body doBeforeTag Clear Buffer

ANS:

Read in Tag's Body

50. Which deployment descriptor element do you use to define an authentication mechanism? login-config authentication-method auth-config realm-name authentication-realm

ANS: login-config

[Note: ]To specify an authentication mechanism for your web application, declare a login-config element in the application deployment descriptor.

51. Which one of the following JSP life-cycle methods can be overridden within a JSP declaration?
jspInit(), jspDestroy() jspInit(), _jspService(), jspDestroy() jspService() jspInit(), jspService(), jspDestroy() init(), service(), destroy()

ANS:

jspInit(), jspDestroy() (Correct) http://www.cheapstocks.com/mystocks/CmdServlet/hello

52. [Sample URI]

Referring to the URI (Universal Resource Identifier) in the sample above, what portion of the URI is considered the context path for Servlet mapping? /CmdServlet/hello http://www.cheapstocks.com /mystocks/CmdServlet/hello /mystocks /hello

ANS: /mystocks (Correct) [Note:] Context Path- this helps container to choose the correct web app ServletPath-this helps container to identify correct servlet into the from the requested web app. PathInfo-in case of directory match

53.[Sample Code:]

Give the following class: package gamble; public class Dice { public static int roll() { return ((int) Math.random() * 6 ) +1; } And the following snippet from a Tab Library Descriptor (TLD) file: <taglib ....> ... <uri>Craps</uri> <function> <name>rollDice</name> <function-class>gamble.Dice</function-class> <function-signature>int roll()</function-signature> </function> ... </taglib>

Given the class Dice, the snippet of code from the TLD (tag library descriptor) above, and the declaration < %@ taglib prefix="craps" uri="Craps"%> at the top of your JSP file, how do you roll the dice using EL (expression language)? ${Craps.roll()} ${rollDice()} ${craps.Dice.roll()} ${craps.roll()} ${craps.rollDice()}

ANS:

${craps.rollDice()} (Correct)

[http://marc.info/?l=taglibs-user&m=111721318517272&w=2]

54. How do you place the text "<%" and "%>" in a JSP so that neither is recognized as a scriptlet bracket?
<%% and %%> <\% and %\> </% and /%> \\% and \\% \<\% and \%\>

ANS:

<\% and %\>

55. <servlet>
<servlet-name>WineTesting</servlet-name> <servlet-class>WineParams</servlet-class> <init-param> <param-name>alcoholContent</param-name> <param-value>0.12</param-value> <init-param> </servlet> Referring to the sample code above, how do you access the Servlet initialization parameter defined in the snippet of XML code from a web.xml deployment descriptor? getServletConfig().getInitParameter(); getServletConfig().getParameter("alcoholContent"); getServletContext("WineTesting").initParameter("alcoholContent"); getServletConfig().getInitParameter("alcoholContent"); getServletContext().initParameter("alcoholContent");

ANS:

getServletConfig().getInitParameter("alcoholContent"); (Correct)

[http://www.oracle.com/technology/sample_code/tech/java/codesnippet/servlets/ReadInit Params/ReadInitParams.html] 56. When is it necessary to use programmatic security for Java Web components? When operating system user privileges are defined within web.xml When declarative security alone is not sufficient When an application's security structure is defined within a deployment descriptor When a web user's privileges are defined within a deployment descriptor When using HTTPS

ANS: When declarative security alone is not sufficient (Correct) [http://java.sun.com/javaee/5/docs/tutorial/doc/bnbxe.html]

57.

Referring to the snippet from web.xml shown in the sample code above, and relative to your application root directory, in what directory is "stock.tld" located? /WEB-INF/lib/tlds WEB-INF/tlds Tlds / /META-INF/tlds

ANS: WEB-INF/tlds (Correct) [http://jakarta.apache.org/taglibs/site/tutorial.html#tag_jsp]


58. How does a Servlet access an initialization parameter after the init() method has completed? By calling the getParameter() method of ServletContext By calling the getConfig().getInitParameter() method By calling getInitParameters() of HttpServletRequest By calling the getServletConfig().getInitParameter() method

ANS: By calling the getServletConfig().getInitParameter() method [Note:] Initialization parameters are stored within each JSP/Servlet as static class variables that are accessed using JavaBean pattern methods getXXX(), setXXX(), where "XXX" is the name of the parameter.

59. package

mycorp; public class EmployeeBean { private int salary = 0; private int age = 0; private String name = null; EmployeeBean() {}

} How do you Servlet?

EmployeeBean(int salary, int age, String name) { setSalary(salary); setAge(age); setName(name); } public int getSalary() { return salary; } public void setSalary(int salary) {this.salary = salary;} public int getAge() { return age; } public void setAge(int age) {this.age = age;} public String getName() { return name; } public void setName(String name) {this.name = name;} store an instance of the bean in the code above so that it has application scope within a getServletContext().setAttribute("emp", new EmployeeBean(200000, 57, "David")); application.setAttribute("emp", new EmployeeBean(200000, 57, "David") ); getServletConfig().getServletContext().setParameter( new EmployeeBean(200000, 57, "David") ); request.getServletContext().setAttribute( new EmployeeBean(200000, 57, "David") ); getApplication().setAttribute( "emp", new EmployeeBean(200000, 57, "David") );

ANS: getServletContext().setAttribute("emp", new EmployeeBean(200000, 57, "David"));

60. main.jsp:

<html> <body> <p>In My Place</p> <jsp:forward page="coldplay.jsp" /> <p>A Rush of Blood to The Head"</p> </body> </html> coldplay.jsp: <p>Parachutes</p> <p>The Scientist</p> From the code snippets shown in the sample code above, which one of the following is displayed when "main.jsp" is loaded? In My Place The Scientist A Rush of Blood to The Head A Rush of Blood to The Head Parachutes In My Place Parachutes The Scientist In My Place A Rush of Blood to The Head Parachutes In My Place A Rush of Blood to The Head Parachutes The Scientist

ANS: Parachutes The Scientist Only the text in coldplay.jsp is displayed. Whenever a forward happens the response buffer is cleared first so anything written before the forward is cleared away. The lines in the source JSP file after the <jsp:forward> element are not processed. Keeping this in mind the the answer should be option C.

61. Which one of the following interfaces must you implement to ensure that your Servlet is single threaded? SingleJSPModel Synchronize SynchronizeServlet ServletRequestQueue SingleThreadModel ANS: SingleThreadModel (Correct)

62.

Referring to the sample code above, what code do you add to "add code here" in order to retrieve a JavaBean "dbInfo" that has been placed in application scope? request.getApplication.getAttribute("dbInfo"); request.getAttribute("dbInfo", HttpServlet.APPLICATION_SCOPE); getServletContext().getAttribute("dbInfo"); application.getAttribute("dbInfo"); pageContext.getAttribute("dbInfo");

ANS:

getServletContext().getAttribute("dbInfo");

63. Which one of the following web.xml elements do you use to define an initialization parameter for your Servlet? <init-parameter> <init-param> <servlet-param> <param> <initialization-param>

ANS: <init-param> (correct) [http://downloadllnw.oracle.com/docs/cd/E13222_01/wls/docs61/webapp/web_xml.html#1016477]

64. Which method is called on a session attribute that implements HttpSessionBindingListener when the session is invalidated? valueUnbound attributeRemoved listenerInvalidated

sessionDestroyed sessionInvalidated

Ans:

valueUnbound (Correct)

[http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionBi ndingListener.html]

65. <a href="/servlet/myServlet" method="POST">myServlet hyperlink</a> Referring to the sample HTML code above, and assuming the service() method has NOT been overridden, which method of myServlet is called when a user selects the "myServlet hyperlink"? doHead() doGet() doService() doPost() doPut()

ANS: doPost()

66. What is the purpose of a Web application tier security constraint? It configures HTTP or HTTPS over SSL. It configures HTTP basic or form-based authentication over SSL. It specifies which roles have been defined for an application. It specifies which user respository to use with container managed authentication. It specifies who is authorized to access specific URL patterns and HTTP methods.

ANS:

It specifies who is authorized to access specific URL patterns and HTTP methods.

67. Which one of the following do you use to programmatically retrieve a list of custom tags supported by a tag library? JSPEngine.getTags() TagLibraryContext.getTags() TldInfo.getTags()

TagSupport.getTags() TagLibraryInfo.getTags()

ANS:

TagLibraryInfo.getTags() (Correct)

[Note:] Returns An array describing the tags that are defined in this tag library.
68. <%@ taglib uri="/chart.tld" prefix="crt" %> Assuming the above is the only tag library directive for "chart.tld" what is its location relative to your application's root directory? / /tld /META-INF /WEB-INF/tld /WEB-INF

ANS: /WEB-INF (Correct)


69. You are given a tag library that has a tag named calcGPA. This tag may accept an attribute, major, which cannot take a dynamic value. You may assume any needed variables are declared. Referring to the scenario above, which one of the following is a correct use of this tag? <mylib:calcGPA /> <mylib:calcGPA attribute="major" value="CS"/> <mylib:calcGPA attribute="major" attribute-value="CS"/> <mylib:calcGPA major="<%= varMajor %>"/> <mylib:calcGPA> <jsp:setProperty name="major" value="CS"/> </mylib:calcGPA>

ANS:

<mylib:calcGPA />

70. What type(s) of checked exceptions can be thrown by a Servlet's doGet() method? Exception HttpServletException IOException

ServletException, IOException HttpServletException, IOException

Ans: ServletException, IOException


71. For which of the following classes does the security manager NOT apply restrictions? Classes loaded from the system's boot classpath Classes within the JRE Permission class Locally run classes Classes loaded from the default class path

ANS:

Classes loaded from the system's boot classpath

[Note:] Generally, the security manager applies restrictions to all classes except those that are

loaded from the system's boot classpath. The boot classpath is the list of locations from which core classes are loaded. Usually, this is restricted to the jarfiles in the directory jre/lib under the main Java installation

72. What is the role of the Front Controller design pattern in JSP applications? It controls the creation of view helpers. It encapsulates application data inside a web application. It generates composite views from incoming user requests. It routes incoming user requests. It authenticates incoming user requests.

ANS:

It routes incoming user requests.

73. HTML

Form: <form action="whatever.jsp"> Name: <input type="text" name="name"> ID: <input type="id" name="name"> Favorite Sport 1: <input type="text" name="favsport"> Favorite Sport 2: <input type="text" name="favsport"> <input type="submit" name="name"> </form>

Given the HTML form above, what is a valid method for reading the "Favorite Sport 1" field from within "whatever.jsp" using EL (expression language)? ${params.favsport[0]} ${param.favsport} ${requestScope.param[favsport[0]]} ${param.favsport[0]} ${requestScope.favsport[0]}

ANS:

${param.favsport}

74. Which one of the following is a valid JSP directive for determining whether or not the current JSP page defines another JSP's error page? <% page exceptionPage="true" /> <%@ page errorPage="true" /> <%! page errorPage="true" /> <%@ page isErrorPage="true" /> <% page exceptionPage="localhost" />

Ans: <%@ page isErrorPage="true" /> (Correct) 75.

The servlet mapping above is defined within an application context in web.xml. Referring to this mapping, which one of the following requests is NOT serviced by "BuyLowServlet"? /ui/stocks/opening.php/closing.php /helloworld.php /ui/stocks/opening.php /ui/php /ui/closing.php

ANS:

/ui/php

76. What interface is implemented by the class generated for a JSP page by an HTTP-based JSP Container? Servlet JspPage JspServlet HttpJspPage HttpJspServlet

ANS:

HttpJspPage (Correct)

[http://www.apache-korea.org/cactus/api/framework13/javax/servlet/jsp/HttpJspPage.html] 77.

Given the above example syntax, which one of the following classes can be extended to implement a custom tag that parses an expression in its body, calculates, and displays the result of that expression? javax.servlet.jsp.tagext.BodyTagSupport javax.servlet.jsp.tagext.TagBody javax.servlet.jsp.tagext.BodyTag javax.servlet.jsp.tagext.Tag javax.servlet.jsp.tagext.TagData

Ans: javax.servlet.jsp.tagext.BodyTagSupport

78.

Referring to the snippet from web.xml shown in the sample code above, what is the correct tag library directive used to refer to "stock.tld" in your JSP page? <%@ taglib uri="www.zzz.com/stocks" prefix="stk" %> <%@ taglib uri="tlds/stock.tld" prefix="stk" %> <%@ taglib uri="/tlds/stock.tld" prefix="stk" %> <%@ taglib uri="http://www.zzz.com/stocks" prefix="stk" %> <%@ taglib uri="stocks" prefix="stk" %>

ANS:

<%@ taglib uri="http://www.zzz.com/stocks" prefix="stk" %>

(Correct) [Note:] The <uri> in the TLD & the uri in the taglib directive must match.
79. Which one of the following implicit objects is only available after the isErrorPage page directive has been set to true? Response Page Error Session Exception

ANS:
[Note:]

exception (Correct)

If the JSP is an error page (the page directive's isErrorPage attribute is set to true), the exception implicit object is also available.
80. A JavaBean "Person" has a property called "address." The value of this property is another JavaBean "Address" with the following string properties: street, city, state, and zip. A controller Servlet creates a session-scoped variable called "student" that is an instance of the "Person" bean.

From the scenario above, which one of the following JSP structures sets the city property of the student to the city request parameter? <c:set> ${sessionScope.student.address.city}=${param.city} </c:set> <c:set target="${sessionScope.student.address.city=param.city" /> <c:set scope="session" var="${customer.address}" property="city" value="$ {param.city}" /> ${sessionScope.student.address.city = param.city} <c:set target="${sessionScope.student.address}" property="city" value="${param.city}" />

Ans: <c:set target="${sessionScope.student.address}" property="city" value="$ {param.city}" /> (Correct)

81. The purpose of a security certificate is to verify which one of the following? A message was created from a specific message digest for a particular message.

A public key was used to encrypt messages that are to be sent to the owner of the corresponding private key. A message is signed by a trusted third party that identifies the public key of another principal as being valid. A message was created with encryption using a private key. A message signature was used that would be impractical to create without knowledge of a particular private key.

ANS: A message is signed by a trusted third party that identifies the public key of another principal as being valid. (Correct) [http://books.google.co.in/books? id=XrXUUtauux0C&pg=PT14&lpg=PT14&dq=purpose+of+a+security+certificate+in+jsp&sour ce=bl&ots=dxrYW2MUvx&sig=3IHmGdsiLLHxxUNeEkL1Hv8aenU&hl=en&ei=MDoXS4qO8aMlAft76DfAg&sa=X&oi=book_result&ct=result&resnum=5&ved=0CBsQ6AEwBA#v=onepag e&q=&f=false] 82. What technique do you use to rewrite URLs if a browser's cookies are disabled (URLs that are passed in the response.sendRedirect() method)? HttpServlet.rewriteURL(String url) HttpServletResponse.rewriteURL(String url) HttpServletRequest.encodeURL(String url) HttpServletResponse.encodeRedirectURL(String url) HttpServletResponse.encodeURL(String url)

[http://www.jguru.com/faq/view.jsp?EID=1045]
ANS: HttpServletResponse.encodeRedirectURL(String url) (this should be encodeRedirectedURL)

83. As a performance optimization, most JSP containers reuse instances of JSP custom tags by pooling them in memory.

Given that some JSP containers have the above optimization, what must authors of custom tag libraries do in a multi-threaded environment in order to prevent the data integrity of the tag handlers from being corrupted? Each tag should synchronize on a lock object. No further action is required. All requests are given a new fully initialized object. Implement a cleanup finalize() method. Implement a TagPoolListener. Implement a cleanup release() method.

ANS: Each tag should synchronize on a lock object.

84. When using Basic Authentication in a Java Servlet/JSP application, how are the username and password strings sent to the server? Message digest Base64 encoding Plain text SSL Encrypted using public-key cryptography

ANS: Base64 encoding (Correct) [http://www.informit.com/articles/article.aspx? p=24253&seqNum=3]

85. <%

int counter=2; %> <% counter++; if(counter > 3) {%> Counter is greater than three <br> <% } else { %> Counter is less than three <br> <% } %> Counter= <%=counter%> Referring to the sample code above, what is the output of the above JSP the second time the document is accessed? Counter is less than three Counter = 3 Counter is greater than three Counter = 3 Counter is less than three Counter = 4 Counter is greater than three Counter = 4 Counter is less than three Counter = 2

ANS: Counter is less than three Counter = 3

[Note:] The counter is a local variable in the scriptlet <%....%>. If it were a declaration<%!...%> the its value will change.

86. A JSP page is compiled into a Servlet; therefore, it can do everything that a Servlet can do. If the above statement is true, then why is an IllegalStateException thrown when opening a Binary Stream output to the client from a JSP page but NOT to a Servlet? JSP has already opened the stream as a JspWriter. JSP pages have more security settings than Servlets. JSP pages must flush their buffers before changing the stream type; Servlets do not have this limitation. JSP pages can write a Binary Stream using its implicit out stream. JSP pages use a different Streaming mechanism than Servlets.

ANS:

JSP has already opened the stream as a JspWriter.

87.

Referring to the sample code above, which line of code added after "add code here" triggers the display of a container generated HTTP Internal Server Error page? throw new HttpServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "database error"); response.send( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "database error" ); response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "database error" ); throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);

response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "database error" ); 88. How many javax.servlet.ServletContext objects can exist within a single Java virtual machine? One for each Web Server One for each Servlet One for each domain

ANS:

One for each Servlet thread One for each application

ANS:

One for each application

89. <c:forEach

var="track" items="${soundTracks}" XXX="i"> ${track} </c:forEach> What is the name of the optional loop counter variable "XXX" in the sample code above? Counter Loop Var varStatus index

ANS: varStatus [Note] The varStatus attribute gets a loop counter. 90. Which one of the following commands within a JSP or Servlet causes a session to be automatically closed after the user has been inactive for 10 minutes? session.setMaxInactiveInterval(10*60) session.setMaxInactivePeriod(10) session.setMaxInactivePeriod(10*60) response.setExpirePeriod(10*60) sessionContext.setMaxIdleTime(10*60)

ANS:

session.setMaxInactiveInterval(10*60) (Correct)

91. class

EmployeeBean {

private double bucks = 0; private int age = 0; String name = null EmployeeBean() {} EmployeeBean(int salary, int age, String name) { setSalary(salary); setAge(age); setName(name); } public double getSalary() { return bucks; } public void setSalary(double bucks) {this.bucks=bucks;}

public public public public }

int getAge() { return age; } void setAge(int age) {this.age=age;} int getName() { return sex; } void setName(String sex) {this.sex=sex;}

<jsp:useBean id="jay" class="EmployeeBean"/> Referring to the sample code above, how do you use a JSP standard action to read the salary of the "jay" instance of "EmployeeBean"? <jsp:property name="jay" attribute="salary"/> <jsp:read id="jay" property="salary"/> <jsp:getProperty id="jay" attribute="salary"/> <jsp:get name="jay" property="salary"/> <jsp:getProperty name="jay" property="salary />

ANS:

<jsp:getProperty name="jay" property="salary /> (Correct)

[http://java.sun.com/products/jsp/tags/11/syntaxref11.fm10.html]

92.

Assuming you have a reference "employeeBean" to an instance of the EmployeeBean class declared in the sample code above, how do you set the value of "bucks" to 10000? <jsp:setValue name="employeeBean" property="salary" value="10000"></jsp:setValue> <jsp:setAttribute name="employeeBean" property="salary" value="<%= Integer.parseInt(10000)%>"/> <jsp:setProperty name="employeeBean" property="salary" value="10000"></jsp:setProperty> <jsp:setProperty id="employeeBean" property="salary" value="10000"></jsp:setProperty> <jsp:setProperty id="employeeBean" property="bucks" value="10000

ANS:

<jsp:setProperty name="employeeBean" property="salary"

value="10000"></jsp:setProperty> (Correct)

[http://java.sun.com/products/jsp/tags/syntaxref.fm13.html]
93.

Referring to the image above, what is the illegal state transition in the Servlet state transition diagram above? Unload Service Destroy Shutdown from Loaded to Unloaded state Shutdown from Destroyed to Unloaded state

ANS:
94.

Unload(Not sure)

Referring to the sample code above, how do you retrieve the database URL "dbURL" defined in web.xml when your Servlet is first loaded? Override HttpServlet.startup() call ServletConfig's getInitParameter("dbURL"). Override HttpServlet.init(), call getServletConfig() to retrieve a copy of ServletConfig, call ServletConfig's getInitParameter("dbURL"). Override Servlet.init(ServletConfig) call ServletConfig's getInitParameter("dbURL").

Call getServletConfig() from doPost(), doGet(), or service() upon receipt of a request to get a copy of ServletConfig, call ServletConfig's getInitParameter("dbURL"). Override HttpServlet.load(), call getServletConfig() to retrieve a copy of ServletConfig, call ServletConfig's getInitParameter("dbURL").

ANS: Override HttpServlet.init(), call getServletConfig() to retrieve a copy of ServletConfig, call ServletConfig's getInitParameter("dbURL").

95. Which one of the following allows you to determine the name and version number of the Servlet or JSP engine that you are using? <%= runtime.getServletContext() %> <%= server.getServletInfo() %> <%= Runtime.getRuntime().getServerInfo() %> <%= application.getInfo("serverinfo") %> <%= application.getServerInfo() %>

ANS:

<%= application.getServerInfo() %> (Correct)

[http://www.exforsys.com/tutorials/jsp/jsp-application-object-methods.html]

[Note: ] If you are using JSP, you can use this expression:
<%= application.getServerInfo() %>

96. The

<jsp:include> element allows you to include either a static or dynamic file in a JSP file. The results of including static and dynamic files are quite different. <jsp:include page="brew.jsp" flush="true"> <jsp:param name="favbeer" value="sprecher" /> </jsp:include> From the scenario above, which one of the following sets of statements differentiates between static and dynamic inclusion of a file in a JSP page? If the file is static or dynamic, the file name cannot be changed. If the file is dynamic, the included file acts on a request and sends back a result. If the file is static, its content is included in the calling JSP file. If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. If the file is static, the file name cannot be changed. If the file is dynamic, the file name can be changed. In both cases the included file acts on a request and sends back a result.

If the file is static or dynamic, the file name can be changed. If the file is dynamic, the included file acts on a request and sends back a result. If the file is static, the file is included a compile time. If the file is dynamic, the file recompiled for each request.

ANS:

If the file is static, its content is included in the calling JSP file.

If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page.

97. For a tag that extends the BodyTagSupport class, doStartTag()


returns once, and doAfterBody() returns EVAL_BODY_AGAIN three times. Referring to the scenario above, how many times is setBodyContent() called? Zero One Two Three Four

ANS: Zero [Note:] The setBodyContent() method is called exactly once & ONLY IF doStartTag() returns EVAL_BODY_BUFFERED. http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/tagext/BodyTag.html 98. How do you use declarative security for Java web components? For expressing an application's security structure in a deployment descriptor For declaring Web user privileges within a deployment descriptor When programmatic security alone is not sufficient to express the security model of an application For defining an application's security structure at run-time within a program For expressing operating system user privileges within web.xml

ANS:

For expressing an application's security structure in a deployment descriptor(Correct)

http://docs.sun.com/app/docs/doc/819-4734/6n6s7shtv?a=view

99.

Referring to the sample code above, which one of the following is a valid use of the circle tag within your JSP page? <s:circle radius="15"/> <s:circle radius="15">a</circle> <circle radius="15" color="blue"> <circle radius="15" color="blue"><circle/> <shapes:circle radius="15" color="blue"/>

ANS:

<s:circle radius="15"/> (Correct)

100.

What method is called by the JSP container in order to provide a Custom Tag with access to built-in

JSP objects such as including request, session, pageContext? setPageContext() setPage() setContext() getServletContext() getContext()

ANS:

getServletContext()

101.For which one of the following does a web container NOT provide support? JSP and Servlet life-cycle management Responding to HTTP client requests Selecting application behaviors at assembly or deployment time Transaction management Session management

Ans: Selecting application behaviors at assembly or deployment time

102.

Once the credit card transaction is complete, what code do you add to "add code here" in the sample code above in order to remove the user's session information? request.getSession().invalidate(); request.getSession().destroy(); request.getSession().remove(); session.close(); getSession().delete();

ANS:

request.getSession().invalidate(); (Correct)

103.Which statement is true for a web application that is distributed across multiple servers? You cannot use sendRedirect(). You cannot depend on events generated when a session is activated or passivated. You cannot use HttpSession. You cannot share application information with ServletContext.

You cannot use RequestDispatcher.include() or RequestDispatcher.forward().

ANS: 104.

You cannot share application information with ServletContext.

<taglib> <taglib-uri>/marketing</taglib-uri> <taglib-location>/WEB-INF/tlds/BadPlan.tld>/taglib-location> </taglib> Referring to the sample code above, which one of the following specifies the use of the above tag library in a JSP page? <@ taglib name="/mar" prefix="marketing"%> <@ taglib library="/marketing" prefix="mar"%> <@ taglib name="/marketing" prefix="mar"%> <@ taglib uri="/mar" prefix="marketing"%> <@ taglib uri="/marketing" prefix="mar"%>

ANS:

<@ taglib uri="/marketing" prefix="mar"%>

105.Which one of the following statements allows you to define an output buffer of 8 kilobytes? <%@ buffer size=8 %> <%@ page buffer=8 %> <%@ page autoFlush="false" buffer=8000 %> <%@ page flush="false" buffer=8000 %> <%@ page autoFlush="false" buffer=8 %>

[http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html]

ANS:

<%@ page autoFlush="false" buffer=8000 %>

106.You are tasked with writing a custom tag that can read any JSP scripting, HTML, JavaScript, and Java code within its tag body and display it without modification. It is important to prevent the JSP container from parsing any content within the tag body. Referring to the scenario above, what is the value of the <body-content> element of your <tag>? Empty Text Tagdependent SKIP-BODY

JSP

ANS:

tagdependent (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html)

107.What is the name of the tag library element that defines whether or not an attribute can have an expression based on a request time (run time) value? Rtexprvalue request-time rtexpr request-value request

ANS: rtexprvalue (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html)

108.What value for the enctype (encoding type) attribute of an HTML form is required for uploading images from a browser to your Servlet? multipart/form-data application/binary multipart/binary-data application/image multipart/image-data

ANS:

multipart/form-data (http://www.flexive.org/docs/3.0/website/tutorial01.html)

109.What is the purpose of the composite design pattern? To represent a hierarchical tree structure of varying complexity while allowing every element in the structure to operate with a uniform interface To create customized composite objects without knowing their exact class or the details of how to create them. To act as an intermediary between two classes, converting the interface of one class so that it can be used with the other To add or remove object functionality without changing the external appearance or function of the object To divide a complex component into two separate but related inheritance hierarchies

ANS:

To represent a hierarchical tree structure of varying complexity while allowing every element in the structure to operate with a uniform interface (Correct) 110.What modifications are required to your Servlet or JSP in order to use secure communications with SSL? Encode all URLs with encodeURL(). No modifications are required. Encode URLs with encodeURL() and write responses to response.getSecureWriter(). Update the setContentType("encodeSSL"). Write all responses with response.getSSLWriter().

ANS:

No modifications are required. (seems correct)

111.

In the above code fragment, when does the "finally" exception handler execute? After s gets converted to an integer When i is a string When i > 0 After NumberFormatException has been thrown Always

ANS:

ALWAYS (Correct)

112.Your Web application, analyzestocks, depends on a JAR file, "db.jar", provided by an outside vendor. Referring to the scenario above, where do you place "db.jar"? analyzestocks/WEB-INF/classes analyzestocks/WEB-INF analyzestocks/WEB-INF/lib analyzestocks/classes/lib

analyzestocks

Ans: analyzestocks/WEB-INF/lib (Correct)

113.Class Human has the following access methods: public String getName(); public void setName(String) public Pet getPet(); public void setPet(Pet) Class Pet has the following access methods: public String getName(); public void setName(String) Both classes are used by the following Servlet code: public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Human h = new Human(); h.setName("John"); Pet p = new Pet(); p.setName("Spike"); h.setPet(p); request.setAttribute("human", h); RequestDispatcher view = request.getRequestDispatcher("view.jsp"); view.forward(request, response); } Referring to the sample code above, how do you display, from "view.jsp" using EL (expression language), the name of the human's pet? Note: Assume you have all necessary package declarations.

<jsp:useBean id="human" class="Human" scope="request" /> <jsp:getProperty name="human" property="pet" /> ${human.pet} ${requestScope.human.getPet()} ${human.pet.name} <% ((Human) request.getParameter("human")).getPet().getName() %>

ANS:

${human.pet.name} (Correct)

114.Which class allows you to access the HttpSession object associated with the current user? HttpServlet HttpServletResponse HttpServletRequest

ServletContext ServletConfig

Ans: HttpServletRequest

115.For a tag handler that implements the BodyTag interface, what value returned from doAfterBody() instructs the JSP container to re-evaluate the body contents? Tag.EVAL_BODY BodyTag.EVAL_BODY Tag.EVAL_BODY_INCLUDE BodyTag.EVAL_BODY_CONTENTS IterationTag.EVAL_BODY_AGAIN

ANS:

IterationTag.EVAL_BODY_AGAIN (Correct)

116.<%@ taglib uri="stocks.tld" prefix="stock" %> You are given a tag library that has a tag named "stockPrice" and a required attribute "ticker" that can take a dynamic value. Referring to the tag library directive in the sample code above, which one of the following is a valid use of the "stockPrice" tag? <stock:stockPrice ticker="sunw"/> <jsp:stockPrice ticker="sunw"/> <stock:stockPrice><jsp:param ticker="sunw"/></stock:stockPrice> <stock:stockPrice><ticker>sunw</ticker></stock:stockPrice> <stockPrice ticker="sunw"></stockPrice>

ANS:

<stock:stockPrice ticker="sunw"/>(Not sure)

117.Which one of the following describes elements that are all required in the taglib element of a web.xml file? <taglib-uri>, <taglib-location> <taglib-uri>, <taglib-location>, <tag-handler> <taglib-url>, <taglib-location>

<uri>, <location> <url>, <location>, <handler>

ANS:

<taglib-uri>, <taglib-location>

118. <jsp:include

page="brew.jsp"> <jsp:param name="favbeer" value="sprecher" /> </jsp:include> The snippet of code shown in the sample code above is from a JSP page that includes the JSP page "brew.jsp". From "brew.jsp", which one of the following is NOT a valid way of accessing "favbeer"? ${request.favbeer} ${requestScope.favbeer} ${paramValues["favbeer"][0]} <%= request.getParameter("favbeer") %> ${param.favbeer}

ANS:

${paramValues["favbeer"][0]}

119.Which one of the following directives allows you to access tags defined in the tag library "taglib.tld" using a JSP tag prefix of "test"? <%@ tag prefix="test" uri="taglib.tld" /> <%@ taglib tag="test" url="taglib.tld" /> <jsp:taglib prefix="test" uri="taglib.tld" /> <%! tag pre="test" url="taglib.tld" /> <%@ taglib prefix="test" uri="taglib.tld" %>

ANS:

<%@ taglib prefix="test" uri="taglib.tld" %>

120.You are developing an order entry application that needs to maintain session information for an unknown and potentially long period of time. You have decided that the best approach is to prevent user session information from timing out and being removed by the Servlet container and only remove users' session information when they log out.

Referring to the scenario above, how do you prevent the Servlet container from timing out your session information? setSessionInterval(HttpSession.NO_TIMEOUT); setSessionInterval(0);

setInterval(Integer.MIN_VALUE); setMaxInactiveInterval(Integer.MAX_VALUE); setMaxInactiveInterval(-1);

ANS:

setMaxInactiveInterval(-1);

121.Which one of the following code snippets tells the JSP engine to NOT create an implicit session variable? <%@ session on="false" %> <%! session=null; %> <% session=null; %> <%@ page session="false" %> <%@ page persistence="off" %>

122.Which one of the following interfaces allows another Servlet to process all or part of a request? javax.servlet.http.HttpSession javax.servlet.ServletConfig javax.servlet.ServletContext javax.servlet.ServletContext javax.servlet.RequestDispatcher

ANS:

<%@ page session="false" %>

ANS :

javax.servlet.RequestDispatcher

The RequestDispatcher interface is the glue that controls the flow between servlets and output streams such as HTTP clients, files, or even JavaServer Pages (JSP).
[Note:]

Before you can send control to another servlet, you must first get the necessary RequestDispatcher for that particular servlet. This is controlled through the method call getRequestDispatcher(...) from the ServletContext interface. You specify the URI to the servlet, and assuming no security violations incur, the necessary RequestDispatcher reference is returned.
123.

Given that the JspWriter's buffer will NOT be flushed until the end of the JSP page has been reached, where does the above code appear within a JSP document?

Only before any scriptlets that write output to the response object Anywhere within the document Before any declarations Only on the very first line of the document Before any directives

ANS:

Anywhere within the document

124.What is the correct JSP structure necessary to ensure that all JSP content is flushed prior to dynamically including the content of another JSP file "brew.jsp"? <%@ include file="brew.jsp" flush="true" %> <%@ include page="brew.jsp" autoFlush="true" /> <jsp:include page="brew.jsp" flush="true" /> <jsp:include page="brew.jsp" autoFlush="true" /> <jsp:include file="brew.jsp" autoFlush="true" />

Ans:

<jsp:include page="brew.jsp" flush="true" />

125. You have created a Servlet to process a user registration form.


http://www.buycheap.com/servlet/RegistrationServlet.

The URL of your Servlet is:

Referring to the scenario above, what attribute of your HTML registration <form ...> tag needs to be set to the URL of your Servlet? Href url method action uri

ANS:

action

126.In a J2EE application server, which set of components are contained by a Web container? JSP, Servlets, Applets

JSP, Servlets JSP, Servlets, EJB Servlets only JSP, Servlets, EJB, JDBC, JNDI, RMI-IIOP, JMS

ANS:

JSP, Servlets, EJB, JDBC, JNDI, RMI-IIOP, JMS

127.J2EE applications (including JSP/Servlet web applications) are made up of components that can be deployed into different containers. JSP and Servlets are deployed within web containers.

Within the context of the background information in the above scenario, what type or types of security are provided by J2EE containers? Reliance on the underlying operating system's security features Reliance on the security built into the J2EE application server Declarative and authorization security Declarative and programmatic security Programmatic and authentication security

ANS :

Declarative and programmatic security

128.

Referring to the sample code above, how do you use a scriplet to set the salary of the "jay" instance of "EmployeeBean" to $200? <% setProperty name="jay" value="200" property="salary" %> <%! jay.setSalary( 200 ); %> <% jay.salary = 200 %> <%= jay.setSalary( 200 ); %> <% jay.setSalary( 200 ); %>

ANS:

<% jay.setSalary( 200 ); %>

129. <select

name='styleId'> <% WineStyles[] styles = wineService.getStyles(); for(int i=0; i<styles.length; i++) { WineStyle style=styles[i]; %> <option value='<%= style.getObjectID() %'> <%= style.getTitle() %> </option> <% } %> </select> What JSTL (JSP Standard Tag Library) code snippet produces the same result as the JSP scriplet shown in the sample code above?

<%select name='styleId'> <c:for var='style' items='${wineService.styles}'> <option value='${item.objectID}'>${style.title}</option> </c:for> </select> <%select name='styleId'> <c:for array='${wineService.styles}'> <option value='${item.objectID}'>${item.title}</option> </c:for> </select> <%select name='styleId'> <c:iterate array='${wineService.styles}'> <option value='${item.objectID}'>${item.title}</option> </c:iterate> </select> <select name='styleId'> <c:forEach var='style' items='${wineService.styles}'> <option value='${style.objectID}'>${style.title}</option> </c:forEach> </select> <%select name='styleId'> <c:iterate array='${wineService.styles}' value='${item.title}'</iterate> </select>

Ans: <select name='styleId'> <c:forEach var='style' items='${wineService.styles}'> <option value='${style.objectID}'>${style.title}</option> </c:forEach> </select> 130.What Java package defines the classes and interfaces that define the contract between a JSP page and the JSP container? javax.servlet.jsp

javax.servlet javax.servlet.http javax.jsp javax.servlet.jsp.tagext

Ans: javax.servlet.jsp
131.Which one of the following methods sends the current contents of the response output stream to the browser? out.close() response.release() response.flush() out.flush() response.close()

Ans: response.flush()
[Note: The Flush method sends buffered output immediately. This method causes a run-time error if Response.Buffer has not been set to TRUE. ]
132. Which one of the following provides a reference to the "this" variable within a JSP page? The Servlet outputstream object The getThisProperty() method The getFocus() method The implicit page object The getProperty() method

ANS:

The implicit page object

You might also like