Tuesday 27 August 2013

Top Most The Servlet Technology Model

The Servlet Technology Model
Objectives
For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method.
Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request.
Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.
Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.
Q1. You are creating a web form with this HTML:
11. <form action="sendOrder.jsp">
12. <input type="text" name="creditCard">
13. <input type="text" name="expirationDate">
14. <input type="submit">
15. </form>
Which HTTP method is used when sending this request from the browser?
A. GET    B. PUT    C. POST     D. SEND    E. FORM
Q2. Given a header in an HTTP request: X-Retries: 4 Which two retrieve the value of the header from a given HttpServletRequest request? (Choose two.)
A. request.getHeader("X-Retries")
B. request.getIntHeader("X-Retries")
C. request.getRequestHeader("X-Retries")
D. request.getHeaders("X-Retries").get(0)
E. request.getRequestHeaders("X-Retries").get(0)
Q3. For a given ServletResponse response, which two retrieve an object for
writing text data? (Choose two.)
A. response.getWriter()
B. response.getOutputStream()
C. response.getOutputWriter()
D. response.getWriter().getOutputStream()
E. response.getWriter(Writer.OUTPUT_TEXT)
Q4. Given an HttpServletRequest request and HttpServletResponse response,
which sets a cookie "username" with the value "joe" in a servlet?
A. request.addCookie("username", "joe")
B. request.setCookie("username", "joe")
C. response.addCookie("username", "joe")
D. request.addHeader(new Cookie("username", "joe"))
E. request.addCookie(new Cookie("username", "joe"))
F. response.addCookie(new Cookie("username", "joe"))
G. response.addHeader(new Cookie("username", "joe"))
Q5. Your web page includes a Java SE v1.5 applet with the following declaration:
11. <object classid='clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA'
12. width='200' height='200'>
13. <param name='code' value='Applet.class' />
14. </object>
Which HTTP method is used to retrieve the applet code?
A. GET         B. PUT
C. POST       D. RETRIEVE
Q6. You are creating a servlet that generates stock market graphs. You want to provide the web browser with precise information about the amount of data being sent in the response stream.
Which two HttpServletResponse methods will you use to provide this information? (Choose two.)
A. response.setLength(numberOfBytes);
B. response.setContentLength(numberOfBytes);
C. response.setHeader("Length", numberOfBytes);
D. response.setIntHeader("Length", numberOfBytes);
E. response.setHeader("Content-Length", numberOfBytes);
F. response.setIntHeader("Content-Length", numberOfBytes);
Q7. You need to retrieve the username cookie from an HTTP request. If this
cookie does NOT exist, then the c variable will be null.
Which code snippet must be used to retrieve this cookie object?
A. 10. Cookie c = request.getCookie("username");
B. 10. Cookie c = null;
11. for ( Iterator i = request.getCookies();
12. i.hasNext(); ) {
13. Cookie o = (Cookie) i.next();
14. if ( o.getName().equals("username") ) {
15. c = o;
16. break;
17. }
18. }
C. 10. Cookie c = null;
11. for ( Enumeration e = request.getCookies();
12. e.hasMoreElements(); ) {
13. Cookie o = (Cookie) e.nextElement();
14. if ( o.getName().equals("username") ) {
15. c = o;
16. break;
17. }
18. }
D. 10. Cookie c = null;
11. Cookie[] cookies = request.getCookies();
12. for ( int i = 0; i < cookies.length; i++ ) {
13. if ( cookies[i].getName().equals("username") ) {
14. c = cookies[i];
15. break;
16. }
17. }
Q8. Given:
10. public void service(ServletRequest request,
11. ServletResponse response) {
12. ServletInputStream sis =
13. // insert code here
14. }
Which retrieves the binary input stream on line 13?
A. request.getWriter();
B. request.getReader();
C. request.getInputStream();
D. request.getResourceAsStream();
E. request.getResourceAsStream(ServletRequest.REQUEST);
Q9. Click the Exhibit button.
As a maintenance feature, you have created this servlet to allow you to upload and remove files on your web server. Unfortunately, while testing this servlet, you try to upload a file using an HTTP request and   on this servlet, the web container returns a 404 status.
What is wrong with this servlet?

 












A. HTTP does NOT support file upload operations.
B. The servlet constructor must NOT have any parameters.
C. The servlet needs a service method to dispatch the requests to the helper methods.
D. The doPut and doDelete methods do NOT map to the proper HTTP methods.
Q10. Click the Task button.

Place the events in the order they occur.
1st:web container loads the servlet class.
2nd:web container instantiates the servlet
3rd. web container calls the servlets init() method.
4th: web container calls the servlets service() method.’
5th: web container  calls the servlets destroy() methos.
Q11. For an HttpServletResponse response, which two create a custom header?(Choose two.)
A. response.setHeader("X-MyHeader", "34");
B. response.addHeader("X-MyHeader", "34");
C. response.setHeader(new HttpHeader("X-MyHeader", "34"));
D. response.addHeader(new HttpHeader("X-MyHeader", "34"));
E. response.addHeader(new ServletHeader("X-MyHeader", "34"));
F. response.setHeader(new ServletHeader("X-MyHeader", "34"));
Q12 .You need to create a servlet filter that stores all request headers to a
database for all requests to the web application's home page "/index.jsp". Which HttpServletRequest  method allows you to retrieve all of the request headers?
A. String[] getHeaderNames()
B. String[] getRequestHeaders()
C. java.util.Iterator getHeaderNames()
D. java.util.Iterator getRequestHeaders()
E. java.util.Enumeration getHeaderNames()
F. java.util.Enumeration getRequestHeaders()
Q13. Click the Task button.
Given a request from mybox.example.com, with an IP address of 10.0.1.11 on port 33086, place theappropriate ServletRequest methods onto their corresponding return  values.
 


 
 



Q: 14 Your web application requires the ability to load and remove web files
dynamically to the web container's file system. Which two HTTP methods are used to perform these actions? (Choose two.)
A. PUT
B. POST
C. SEND
D. DELETE
E. REMOVE
F. DESTROY
Q15. Which retrieves all cookies sent in a given HttpServletRequest request?
A. request.getCookies()
B. request.getAttributes()
C. request.getSession().getCookies()
D. request.getSession().getAttributes()
 
Q16. Click the Task button.
Given a servlet mapped to /control, place the correct URI segment returned as a String on the corresponding HttpServletRequest method call for the URI: /myapp/control/processorder.
 
Q17. A web browser need NOT always perform a complete request for a
particular page that it suspects might NOT have changed. The HTTP specification provides a mechanism for the browser to retrieve only a partial response from the web server; this response includes information, such as the Last-Modified date but NOT the body of the page. Which HTTP method will the browser use to retrieve such a partial response?
A. GET            B. ASK
C. SEND         D. HEAD
E. TRACE       F. OPTIONS
Q 18. You are creating a servlet that generates stock market graphs. You want to provide the web browser with precise information about the amount of data being sent in the response stream. Which two HttpServletResponse methods will you use to provide this information? (Choose two.)
A. response.setLength(numberOfBytes);
B. response.setContentLength(numberOfBytes);
C. response.setHeader("Length", numberOfBytes);
D. response.setIntHeader("Length", numberOfBytes);
E. response.setHeader("Content-Length", numberOfBytes);
F. response.setIntHeader("Content-Length", numberOfBytes);
Q19. Which two prevent a servlet from handling requests? (Choose two.)
A. The servlet's init method returns a non-zero status.
B. The servlet's init method throws a ServletException.
C. The servlet's init method sets the ServletResponse's content length to 0.
D. The servlet's init method sets the ServletResponse's content type to null.
E. The servlet's init method does NOT return within a time period defined by the servlet container.
  
Q20 . Which of the following HTTP methods is used to remove an article from a virtual shopping  cart in a Web application?  [Select one correct answer ]
 A.  GET          B. HEAD       C.   TRACE      D.  POST    E.   CONNECT          F. PUT 
Q21 Consider the following code segment:
<HTML>
<BODY>
<FORM       ACTION=’/ servlet/postQuery’ >
<p>Enter  the file name  you want to post</p>
<INPUT  TYPE=`text’  name=’ resourceName’  size=’22 ‘   >
<input type =’submit’ >  </ p>
</FORM>
</ BODY>
</ HTML
Which request method will be invoked?    [Select one correct answer]     
A. PUT  B.  HEAD   C. POST D.  TRACE          E.  GET
Q22  Which of the following statements are true?  [ Select all correct answer] 
A GET request is supposed to change the state of the server.
A POST request can be bookmarked
POST is the default HTTP method
 A GET request can handle limited data size.
 Request parameters submitted via a GET request get appended to the URL
Q23  Which character is used to separate the URI and query string in a GET request?
[ select one  Answer]
A. &       B.   ?   C. +             D.  = 
Q24. Consider the following code fragment taken from an HTML page:
      < FORM ACTION=
http://www.sunjavasnips.blogspot.com/servlet/Post FromDataServlet”>
Which method do you need to override of the HttpServlet class inside the   PostFormDataServlets class?
void doPost(HttpServletRequest req, HttpServletResponse rest)
void doPost(ServletRequest req, ServletResponse rest)
void doGet(HttpServletsRequest req, HttpServletsResponse rest)
void doPut(HttpServletsRequest req, HttpServletResponse rest)
void doConnect (ServletsRequest req, ServletResponse rest)
Q26.    Which statements about the servlet lifecycle methods are true?
        [Select all correct answers]
The init( ) method is called for every client request
Since GET is the default HTTP method, HttpServlets.doGet( )method is calld even for other request types like POST, OPTIONS etc. 
The HttpServlets.doConnect( ) is empty implementation method.
The destroy( ) method is guaranteed to be called only after any request processing.
The service( )-doGet( )/( )do post( ) sequence is called for each request
Q27.      Which of the following Servlet API interfaces provide utility methods for sending text
 Or a binary stream to a client?                    [Select one correct answer] 
      A. ServletContext   B.SevletRequest
      C.HttpServletRequest                     D.ServletResponse
      E.servlet       
   
   
Q28.         Consider the following URL:       
     
http://www.sunjavasnips.blogspot.com/servlet/UserInputServlet?name=kuna
Which method gets the value of  name request parameter?  [ Select all correct answers]
ServletRequest.getParameter(“name”);
ServletRequest.getInitParameter(“kunal”);
ServletsRequest.getParameterNames( )
ServletRequest.getInitParameterNames( )
ServletConfig.getInitParameter(“name”);
Q29. Which of the following methods would you use to retrieve request headers?         [ Select all correct answer]
ServletRequest.getHeader(String HeaderName)      B.  HttpServeletsRequest.getHeader(String headerName)
ServletRequest.getParameterNames( )
HttpServletReequest.getHeaderValues(string headerName)
HttpServletReequest.getIntHeader(string headerName)
Q30.     Assume that you want to send a video file to users over the Web. Which class/interface
And method combination would you use to send the video?   [Select one correct answer]
A. HttpServletResponse.getVideoStream( )
B. HttpServletResponse.getWriter( )
C. ServletRequest.getBinaryStream( )
      D.HttpServletRequest.getOutputStream( )
      E.ServeletResponse.getOutputStream( )
        
Q31.   Consider the following code fragment taken from a servlet:
Public void doGet(httpServletRequest request, HttpServletResponse response)
      throws ServletExceptions, IOException {
Response. setContentType(“text/html”);
PrintWriter out= response.getWriter( );
out.println<B> McGraw-Hill Education eBookshop</B>”);
out.fluesh( );
  Response. sendRedirect (request.getQueryString( ));
   }
What will be the result of compiling and running above code snippet?
 [Select one correct answer]
It’ll  fail to compile because there’s no sendRedirect( ) method in
HttpServletResponse.
B. Compilation error because HttpServletResponse.sendRdirect( ) method accepts a  URL.
An IllegalStateException will be thrown at runtime.
No compilation error and successful output of  “McGraw-Hill Education
eBookshop” in the browser window.
E.   No compilation error, but the browser will render a blank window.
Q32.  Which of the following servlet lifecycle method is guaranteed to run before a servlet
can process any request?               [Select one correct answer]
A. doGet( )          B. service( )            C. init()        D. detroy( )     E.doPut( )
Q33.   Assume that you have a servlet class that extends javax.servlet.http.HttpServlet class   
  which of the following methods you should override to process only the POST request?
[Select one correct answer]
 
A. doGet( )         B. service( )            C. doPut( )          D. doPost( )        E. Both B and D
Q34.  How would servlet code from a service method (e.g., dopost ( )) retrieve the value of the   “User-Agent” header from request? (Choose all that apply.)
   
A. String userAgent = request.getparameter(“User-Agent”)
B. String userAgent = request.getHeader(“User-Agent”)
C. String userAgent = request.getRequestHeader(“Mozilla”)
D. String userAgent = getServletcontext( ).getInitparameter(“User-Agent”);  
Option B show the correct method call passing in the header name as a String  parameter
Q35. Which HTTP methods are used to show the client what the server is receiving?  
  [Choose all that apply.] 
A. GET   B. PUT      C. TRACE           D. RETURN      E. OPTIONS
This method is typically used for troubleshooting, not for production
     
Q36.Which method of HttpServletResponse is used to redirect an HTTP request to another URL?    
  
A. sendURL ( )             B. redirectURL ( )             C. redirectHttp ( )   
 D. sendRedirect ( )  E. getRequestDispatcher ( )   
  Option D is correct and of the methods listed, it’s the only one that exists in
HttpServletResponse
 Q37. Which HTTP methods are NOT considered idempotent? [Choose all that apply]   
 A. GET            B. POST          C. HEAD     D. PUT  
By design POST is meant to convey request to update the state of the server. In general same update should not be applied multiple times.
Q38 Given req is a HttpServletRequest, which gets a binary input stream?  [Choose all that apply]          
A. BinaryInputStream S = req.getInputStream ( );     B. ServletInputStream S = req.getInputStream ( );
 C. BinaryInputStream S = req.getBinaryStream ( );    D. ServletInputStream S = req.getBinaryStream ( );
Option B specifies the correct method and the correct return type
     
Q39.  How would you set a header named “CONTENT-LENGTH” in the HttpServletResponse object?  
[Choose all that apply]         
A.response.SetHeader(CONTENT-LENGTH, “1024”);        B. response.Set Header(“CONTENT-LENGTH”, “1024”);   
  C. response.setStatus(1024); D. response.setHeader(“CONTENT-LENGTH”, “1024”);
Option B shows the correct way to set an HTTP header with two String parameters one representing the header name and other the value.
Q40. Choose the servlet code fragment that gets a binary stream for writing an image or other binary type to the HttpServletResponse.
      A. java.io.printWriter out = response.getWriter( );  B. ServletOutputStream out = response.getOutputStream( );
C. java.io.PrintWriter out = new PrintWriter(response.getWriter ( ));   

D. ServletOutputStream out = response.getBinaryStream( );    
Option a is incorrect because it uses a character orented PrintWriter
Q41.Which methods are used by a servlet to handle from data form a client?
  [Choose all that apply]
A. HttpServlet.doHead( )    B. HttpServlet.doPost( )
C. HttpServlet.doForm( )      D. ServletRequest.doGet( )
E. ServletRequest.doPost( )     F. ServletRequest.doForm( ) 
Q42.   Which of the following methods are declared in HttpServletRequest as
  opposed ServletRequest?           [Choose all that apply.]         

   A. getMethod( )   B. getHeader( ) C. getCookies( )    D. getInputStream( )  E. getParameterNames( )
  Options A,B and C all relate to components of an HTTP request.   
Q43.    How should servlet developers handle the HttpServlet’s service ( ) method when extending HttpServlet?
[Choose all that apply]
A. They should override the service( ) method in most cases.
B. They should call the service( ) method from doGet( ) or doPost( )
C. They should call the service( ) method from the init ( ) method.
  D. They should override at least one doXxx( ) method (such as doPost ( ) )    
Option D is correct developers typically focus on the doGet ( ), and doPost( ) methods
Answers::
Q1. Answer: A
Q2. Answer: A, B
Q3. Answer: A, B
Q4. Answer: F
Q5. Answer: A
Q6. Answer: B, F
Q7 Answer: D
Q8. Answer: C
Q9. Answer: B
Q10. Answer:
1st:web container loads the servlet class.
2nd:web container instantiates the servlet
3rd. web container calls the servlets init() method.
4th: web container calls the servlets service() method.’
5th: web container  calls the servlets destroy() methos.
Q11.  Answer: A, B
Q12.  Answer: E
Q13.  Answers:
   nbsp;    Mybox.example.com : getRemoteHost
   nbsp;    10.0.1.11      :  getRemoteAddr
Q14.  Answer: A, D
Q15.
Q16. Answers:
getServletPath()------à /control
getPathInfo() --------à /processorder
getContext() --------à /myapp
Q17. Answer: D
Q18. Answer: B, F
Q19.
Answer: B, E
Q20.Ans: D
Q21.Ans: E
Q22.Ans: D and E
Q23. Ans: A
Q24. Ans: C
Q25.
Q26. Ans: 5
Q27 Ans: D
Q28. Ans: A
Q29. Ans: B and E
Q30. Ans: E
Q31. Ans: C
Q32.
Ans: C
 Q33.Ans: D
Q34.Ans:B
Option B show the correct method call passing in the header name as a String  parameter
      Q35. Ans:C
   This method is typically used for troubleshooting, not for production    
Q36. Ans: D
  Option D is correct and of the methods listed, it’s the only one that exists in
    HttpServletResponse       
Q37. Ans: B  
         By design POST is meant to convey request to update the state of the server. In general same update should not be applied multiple times.
Q38. Ans: B
        Option B specifies the correct method and the correct return type
Q39. Ans:B
Option B shows the correct way to set an HTTP header with two String parameters one representing the header name and other the value.
     Q40. Ans:B
          Option a is incorrect because it uses a character orented PrintWriter
Q41. Ans: B   Options C-F are wrong because these methods don’t exist
Q42. Ans:  A,B,C
         Options A,B and C all relate to components of an HTTP request.   
Q43. Ans: D
Option D is correct developers typically focus on the doGet ( ), and doPost( ) methods


LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt