java advanced java servlets arqb trcqb v1.0

43
1.Which one of the following HTTP methods is commonly used to test the validity of a hyperlink when you do not want (or need) to actually retrieve the content of the link, as the latest version is already available? 1 CHECK TEST PUT GET HEAD Y 2.Which one of the following methods will be invoked when a ServletContext is destroyed? 1 contextDestroyed() of javax.servlet.ServletContextListener Y contextDestroyed() of javax.servlet.HttpServletContextListener destroy() of javax.servlet.GenericServlet contextDestroyed() of javax.servlet.http.HttpServletContextListener contextDestroyed() of javax.servlet.http.HttpSessionListener 3."Consider the following class: import javax.servlet.*; public class MyListener implements ServletContextAttributeListener { public void attributeAdded(ServletContextAttributeEvent scab) { System.out.println(""attribute added""); } public void attributeRemoved(ServletContextAttributeEvent scab) { System.out.println(""attribute removed""); } } Which one of the following statements about the above class is correct? " 1 This class will compile as it is. This class will compile only if the attributeReplaced() method is added to it. Y This class will compile only if the attributeUpdated() method is added to it. This class will compile only if the attributeChanged() method is added to it. This class will compile only if the attributeDestroyed() method is added to it 4.Which one of the following is a requirement of a distributable web application? 1 It cannot depend on ServletContext for sharing information Y It cannot depend on the sendRedirect() method It cannot depend on the include() and forward() methods of the RequestDispatcher class It cannot depend on cookies for session management It cannot depend on html hidden form fields for session management

Upload: kapilvaswani5160

Post on 07-Mar-2015

58 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Advanced Java Servlets ARQB TRCQB v1.0

1.Which one of the following HTTP methods is commonly used to test the validity of a hyperlinkwhen you do not want (or need) to actually retrieve the content of the link, as the latest versionis already available? 1CHECKTESTPUTGETHEAD Y

2.Which one of the following methods will be invoked when a ServletContext is destroyed? 1

contextDestroyed() of javax.servlet.ServletContextListener YcontextDestroyed() of javax.servlet.HttpServletContextListenerdestroy() of javax.servlet.GenericServletcontextDestroyed() of javax.servlet.http.HttpServletContextListenercontextDestroyed() of javax.servlet.http.HttpSessionListener

3."Consider the following class:

import javax.servlet.*;public class MyListener implements ServletContextAttributeListener{public void attributeAdded(ServletContextAttributeEvent scab){System.out.println(""attribute added"");}public void attributeRemoved(ServletContextAttributeEvent scab){System.out.println(""attribute removed"");}}Which one of the following statements about the above class is correct? " 1 This class willcompile as it is.This class will compile only if the attributeReplaced() method is added to it. YThis class will compile only if the attributeUpdated() method is added to it.This class will compile only if the attributeChanged() method is added to it.This class will compile only if the attributeDestroyed() method is added to it

4.Which one of the following is a requirement of a distributable web application? 1It cannot depend on ServletContext for sharing information YIt cannot depend on the sendRedirect() methodIt cannot depend on the include() and forward() methods of the RequestDispatcher class

It cannot depend on cookies for session managementIt cannot depend on html hidden form fields for session management

Page 2: Java Advanced Java Servlets ARQB TRCQB v1.0

5."You want to write Servlet classes for a new web protocol of yours that you have developed.Which one of the classes from the following would you extend your servlets from?" 1HttpServletGenericServlet YServletAbstractServlet6.Which one of the following methods would you use to put the session id into the URL tosupport sessions using URL rewriting? 1rewriteURL() of HttpServletResponserewriteURL() of HttpServletencodeURL() of HttpServletRequestencodeURL() of HttpServletResponse YencodeURL() of HttpServlet7."Given the following web application deployment descriptor:<web-app> <servlet> <servlet-name>myServlet</servlet-name> <servlet-class>MyServlet</servlet-class> … </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping>

which one of the following statements is true?" 1servlet-mapping element should be inside servlet elementurl-pattern can't be defined that wayif you make the http call: http://host/Hello.jsp the servlet container will execute MyServlet Y

It would work with any extension excepting jsp,html,htmIt should be <urlpattern> tag instead of <url-pattern>

8.Which two of the following statements are true? 2The deployment descriptor must be well formed, i.e. every tag every tag must have a matchingclosing tag (or be closed with a forward slash) YThe deployment descriptor contains information on the configuration of servlets in a webapplication YA single deployment descriptor may be used to configure multiple web applicationsThe deployment descriptor cannot contain commentsdeployment descriptor can be edited by the designer

9.Which one of the following statements is true? 1A file marked as load-on-startup will be returned as the default from a request to a directorywith no file component.

Page 3: Java Advanced Java Servlets ARQB TRCQB v1.0

By default if a directory contains a file called welcome.jsp it will be returned from a requestwhere no file name is specified.Only a jsp file can be marked as a welcome file, not a servletA file or a jsp can be marked as a welcome file within the deployment descriptor YA jsp file will be placed in the source packages folder

10.Which one of the following options would initialize a stream for sending text to a browser? 1

OutputReader out = response.getStream();OuputStream out = response.getStream();PrintWriter out = response.getWriter(); YServletWriter out =response.getWriterStream();StreamWriter out = response.getStreamWriter();

11."Which one of the following is the correct way of retrieving the value of the ""User-Agent""header value from the request from the service method( eg: doPost() )?" 1"String userAgent=request.getParameter(""User-Agent"");""String userAgent=request.getHeader(""User-Agent"");" Y"String userAgent=request.getRequestHeader(""User-Agent"");""String userAgent=getServletContext().getInitParameter(""User-Agent"");"

12.Which one of the following HTTP methods is used to show the client what the server isreceiving? 1GETTRACE YRETURNOPTIONS13."Which one of the following is the correct way of setting the header named""CONTENT-LENGTH"" in the HttpServletResponse object?" 1"response.setHeader(CONTENT-LENGTH,""numBytes"");"response.setHeader(1024);"response.setHeader(""CONTENT-LENGTH"", ""numBytes"");" Y"response.setHeader(""CONTENT-LENGTH"",1024);"

14.Which one of the following servlet code fragments gets a binary stream for writing an imageor other binary type to the HttpServletResponse? 1java.io.PrintWriter out=response.getWriter();ServletOutputStream out=response.getOutputStream(); Yjava.io.PrintWriter out=new PrintWriter(response.getWriter());ServletOutputStream out=response.getBinaryStream();

15.Which three of the following methods are declared in HttpServletRequest as opposed to inServletRequest? 3getMethod() YgetHeader() YgetCookies() Y

Page 4: Java Advanced Java Servlets ARQB TRCQB v1.0

getInputStream()getParameterName()16.Which one of the following is the abstract method in the HttpServlet abstract class? 1service()doGet()doPost()No abstract methods Y17.Which one of the following HttpServletResponse is used to redirect an HTTP request toanother URL? 1sendURL()redirectURL()redirecthttp()sendRedirect() Y18."Where does the response redirect happen?Select one correct answer from the following." 1On the Servlet ContainerOn the Servlet ProgramOn the Client YOn the Deployment Descriptor

19."Where does the request dispatch happen?Select one correct answer from the following." 1On the Server YOn the Servlet ProgramOn the ClientOn the Deployment Descriptor

20."When is it not possible to call the sendRedirect() method of response object?Select one correct answer from the following." 1After creating a connection to the Database.After the response is already commited. YAfter iterating through the resultSet objectAfter opening an I/O stream

21.Which one of the following is a valid tag for configuring a listener class? 1"<contextlistener> <listener-class>mypackage.SomeListener</listener-class> </contextlistener>""<listener> <listener-class>mypackage.SomeListener</listener-class> </listener>" Y"<context-listener> <listener-class>mypackage.SomeListener</listener-class> </context-listener>""<listener><class>mypackage.SomeListener</class></listener>"22.Which two of the following statements are true? 2The sendRedirect method can only process an absolute URL as a parameterAfter a sendRedirect method call, the browser will automatically return to the original URL

Page 5: Java Advanced Java Servlets ARQB TRCQB v1.0

If the sendRedirect method is called after the response has been committed, an exception will bethrown YSendRedirect is a method of the HttpServletResponse Interface YSendRedirect is a method of the HttpServletRequest class

Which one of the following statements is true about the Web ApplicationDeploymentDescriptor? 1There cannot be leading nor trailing spaces for PCDATA within text nodesThe servlet container must ensure that role-names in auth-constraint are defined in security-roleelementURI paths specified are assumed to be URL decoded form YWeb Application DD cannot be edited by a deployer

Which one of the following statements is false about the method log? 1log is a method GenericServlet classlog is a method of ServletContext interfacelog is an overloaded methodThere is a log method with the signature log(String, Throwable)There is a log method with the signature log(String ,int) Y

Which one of the following types is returned by the ServletContext method getResource andgetResourceAsStream? 1InputStream and StringString and InputStreamURL and InputStream YURL and StreamReaderWhich two of the following are mandatory elements of the web-resource-collection element? 2

web-resource-name Yurl-pattern Yhttp-methodauth-constraintdescription

"Consider the following servlet code:

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyFirstServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {

Page 6: Java Advanced Java Servlets ARQB TRCQB v1.0

res.setContentType(""text/html""); }

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException { res.getWriter().println(""This is doGet!""); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException { res.getWriter().println(""This is doPost!""); } }

This servlet is executed by clicking on a submit button of a form in a web page: <form action=""/MyFirstServlet"" method=POST> <input type=submit> </form>

Predict the output.Select one answer from the following." 1This is doPostThis is doGet """This is doPost"" as well as ""This is doGet"""It will not print anything Y“This is doGet!” is printedWhich two of the following methods must be implemented to create a class that implements anHttpSessionListener? 2public void sessionCreated(HttpSessionEvent se) Ypublic void sessionAdded(HttpSessionEvent se)public void sessionDestroyed(HttpSessionEvent se) Ypublic void sessionModified(HttpSessionEvent se)Public void sessionUpdated(HttpSessionEvent se)

"Consider the following:<web-app> <servlet> ..... </servlet> <listener> <listener-class>com.javarich.LogListener</listener-class> </listener></web-app>

Page 7: Java Advanced Java Servlets ARQB TRCQB v1.0

Which one of the following will happen because of the above entry in the DeploymentDescriptor(DD)?" 1Log all session information as they occurProvide a Log Servlet for the entire applicationCreate a listener as defined by the com.javarich.LogListener class. YThe webapp will not be loaded due to a parse exception of the DD<Listener> must come under <servlet>tag

"Your servlet can specify a different session timeout than the one defined in the DeploymentDescriptor.Which one of the following methods need to be called to achieve this?" 1HttpServlet#setSessionTimeout(int interval)HttpSession#setMaxInactiveInterval(int seconds) YHttpSession#setSessionTimeout(int interval)HttpSession#setMinInactiveInterval(int interval)The timeout in deployment descriptor cannot be changed.

"What will happen when you attempt to compile and run the following code (assuming menu.jspis available)?

package com.evaluvate;import java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*;

public class ReqD extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { ServletContext sc = this.getServletContext(); RequestDispatcher dis = sc.getRequestDispatcher(""menu.jsp""); if (dis != null){ dis.include(request, response); } PrintWriter out = response.getWriter(); out.print(""Output after menu.jsp""); } }

Select one answer from the following." 1Compilation error, the this object is not available within doGet"Compilation success and output of the contents of menu.jsp followed by ""output aftermenu.jsp"""Compilation success and output of the contents of menu.jsp onlyCompilation success but error at runtime Y

Page 8: Java Advanced Java Servlets ARQB TRCQB v1.0

"Consider the following code for the init() method of a servlet:public void init(){ Class.forName(""sun.jdbc.odbc.JdbcOdbcDriver""); // 1 Get DBURL here theConnection = DriverManager.getConnection(dbUrl, ""admin"", ""admin"");}

Assume that servletcontext is a reference to ServletContext for this servlet.

Which two of the following LOCs ""may"" correctly retrieve the DBURL parameter at //1?" 2

"servletcontext.getInitParameter(""DBURL"");" Y"this.getParameter(""DBURL"");""servletcontext.getParameter(""DBURL"");""this.getContextParameter(""DBURL"");""this.getInitParameter(""DBURL"");" Y

"Following is the code for doGet() and doPost() method of TestServlet: public void doGet(HttpServletRequest req, HttpServletResponse res){ try { PrintWriter pw = res.getWriter(); pw.println(""<html><head></head><body>""); String name = req.getParameter(""name""); String[] hobbies = req.getParameterValues(""hobbies"");pw.println(""Hello, ""+name+""!<br> As I understand, your hobbies are :"");for(int i=0; i< hobbies.length; i++) pw.println(""<br>""+hobbies[i]); pw.println(""</body></html>""); } catch(Exception e){ e.printStackTrace(); }}public void doPost(HttpServletRequest req, HttpServletResponse res){ doGet(req, res);}

Page 9: Java Advanced Java Servlets ARQB TRCQB v1.0

Which one of the following statements is correct?" 1This will only work for HTTP GET requestsThis will only work for HTTP POST requestsThis will work for HTTP GET as well as POST requests. YIt will throw an exception at runtime, as you cannot call doGet() from doPost()It'll throw an exception at runtime only if a POST request is sent to it

"Consider the following form and servlet code:

<form action=”printParams?param1=First” method=”post”><input type=”hidden” name=”param1” value=”First”/><input type=”text” name=”param1” value=”Second”/><input type=”radio” name=”param1” value=”Third”/><input type=”submit”/></form>

protected void doPost(HttpServletRequest request,HttpServletResponse response) throwsServletException,IOException{response.setContentType(“text/plain”);PrintWriter Out=response.getWriter();Out.write(“<html><body>”);String[] param1=request.getParameterValues(“param1);Forint i=0;i<parm1.length;i++){Out.Write(param1[i]+”:”);}Out.write(“</body></html>”);

}

Assuming the user changes none of the default setting s and presses SUBMIT, what will be theservlet output in the response?

Select one answer from the following." 1First:Second:ThirdFirst:Second:SecondFirst:Third:ThirdFirst:First:Second YNo response-servlet will not compile

"What is the maximum number of parameters that can be forwarded to the servlet from the

Page 10: Java Advanced Java Servlets ARQB TRCQB v1.0

following HTML form?<html><body><form action=”ParamServlet” method=”get”. <select name=”Languages” size=”3” multiple><option value=”JAVA” selected>Java</option><option value=”CSHARP” selected>C#</option><option value=”C” selected>C</option><option value=”CPLUS” selected>C++</option><option value=”PASCAL” selected>pascal</option><option value=”ADA” selected>Ada</option> </select> <input type=”submit” name=”button”/></form></body></html>

Select one answer from the following."10567 Y4

Which one of the following circumstances can cause the HttpServletRequest.getHeaders(Stringname) method to return null? 1If there are no request headers present in the request for the given header name.If there are multiple headers for the given header nameIf the container disallows access to the header information YIf there are multiple values for the given header nameThere is no such method on HttpServletRequest

Which three of the following are likely to be found as request header fields?3Accept YWWW-AuthenticateAccept-Language YFrom YClient-Agent

"What will be the outcome of running the following servlet code?

Long date=request.getDateHeader(‘Host”);

Page 11: Java Advanced Java Servlets ARQB TRCQB v1.0

response.setContentType(“text/plain”);response.getWriter().write(“”+date);

Select one answer from the following." 1A formatted date is written to the response-1 is written to the responseIllegalArgumentException YNumberFormatExceptionDateFormatException

"What will be the outcome of attempting to run the following servlet code?

String[] values=request.getHeaders(“Joy”);Response.setContentType(“text/plain”);Response.getWriter().write(values[0]);

Select one answer from the following." 1IllegalArgumentExceptionNumberFormatExceptionWill not run: 1 compilation error.Will not run:2 compilation errors. YNull written to the response

Which one of the following methods is NOT idempotent? 1GetPost YTraceHeadOptions

Which two of the following circumstances will cause a servlet instance’s destroy() method to benever called? 2As a result of a web application closedown requestWhen init() has not run to completion successfully YIf no thread has ever executed the service() methodAfter destroy() has already been called YDuring Servlet replacement"Consider the following deployment descriptor(web.xml)file:

<session-config><session-timeout>30</session-timeout></session-config>

Page 12: Java Advanced Java Servlets ARQB TRCQB v1.0

Then, in the program code setMaxInactiveInterval(2400)(seconds) for the session object isinvoked. After how long would session expire?

Select one answer from the following." 130 minutes40 minutes YGives illegalStateExceptionNone of the listed options

Which one of the following is a valid life cycle event listener interface but is NOT configured in theweb.xml? 1HttpSessionListenerSessionActivationListenerHttpSessionBindingListener YContextAttributeListenerSessionAttributeListenerWhich one the following statements is correct? 1

Only ServletContext interface has method getRealPathAnswr 1 is incorrect because also HttpServletRequest has getRealPath methodYMethod getRealPath throws an IllegalArgumentException if it can't convert the argument to alocal filesystem pathMethod getPathInfo never returns nullMethod getRealPath throws an IllegalStateException if it can't convert the argument to a localfilesystem path"Consider the following code snippet:

package com.evaluation;import java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*;

public class ReqD extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { ServletContext sc = this.getServletContext(); RequestDispatcher dis = sc.getRequestDispatcher(""/menu.jsp""); if (dis != null){ dis.include(request, response); } PrintWriter out = response.getWriter(); out.print(""Output after menu.jsp""); } }Which one of the following will be the correct outcome when the above is executed?" 1

Page 13: Java Advanced Java Servlets ARQB TRCQB v1.0

Compilation and output of the contents of menu.jsp only"Compilation and output of the contents of menu.jsp followed by ""Output after menu.jsp""" Y

Compilation errorCompilation, but runtime error, the buffer has been flushed

Which one of the following statements is true? 1

HttpSessionActivationListener class is used to support sessions in a distributed environment Y

HttpSessionActivationListener cannot be used where a session is based on URL rewriting

HttpSessionActivationListener configuration uses the <session-activation> tagHttpSessionActivationListener configuration uses the <session-listener> tag

Which one of the following methods will be invoked when a ServletContext is initialized? 1

contextInitialized() on a ServletContextListener Object. YcontextCreated() on a ServletContextListener ObjectcontextStateChanged() on a ServletContextListener Objectinit() on a ServletContextListener Object.initialized() on a ServletContextListener Object.

Which two of the following statements are true? 2

Every (non distributed) web application has only one instance of ServletContext YEvery instance of HttpServlet has only one instance of ServletContextThe ServletContext object is retrieved via the getServletContext method of ServletConfigYThe ServletConfig object is retrieved via the getServletConfig method of ServletContext

Which two of the following can store data attributes? 2

HttpServletResponseHttpSession YHttpServletServletContext YServletConfig

Which two of the following statements are true? 2A request attribute will be visible to all subsequent request from the same clientA session attribute will, by default be visible to all subsequent requests from the same client Y

Page 14: Java Advanced Java Servlets ARQB TRCQB v1.0

Attributes are stored with the data type of Object YServletContext attributes are only visible within the same servlet.ServletCofig attributes are visible to all subsequent request for the same client

"Consider the following code:

//in file UserData.javapublic class UserData{ ...data fields and methods...}

//In file LoginServlet.javapublic class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) { UserData userdata = loginUser(req); req.getSession().setAttribute(""userdata"", userdata); //1 }}The UserData object is added to the session.You need to know, whenever it is added to the session.

Which one of the following is the right way to accomplish this?" 1

Make the class UserData implement HttpSessionBindingListener YMake the class UserData implement HttpSessionListenercall some method on UserData object after //1Make the class UserData implement HttpSessionAttributesListenerThis cannot be done

Which one of the following is the correct way of writing the init-param for a servlet in web.xmldeployment descriptor file? 1"<servlet> <servlet-name>HelloGeneric</servlet-name> <servlet-class>HelloGeneric</servlet-class> <init-param> <param-name>count</param-name> <param-value>13</param-value>

Page 15: Java Advanced Java Servlets ARQB TRCQB v1.0

</init-param> </servlet>

<servlet-mapping> <servlet-name>HelloGeneric</servlet-name> <url-pattern>/HelloGeneric</url-pattern> </servlet-mapping>" Y

"<servlet>

<init-param> <param-name>count</param-name> <param-value>13</param-value> </init-param>

<servlet-name>HelloGeneric</servlet-name> <servlet-class>HelloGeneric</servlet-class> </servlet>

<servlet-mapping> <servlet-name>HelloGeneric</servlet-name> <url-pattern>/HelloGeneric</url-pattern> </servlet-mapping>"

"<servlet>

<servlet-name>HelloGeneric</servlet-name>

<init-param> <param-name>count</param-name> <param-value>13</param-value> </init-param>

<servlet-class>HelloGeneric</servlet-class> </servlet>

<servlet-mapping> <servlet-name>HelloGeneric</servlet-name> <url-pattern>/HelloGeneric</url-pattern> </servlet-mapping>"

Page 16: Java Advanced Java Servlets ARQB TRCQB v1.0

"<servlet> <servlet-name>HelloGeneric</servlet-name> <servlet-class>HelloGeneric</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloGeneric</servlet-name> <url-pattern>/HelloGeneric</url-pattern> <init-param> <param-name>count</param-name> <param-value>13</param-value> </init-param></servlet-mapping>"

" <init-param> <param-name>count</param-name> <param-value>13</param-value> </init-param>

<servlet>

<servlet-name>HelloGeneric</servlet-name> <servlet-class>HelloGeneric</servlet-class> </servlet>

<servlet-mapping>

<servlet-name>HelloGeneric</servlet-name> <url-pattern>/HelloGeneric</url-pattern>

</servlet-mapping>"Which two of the following statements are correct about the HttpServletResponse's buffer?

You can specify its size with the method setBufferSize with either a number ending with kb or theword noneIf you use setBufferSize method after any content has been written the buffer won't be changed

reset will clear uncommitted data including headers and status line YresetBuffer won't clear headers nor status line Y

default buffer size will be 12kb

Which two of the following statements are correct?HttpServlet.init() throws ServletException YHttpServlet.service throws ServletException and IOException Y HttpServlet.destroy() throwsServletExceptionHttpServlet.doHead() throws ServletException

Page 17: Java Advanced Java Servlets ARQB TRCQB v1.0

HttpServlet.doPut() throws IOException

Which one of the following statements is correct about the way a servlet can access itsinitialization parameters?

By simply calling getInitParameter from any of the servlets methods (for example doGet) Y

It must be done only by calling getServletConfig().getInitParaemterIt can only be done by overriding the method init(ServletConfig config)It can be done by calling getServletContext().getInitParameter method

"Assume that the following servlet mapping is defined in the deployment descriptor of a webapplication:

<servlet-mapping><servlet-name>TestServlet</servlet-name><url-pattern>*.jsp</url-pattern></servlet-mapping>

Which one of the following requests will NOT be serviced by TestServlet?"/hello.jsp/gui/hello.jsp/gui/hello.jsp/bye.jsp/gui/jsp Y/gui/*.jsp

"Your servlet class depends on a utility class named com.abc.TaxUtil. Where would you keep the TaxUtil.class file? Select one answer from the folllowing."

WEB-INFWEB-INF/classesWEB-INF/libWEB-INF/jarsWEB-INF/classes/com/abc Y

"Consider the following code for the doGet() method:

public void doGet(HttpServletRequest req,HttpServletResponse res){PrintWriter out = res.getWriter);out.println(""<html><body>Hello</body></html>"");//1

Page 18: Java Advanced Java Servlets ARQB TRCQB v1.0

if(req.getParameter(""name"") == null){res.sendError(HttpServletResponse.SC_UNAUTHORIZED);}}

Which one of the following lines can be inserted at //1 so that the above code does NOT throwany exception? "if ( ! res.isSent() )if ( ! res.isCommitted() ) Yif ( ! res.isDone() )if ( ! res.isFlushed() )if ( ! res.flush() )

"What is printed as output on the server console when the following servlet program runs forthe first time?

1.import java.io.IOException;2.import java.io.PrintWriter;3.mport javax.servlet.*;4.public class HelloGeneric extends GenericServlet {5.public HelloGeneric() {6.super();7.System.out.println(""constructor "");8.}9.public void init() throws ServletException {10. super.init();11. System.out.println(""init "");12.}13.public void init(ServletConfig arg0) throws ServletException {14.super.init(arg0);15.System.out.println(""init with ServletConfig "");16.}17.public void service(ServletRequest request, ServletResponse response) throwsServletException, IOException {18.System.out.println(“service method ”);19.}20.}

Select one answer from the following." 1constructor init init with ServletConfig service method Yinit with ServletConfig init service method init with ServletConfig service methodA runtime exception is thrown.Constructor init with ServletConfig init service method

Page 19: Java Advanced Java Servlets ARQB TRCQB v1.0

"Consider the following code:

public void doGet(HttpServletRequest req,HttpServletResponse res){HttpSession session = req.getSession();ServletContext ctx = this.getServletContext();if(req.getParameter(""userid"") != null){String userid = req.getParameter(""userid"");//1}}

You want the userid parameter to be available only to the requests that come from the sameuser. Which one of the following lines would you insert at //1?"session.setAttribute(""userid"", userid);" Y"req.setAttribute(""userid"", userid);""ctx.addAttribute(""userid"", userid);""session.addAttribute(""userid"", userid);""this.addParameter(""userid"", userid);"

"Consider the following deployment descriptor for a servlet :

<servlet-mapping><servlet-name>goldie</servlet-name><url-pattern>*.g</url-pattern></servlet-mapping>

Which two of the following requests will be serviced by the servlet named 'goldie'?" 2http://abcinc.com/ghttp://abcinc.com/goldie/temp.g Yhttp://abcinc.com/servlet/goldie/temphttp://abcinc.com/a/b/c/temp.g Yhttp://abcinc.com/goldie/empt.g

"What are the implications of using the HTTP GET method for a form submission?Select three answers from the following." 3

Page 20: Java Advanced Java Servlets ARQB TRCQB v1.0

You cannot pass binary data to the server. YYou cannot send unlimited (or a lot of) data to the server YYou cannot send multiple values for one parameter to the server.You can only reply with the HEADER information in the response.The parameters will be appended to the URL as a query string. Y

"Consider the following HTML page code:

<html><body><a href=""/servlet/HelloServlet"">POST</a></body></html>

Which one of the following methods of HelloServlet will be invoked when the hyperlink displayedby the above page is clicked? " 1doGet YdoPostdoFormdoHrefserviceGet

Which one of the following lines would initialize the out variable for sending a Microsoft Wordfile to the browser? 1PrintWriter out = response.getServletOutput();PrintWriter out = response.getPrintWriter();OutputStream out = response.getWriter();PrintWriter out = response.getOuputStream();OutputStream out = response.getOuputStream(); Y

Which two of the following methods would you use to retrieve header values from a request? 2

getHeader() of ServletRequestgetHeaderValue() of ServletRequestgetHeader() of HttpServletRequest YgetHeaders() of ServletRequestgetHeaders() of HttpServletRequest Y

"Assuming that the Servlet Container has just called the destroy() method of a servlet instance,which two of the following statements are correct?" 2Any resources that this servlet might hold have been released.The servlet container time out has exceeded for this servlet instance.The init() method has been called on this instance. Y

Page 21: Java Advanced Java Servlets ARQB TRCQB v1.0

None of the requests can EVER be serviced by this instance. YAll threads created by this servlet are done.

Which two of the following statements are true? 2The init method is called each time a Servlet service method runsThe init method is called by the container when it is placed into service YThe init method cannot be overridden because it is marked as final.When a container shuts down it will call the undeploy method of running ServletsWhen a container shuts down it will call the destroy method of running Servlets Y.

Which one of the following statements is true? (given that webapp is the root of the webapplication) 1The deployment descriptor must reside in the webapp\ directoryThe deployment descriptor must reside in the webapp\deploy directoryThe deployment descriptor must reside in the webapp\CONFIG directoryThe deployment descriptor must reside in the webapp\WEB-INF\ directory Y

Which two of the following statements are true? 2To be able to directly access a servlet the servlet-name must have a matching servlet-mapping Y

The init-param tag may contain java code between its opening and closing brackets.The welcome-file tag can mark a servlet as the default item that is returned from a url. YThe welcome-file tag must point to a servlet called welcomeThe error-page tag must point to an html or JSP page, not a servlet.

"You have configured your web application deployment descriptor to make some initializationparameters available to every servlet.Which one of the following will retrieve those parameters?" 1The getInitParameter method of ApplicationContextThe getInitParameter method of ServletContext YThe getConfigParameter method of ServletContextThe getSevletInitParam method of SevletContextThe geAttribute method of ServletContext

"The users of your web application do not accept cookies. Which one of the following statements is correct? " 1

You cannot maintain client stateURLs displayed by static HTML pages may not work properly YYou cannot use URL rewritingYou cannot set session timeout explicitly

Which two of the following statements are true? 2

Page 22: Java Advanced Java Servlets ARQB TRCQB v1.0

New users can be added to a container using the addNewUser method.New users can be added to a container using the addUser methodUser and role configuration is not part of the Servlet/JSP specification YAn empty auth-constraint tag means no users will be able to access a resource YAn empty auth-constraint tag means all users will be able to access a resource

"Given the code of doGet() method of a servlet as follows:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{

String userId = loginUser(req); //this method takes the credentials from the request and logs in the user.

if(userId == null)

{

// 1 Should send SC_FORBIDDEN

}

else

{

PrintWriter out = response.getWriter();

generateAndPublishData(out); //this method writes appropriate date to out.

}

}

The data should be sent to the client only if loginUser() returns a non null userid, otherwise astatus of SC_FORBIDDEN should be sent. What can be placed at //1 to fulfill this requirement? Select three answers from the following.

"req.getRequestDispatcher(""errorpage.jsp"").dispatch(req, res,HttpServletResponse.SC_FORBIDDEN)"throwServletException(HttpServletResponse.SC_FORBIDDEN)res.setStatus(HttpServletResponse.SC_FORBIDDEN)Y

Page 23: Java Advanced Java Servlets ARQB TRCQB v1.0

"res.sendError(HttpServletResponse.SC_FORBIDDEN, ""You are not authorized."")" Yres.sendError(HttpServletResponse.SC_FORBIDDEN) Y

Which two of the following are sensible ways of sending an error page to the client in case of abusiness exception that extends from java.lang.Exception?

Catch the exception and use RequestDispatcher to forward the request to the error page Y

Do not catch the exception and define the 'exception to error-page' mapping in web.xmlCatch the exception, wrap it into ServletException and define the 'business exception toerror-page' mapping in web.xml YCatch the exception, wrap it into ServletException, and define the 'ServletException toerror-page' mapping in web.xml.Do not do anything, the servlet container will automatically send a default error page.

"Identify correct statements about session management from the list below.(Select two answers)" 2

Session management is usually dependent on a hidden form field called JSessionId.The unique identifier for a session may be passed back and forward through a name/value pairin the URL.The name is jsessionid. YIf a cookie used for default session management, there is some flexibility with the name used forthe cookie.The cookie used for default session management must be added to the response using theHttpServletResponse.addCookie(Cookie thecookie) methodThe rules for rewriting URLs for links may be different from those for rewriting URLs forredirection. Y

"What are the possible outcome from executing the doGet method in Toyservlet given below?

public class ToyServlet extends HttpServlet{public void doGet(HttpServletRequest req,HttpServletResponse res) throwsServletException,IOException

Page 24: Java Advanced Java Servlets ARQB TRCQB v1.0

{RequestDispatcher rd=getServletContext().getRequestDispatcher(“JoyServlet”);rd.forward(req,res);}}

Select two answers from the following." 2HTTP 500 eror YNullPointerExceptionHTTP 404 errorAn illegalArgumentException YHTTP 255 error

"Consider the following servlet code:

public class TestServlet extends HttpServletimplements SingleThreadModel{private static Hashtable staticHash = new StringBuffer();private Hashtable instanceHash = new StringBuffer();public void doGet(HttpServletRequest req, HttpServletResponse res){StringBuffer sb = new StringBuffer()HttpSession session = req.getSession();ServletContext ctx = getServletContext();// 1}}

Which of the following lines can be inserted at //1 so that the StringBuffer object referred to bythe variable sb can only be accessed from a single thread at a time?(Select two answers)" 2

"staticHash.put(""sb"", sb)""instanceHash.put(""sb"", sb)"Y"session.setAttribute(""sb"", sb)" “ctx.setAttribute(""sb"", sb)"“req.setAttribute(""sb"", sb)" Y

Page 25: Java Advanced Java Servlets ARQB TRCQB v1.0

"Consider the following servlet code:

public class LogTestServlet extends HttpServlet{public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException{String logMsg = ""LogTestServlet.service():Probe message"";//1}}

Which of the following statements can be inserted at //1 so that logMsg may be entered into theservlet log file? (Select three answers)" 3log(logMsg); Yreq(logMsg);getServletConfig().log(logMsg);getServletContext().log(logMsg); YgetServletConfig().getServletContext().log(logMsg); Y

Which three of the following codes represent internal dispatch to servlet requests? 3"<filter-mapping><filter-name>All Dispatch Filter</filter-name><servlet-name>*</servlet-name><dispatcher>FORWARD</dispatcher></filter-mapping>" Y

"<filter-mapping><filter-name>All Dispatch Filter</filter-name><servlet-name>*</servlet-name><dispatcher>ERROR</dispatcher></filter-mapping>" Y

"<filter-mapping><filter-name>All Dispatch Filter</filter-name><servlet-name>*</servlet-name><dispatcher>RESPONSE</dispatcher></filter-mapping>" Y

"<filter-mapping><filter-name>All Dispatch Filter</filter-name><servlet-name>*</servlet-name>

Page 26: Java Advanced Java Servlets ARQB TRCQB v1.0

<dispatcher>REQUEST</dispatcher></filter-mapping>"

"<filter-mapping><filter-name>All Dispatch Filter</filter-name><servlet-name>*</servlet-name></filter-mapping>"

Which two of the following are names of special attributes associated with the dispatchingmechanism? 2java.servlet.include.servlet_namejavax.http.servlet.include.query_namejavax.servlet.include.servlet_path Yjavax.servlet.forward.request_urljavax.servlet.include.path_info YWhich two of the following are true statements about sessions? 2

Sessions can span web applicationsSessions can be cloned across JVMs YSessions are destroyed only after a predefined period of inactivitySessions can be set to never time out YYou can use the deployment descriptor to cause sessions to expire after a set number of requests.

Which one of the following lines of code, in the doPost() method of a servlet, uses the URLrewriting approach to maintaining sessions? 1useURLRewriting();"out.println(response.rewrite(""<a href='/servlet/XServlet'>Click here</a>""));""out.println(""<a href=' ""+request.rewrite(""/servlet/XServlet"")+"" '>Click here</a>""));"

"out.println(""<a href=' ""+response.encodeURL(""/servlet/XServlet"")+"" '>Click here</a>""));"Y

"out.println(""<a href=' ""+request.encodeURL(""/servlet/XServlet"")+"" '>Click here</a>""));"

Which three of the following elements are allowed in the <filter-mapping> element of thedeployment descriptor? 3

<servlet-name> Y<filter-class><dispatcher> Y<url-pattern> Y<filter-chain>

Page 27: Java Advanced Java Servlets ARQB TRCQB v1.0

"Rahul is working on a web application. He wants to have a functionality that will enable him toknow if the session the user is using is from cookie or from URL .

Which two of the following methods should he use?" 2isRequestedIdFromCookieisRequestedSessionIdFromURL YisRequestedId FromURLisRequestedSessionIdFromCookie Y Requested SessionIdIsFromCookie

Which two of the following statements are correct? 2

A call to ServletRequest.setAttribute() with a new name causes a call to theattributeAdded()method on ServletRequestListenerA call to ServletRequest.setAttribute() with a new name causes a call to theattributeAdded()method on ServletRequestAttributeListener YA call to ServletRequest.setAttribute() with an existing name causes a call to theattributeAdded()method on ServletRequestAttributeListenerA call to ServletRequest.setAttribute() with an existing name causes a call to theattributeReplaced()method on ServletRequestAttributeListener YA call to ServletRequest.setAttribute() with an existing name causes a call to theattributeModified()method on ServletRequestAttributeListener

Which two of the following are true regarding the parameters defined using the<context-param> element of a deployment descriptor? 2

They are thread safe. YThey are accessible from multiple threads simultaneously and from any servlet of the webapplication. YThey can be modified using the setAttribute() method.They can be modified using the setParameter() method.They can be modified using the setInitParameter() method.

"Consider the following code:public class WWServlet extends HttpServlet{....}Which one of the following abstract methods do you need to compulsorily implement so that itcompiles without any errors?" 1

Page 28: Java Advanced Java Servlets ARQB TRCQB v1.0

service()init()doGetall doXXX methodsNo method as HttpServlet has dummy implementations Y

Which two of the following statements are true? 2

The sendRedirect method can only accept an absolute URLThe sendRedirect method can only accept a relative URLThe sendRedirect method can accept either an absolute or relative URL YA redirect cannot be performed after anything has been written to the outputstream YSendRedirect() is declared in HttpServletRequest interface

Which two of the following statements are correct about object implementingHttpSessionBindingListener interface? 2

valueBound method will be called before the object is accessible through getAttribute method Y

valueBound method will be called after the object is accessible through getAttribute method

valueUnbound method will be called before the object is removed from the sessionvalueUnbound method will be called after the object is removed from the session YvalueBound method will be called before the object is bound to the session.

"Predict the output of the following servlet code:

Line no 1)Import java.io.*;Line no 2)Import javax.servlet.*;Line no 3)Import javax.servlet.http.*;Line no 4)Public class ServletTest extends HttpServletLine no 15{Line no 6)protected void doGet(ServeltRequest request,ServletResponse response)throwsServletException,IOExceptionLine no 7){Line no 8)HttpSession ss=request.getSession(false);Line no 9)ss.invalidate();Line no 10)ss.setAttribute(“illegal”,”exception thrown”);}

Page 29: Java Advanced Java Servlets ARQB TRCQB v1.0

}

Select one answer from the following." 1Will not compile YNullPointerException at line 8 on clients first call to servletllegalStateException at line10None of the listed options

Which one of the following interfaces or classes is used to retrieve the session associated with auser? 1

GenericServletServletConfigServletContextHttpServletHttpServletRequest Y

Which one of the following is a method of the HttpSessionListener interface?1SessionCreated YAttributeRemovedValueBoundSessionDidActivateSessionInitialized

Which one of the following methods will be invoked on a session attribute that implementsHttpSessionBindingListener when the session is invalidated? 1

sessionDestroyedvalueUnbound YattributeRemovedsessionInvalidatedsessionDeactivated

Which one of the following method calls will ensure that a session will never be expunged by theservlet container? 1session.setTimeout(0);session.setTimeout(-1);session.setTimeout(Integer.MAX_VALUE);session.setTimeout(Integer.MIN_VALUE);HttpSession.setMaxInactiveInterval(int seconds) Y

Page 30: Java Advanced Java Servlets ARQB TRCQB v1.0

Which one of the following statements is true? 1A session attribute can store either a class or primitive typeA session attribute is stored with the type Object YA session attribute can only be a data type that implements the serializable interfaceA session attribute is stored with a call to the setSessionAttribute method

"Servlets that implement the SingleThreadModel cannot share a single HttpSession Object acrossmultiple servlets.State True or False." 1

True Y

Which one of the following statements is true about sessions? 1

Objects can only be stored in sessions if the user has cookies activatedBy default, session objects only exist for the scope of a requestObjects created within a session are stored as cookies in the browserSession variables are stored with the Application type ObjectBy default request parameters are stored within a session Y

Which one of the following classes is appropriate for monitoring when users sign into the systemand recording it in the log? 1

ApplicationContextAttributeListenerHttpSessionListener YHttpSessionActivationListenerHttpLoginListenerServletContextListener

Which one of the following methods would you use to acquire the stream to write binary data inresponse to a request to from servlet? 1

getOutputStream() of ServletResponse interface. YgetOutputStream() of HttpServletResponse interface.getFileOutputStream() of HttpServletResponse interfacegetWriter() of HttpServletResponse interfacegetWriter() of ServletResponse interface

Page 31: Java Advanced Java Servlets ARQB TRCQB v1.0

"Cactus is severside unit testing.Cactus is serverside functional testing.

Which one of the following statements is appplicable to the above?"1Statement a is true and b is false YStatement a is false and b is trueStatement a is true and b is trueStatement a is false and b is false

"Which two of the following statements correctly store an object associated with a name at aplace where all the servlets/JSPs of the same webapp participating in a session can use it?

(Assume that request, response, name, value etc. are references to objects of appropriatetypes.)" 2

request.setAttribute(name, value)response.setAttribute(name, value)request.getSession().setAttribute(name, value) Yservlet.getServletContext().setAttribute(name, value) Yrequest.setParameter(name, value)

Which two of the following situations will result in a session getting invalidated? 2

No request is received from the client for longer than the session timeout period YThe client sends a KILL_SESSION request.The servlet container decides to invalidate a session due to overloadThe servlet explicitly invalidates the session YA user closes the active browser window

Which two of the following statements are true? 1

The HttpSessionActivationListener is a marker interface and supplies no methodsHttpSessionActivationListener must be configured in the deployment descriptor via the listenertagThe HttpSessionActivationListener interface supplies two methods sessionDidActivate andsessionWillPassivate YThe HttpSessionActivationListener cannot be used to monitor migration of sessions betweenJVM's

Page 32: Java Advanced Java Servlets ARQB TRCQB v1.0

"Consider the following URL:

http://www.godaddy.com/servlet/HelloWorld;jsessionid=ab123f556

The above is a correct example of _______________." 1use of URL-rewriting for authenticationuse of URL-rewriting for session tracking Yuse of html hidden parameters for session trackinguse of cookie based session tracking.use of HttpSession for session tracking.

"<web-app> ... <session-config> <session-timeout>15</session-timeout> </session-config>....

What does the above entry in the Deployment Descriptor cause?Select one answer from the following." 1

Only allows users to be connected for 15 days total.Sets the session timeout interval to 15 minutes. YOnly allows users to be connected for 15 minutes totalSets the session timeout interval to 15 days.Sets the session timeout interval to 15 seconds.

"What can be inferred by the following deployment descriptor?

<error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/math_error.html</location></error-page>

Select one answer from the following." 1Route any request to your web application for a page or servlet that cannot be found tomath_error.htmlPrevents throwing ArithmeticException from math_error.htmlRoute any ArithmeticException thrown from your servlet to math_error.html YRoute any ServletExceptions with the code 404 thrown from your servlet to math_error.html

Page 33: Java Advanced Java Servlets ARQB TRCQB v1.0

Which one of the following method calls creates a binary output stream in a servlet? 1response.getOutputStream(); Yrequest.getWriter();request.getOutputStream();response.getWriter();Session.getOutputStream();

"You have two classes named 'MyServletContextAttributesListener' and 'MyHttpSessionListener'which implement interfaces as suggested by their names.

Which one of the following XML fragments, written directly under the <web-app> tag, correctlyregister these classes so that their instances may receive appropriate notifications?" 1

"<listener> <listener-class>MyServletContextAttributesListener</listener-class> <listener-class>MyHttpSessionListener</listener-class></listener>"

"<listener-class>MyServletContextAttributesListener</listener-class><listener-class>MyHttpSessionListener</listener-class>"

"<listener> <listener-class>MyServletContextAttributesListener</listener-class></listener>

<listener> <listener-class>MyHttpSessionListener</listener-class></listener>" Y

"<context-listener> <listener-class>MyServletContextAttributesListener</listener-class></context-listener>

<session-listener> <listener-class>MyHttpSessionListener</listener-class></session-listener>"

"<listener>MyServletContextAttributesListener</listener><listener>MyHttpSessionListener</listener>"

Identify three techniques from the following that can be used to implement 'sessions' if the clientbrowser does not support cookies. 3 Using Http headers.

Page 34: Java Advanced Java Servlets ARQB TRCQB v1.0

Using https protocol YHidden form fields. YURL rewriting YIt cannot be done without cookie support.

"Consider the following deployment descriptor snippet:<filter-mapping> <filter-name>Filter1</filter-name> <servlet-name>ServletToFilter</servlet-name></filter-mapping><filter-mapping> <filter-name>Filter2</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

Which one of the following is true about the above code?" 1

The filter-mapping tag does not have a servlet-name sub elementFilter1 will be invoked before Filter2 if ServletToFilter is requestedFilter2 will be invoked before Filter1 if ServletToFilter is requested YOnly Filter1 will be invoked by a valid request to ServletToFilter

Which one of the following statements is true? 1

Once an ServletRequest attribute has been set, it is visible to all subsequent requestsData in a HttpSession attribute will be available if the web server restarts.Data in the ServletContext can be shared by any servlet of the same web application YThe getParameter method of HttpSession will retrieve a session attribute

Which two of the following statements are true? 2

The doFilter method is always invoked by the container, never within a programmers code

A filter can be invoked either through being declared in WEB.XML or explicitly within aprogrammers codeFilters are associated with a URL via the filter-mapping tag YFilters can be initialised via the filter-init-param tag in the deployment descriptorFilters can be initialised via the init-param tag in the deployment descriptor Y

Page 35: Java Advanced Java Servlets ARQB TRCQB v1.0

Which three of the following statements are true? 3

The getSession method of HttpServletRequest has a return type of HttpSession. YThe getSession method of HttpServletResponse has a return type of HttpSession.getSession(false) will return any existing session but not create a new one if none exists YgetMaxInactiveInterval() returns an int value that represents time in seconds YgetMaxInactiveInterval() returns an int value that represents time in milliseconds

Which of the following statements are true?(Select three answers) 3

A session will always be invalidated if a user shuts down their browserA session will always be invalidated if the servlet container restarts YA session can be invalidated by calling the invalidate method of the HttpSession class YA session cannot be invalidated via programmer code.The session timeout interval can be specified in the deployment descriptor. Y

Which three of the following are methods of the HttpServlet class used to process HTTPrequests? 3doDelete YdoRemovedoPut YdoHead YdoDown

Which one of the following statements is true? 1

A request attribute will exist for as long as the web applicationA session attribute is visible to all clients currently accessing the applicationServletContext attributes are visible to all clients currently accessing the application YA ServletContext attribute is only visible to the servlet from which it is created.The scope of an attribute can be HttpSession,ServletRequest or ServletConfig.

Page 36: Java Advanced Java Servlets ARQB TRCQB v1.0

"The following line of code exists in the doGet method of Servlet:

String sid = request.getParameter(""jsessionid"");

Which three of the following options will retrieve the HttpSession associated with the request?(Assume that the session has already been created.) " 3HttpSession session = request.getSession(); YHttpSession session = HttpSession.getSession(sid);HttpSession session = request.getSession(sid);HttpSession session = request.getSession(true); YHttpSession session = request.getSession(false); Y

Which two of the following classes/interfaces provide methods to write messages to a log file?2

GenericServlet YServletRequestHttpServletRequestServletContext YOnly GenericServlet

Which one of the following gives the correct return type for ServletContext.getResource() andServletContext.getResourceAsStream() methods? 1java.io.Resource and java.io.InputStreamjava.io.Resource and java.io.BufferedInputStreamjava.net.URL and java.io.InputStreamYjava.io.File and java.io.InputStreamjava.net.URL and java.io.FileInputStream

Which one of the following HTTP protocol methods is eligible to produce unintended side effectsupon multiple identical invocations beyond those caused by single invocation? 1

GETPOST YPUTOPTIONSHEAD

Which one of the following can be used to explicitly expunge the session object? 1

You cannot. It can only be expunged automatically after session timeout expires.

Page 37: Java Advanced Java Servlets ARQB TRCQB v1.0

By calling invalidate() on session object. YBy calling expunge() on session object.By calling delete() on session object.By calling finalize() on session object.

"Mahesh is a developer developing a web application. He wants his servlets to behave in a singlethreaded environment.Which one of the following will be the right choice to achieve the above?" 1

The servlet has to implement singleThreadedModel interface YThe servlet has to extend singleThreadedModel ClassThe servlet has to extend httpServlet which in turn implements SingleThreadedModel interface

It is not possible to make a servlet behave in a single threaded fashion

Which three of the following are true about servlet filters? 3

A filter must implement the destroy method YA filter must implement the do Filter method YA servlet may have multiple filters associated with it YA servlet that is to have a filter applied to it must implement the javax.servlet.FilterChaininterface.A filter that is part of a filter chain passes control to the next filter in the chain by invoking theFilterChain forward method.

Which one of the following jar files is used in cactus testing to perform tasks such as loggingentries and exit of methods, checking configuration, etc.?

Cactus.jarhttpclient.jarHttpunit.jarAspectjrt.jar YTaspCactus.jar

Which one of the following is a valid way to set up a mime mapping in the deploymentdescriptor? 1

"<mime-mapping-list><mime-type>text/plain</mime-type><extension>txt</extension></mime-mapping-list>"

Page 38: Java Advanced Java Servlets ARQB TRCQB v1.0

"<mime-mapping-list><mime-type>text/plain</mime-type></mime-mapping-list>"

"<mime-mapping><extension>txt/plain</extension>

</mime-mapping>"

"<mime-mapping><extension>txt</extension><mime-type>text/plain</mime-type></mime-mapping>" Y

"Sachin wants to debug his code while executing the code he has created.Select three methods from the following that he can use to do it." 3

System.out.println(); YUsing jdb(java debugger )tool YUsing javadebugging classUsing log() method of ServletContext YUsing debugger interface methods

Which two of the following statements are correct? 2

The getRequestDispatcher(String path) method of ServletRequest interface accepts parameterthe path to the resource to be included or forwarded to, which cannot be relative to the requestof the calling servlet.

The getRequestDispatcher(String path) method of ServletContext interface cannot acceptsrelative paths Y

The getRequestDispatcher(String path) method of ServletRequest interface accepts parameterthe path to the resource to be included or forwarded to, which can be relative to the request of

Page 39: Java Advanced Java Servlets ARQB TRCQB v1.0

the calling servlet Y

The getRequestDispatcher(String path) method of ServletContext interface can accepts relativepaths

Which two of the following are true about Cookies? 2

Cookies are created in clientside and stored in server sideMaximum of twenty cookies per website can be stored in a client machine YMinimum size of a cookie is 4kbCookies can be created by using Cookie class Y

Which two of the following attributes are thread safe? 2Context attributesSession attributesStatic variables in servletsInstance variables YLocal variables Y

Which two of the following are of the correct syntax for sendError() of HttpServletResponseinterface? 2

void sendError(int ) Yvoid sendError(int,int)void sendError(int,String) Yvoid sendError(String,String)void sendError(String)

Which two of the following statements are true? 2

sendError triggers the container to generate an error page YsetError method does not trigger the container to generate an error pagesetStatus method triggers the container to generate an error pagesetStatus method just sends the status code to the browser and browser displays it according tothe browser settings. Y

Which three of the following statements are true? 3

Page 40: Java Advanced Java Servlets ARQB TRCQB v1.0

To use a filter it must be declared in the deployment descriptorYFilters perform filtering in the doFilter method YFilters perform filtering in the filter methodFilter has access to a FilterConfig object from which it can obtain its initialization parameter Y

Every filter must have a service method

Which one of the following sets of tags will declare a filter and map it to a URL? 1"<filter><filter-name>Filter2</filter-name><filter-class>com.examulator.Filter</filter-class></filter>

<filter-mapping><filter-name>Filter2</filter-name><url-pattern>/*</url-pattern></filter-mapping>"Y

"<filter><filter-name>Filter2</filter-name><filter-class>com.examulator.Filter</filter-class>

<filter-mapping><filter-name>Filter2</filter-name><url-pattern>/*</url-pattern></filter-mapping></filter>"

"<filter><name>Filter2</name><class>com.examulator.Filter</class></filter><filter-mapping><name>Filter2</name><url>/*</url></filter-mapping>"

"<filter>

Page 41: Java Advanced Java Servlets ARQB TRCQB v1.0

<name>Filter2</name><class>com.examulator.Filter</class></filter><filter-map><name>Filter2</name><url>/*</url></filter-map>"

Which two of the following statements are NOT TRUE? 2

HttpServletResponseWrapper takes a constructor parameter of type HttpServletResponse.

Filters are called in the order they appear in the deployment descriptor.

Methods of the wrapper classes must not be overridden. Y

Filters are an example of the Intercepting Filter design pattern.Filters can only be invoked on incoming requests, and not on a dispatcher forward or include. Y

"Which one of the given options can be used in a servlet code that needs to access a binary filekept in WEB-INF/data.zip while servicing a request?

(Assume that config refers to the ServletConfig object of the servlet and context refers to theServletContext object of the servlet.) " 1

"InputStream is = config.getInputStream(""/WEB-INF/data.zip"");""InputStream is = context.getInputStream(""data.zip"");""InputStream is = context.getResourceAsStream(""/WEB-INF/data.zip"");" Y"InputStream is = context.getResourceAsStream(""WEB-INF/data.zip"");""InputStream is = config.getResourceAsStream(""WEB-INF/data.zip"");"

"Consider the code given below:

public class MyHSAListener implements HttpSessionAttributeListener{ public void attributeAdded(HttpSessionBindingEvent e){ } public void attributeRemoved(HttpSessionBindingEvent e){ }}

Page 42: Java Advanced Java Servlets ARQB TRCQB v1.0

Which one of the following statements is correct with respect to the above code?" 1

public void attributeReplaced(...){ } must be added. Ypublic void attributeChanged(...){ } must be addedThe parameter class should be HttpSessionEventThe parameter class should be HttpSessionAttributeEventIt will compile as it is.

Which one of the following elements of web.xml affect the whole web application instead of aspecific servlet? 1content-typeinit-paramlistener Yapplicationapp-config

"Given a servlet with the following method signature:

protected void doGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException { ServletContext ctx = getServletContext();//comment}

Which of the following if placed on the line after //comment will be valid to perform a browserredirect?(Select two answers)" 2

"ctx.sendRirect(""/login.jsp"");""response.sendRedirect(""/login.jsp"");"Y"response.sendRedirect(""login.jsp"");""request.redirect(""login.jsp"");" Y"request.sendRedirect(""login.jsp"");"

"A resource that is included using the RequestDispatcher.include method will share attributes ofthe originating resource.State true or false."1

True Y

Page 43: Java Advanced Java Servlets ARQB TRCQB v1.0

False

Which two of the following statements are true? 2

The HttpSessionBinding listener provides valueBound and valueUnbound methods YThe HttpSessionBinding listener provides attributeBound and attributeUnbound methods

The HttpSessionBindingListener does not need to be configured in the deployment descriptor Y

HttpSessionAttributeListener is a marker interface and provides no methods