QUESTION BANK UNIT –III Q.1 What are servlets?Whatare the advantages of usingservlets? Ans: Java Servletsare programsthatrun on a Web or Application serverand act asa middle layer between a requestcoming froma Web browserorother HTTP client and databasesorapplicationson theHTTP server.  Servlets providea way to generatedynamicdocumentsthatisboth easier to write and fasterto run.  Provideall thepowerfullfeaturesof JAVA,such asException handling and garbagecollection.  Servlet enableseasy portability acrossWeb Servers.  Servlet can communicatewith differentservlet and servers.  Since all web applicationsarestatelessprotocol,servlet usesits own APIto maintain session Q.2 Explainthe lifecycle of servlet. Ans: A servletlifecycle canbe definedasthe entire processfromitscreationtill the destruction.The following are the pathsfollowedbyaservlet  The servletisinitializedbycallingthe init() method. The initmethodisdesignedtobe calledonlyonce.Itiscalledwhenthe servletisfirstcreated,andnot calledagainforeach userrequest. publicvoidinit() throwsServletException { // Initializationcode... }  The servletcalls service() methodtoprocessaclient'srequest. The service() methodisthe mainmethodtoperformthe actual task.The servletcontainer(i.e.webserver) callsthe service() methodtohandle requestscomingfromthe client( browsers)andtowrite the formatted response backto the client. publicvoidservice(ServletRequestrequest,ServletResponseresponse) throwsServletException,IOException { // code... }  The servletisterminatedbycallingthe destroy() method. The destroy() methodiscalledonlyonce atthe endof the life cycle of a servlet.Thismethodgivesyour servletachance toclose database connections,haltbackgroundthreads,writecookie listsorhitcountsto disk,andperformothersuch cleanupactivities. publicvoiddestroy(){ // Finalizationcode... }
Q.3 Write a servletprogram to display the simple sentence Welcome alongwiththe name enteredby the user through an HTML form. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter yourName:<inputtype=textname=t1> <inputtype=submitvalue=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); Stringa=req.getParameter(“t1”) out.println("<h1>Welcome “+ a + "</h1>"); } } Q.4 Explainthe followingelementsofthe web.xml file ofservlet 1. <servlet> 2. <servlet-mapping> 3. <session-config> 4. <welcome-file-list> 5. <web-app> Ans: 1. <servlet>: The servletelementcontainsthedeclarativedata of a servlet. 2. <servlet-mapping>: The servlet-mapping elementdefinesa mapping between a servlet and a URL pattern. 3. <session-config>: The session-config elementdefinesthesession attributesforthisWeb application. 4. <welcome-file-list>: The welcome-file-listelementof web-app,isused to definea list of welcome files. Itssub
element iswelcome-filethatis used to definethe welcomefile. 5. <web-app>: The XML Schema forthe Servlet2.4 deploymentdescriptor.WebLogicServerfully supports HTTP servlets as defined in theServlet2.4 specification fromSun Microsystems.However, theversion attributed mustbesetto 2.4 in orderto enforce2.4 behavior. Q.5 What is CGI?Whatare the disadvantagesof CGI? Ans:  The Common Gateway Interface(CGI) isan interfaceto the Web serverthatenablesyou to extend theserver's functionality.  Using CGI,you can interact with users who accessyoursite.  CGI enablesyou to extend thecapability of yourserverto parse (interpret) inputfromthe browserand return information based on userinput.  CGI is an interfacethatenablesthe programmerto write programsthatcan easily communicatewiththe server. Disadvantages: 1. Responsetime is high,the creation of an Shell is an heavy weightactivity 2. CGI is not scalable 3. Notalwayssecureor object-oriented 4. No separation of presentation and businesslogic 5. Scripting languagesareoften platform-dependent Q.6 Explainwith suitable diagram request/response paradigmof servlet Ans: In theHTTP based request-responseparadigm,a clientuser agent(a web browseror any such application thatcan makeHTTP requestsand receive HTTP responses) establishesa connection with a web server and sendsa requestto theserver. If the web server hasa mapping to a servlet forthe specified URL in the request,theweb server delegates the requestto thespecified servlet.The servlet in turn processestherequestand generatesa HTTP response. HTTP Request: The interface HttpServletRequestisthe first abstraction provided by theservletAPI.When a requestis received by the servlet engine,an objectof this typeis constructed and passed on to a servlet. This objectprovidesmethodsforaccessing parameternamesand valuesof therequest & otherattributes of the request. HTTP Response: The HttpServletResponseinterfaceof theservletAPI providesan encapsulation of theHTTP responsegenerated by a servlet. This interfacedefinesan objectcreated by the servlet enginethat lets a servlet generatecontentin responseto a user agent'srequest. ApplicationLogicandContent Generation: The HttpServletinterfacespecifies methodsforimplementing the application logic and generating contentin responseto a HTTP request. Q.7. Explainthe followingmethodof servletinterface 1.init 2.destroy 3.service 4.getServletConfig 5.getServletInfo Ans: These are 5 methodsin Servlet interface. Servletinterfaceneeds to be implemented forcreating any servlet
(either directly or indirectly).It provides3 life cycle methodsthatare used to initialize the servlet, to service the requests,and to destroy theservlet and 2 non-lifecycle methods. 1. Init() : The init method isdesigned to be called only once.It is called when the servlet is first created,and not called again foreach user request. public void init() throwsServletException { // Initialization code... } 2. Destroy(): The destroy() method iscalled only onceat the end of the life cycle of a servlet.This method givesyour servlet a chanceto close databaseconnections,haltbackground threads,writecookielists or hit countsto disk,and performothersuch cleanup activities. public void destroy() { // Finalization code... } 3. Service(): The service() method is the main method to performthe actualtask.The servlet container(i.e.web server) calls the service() method to handlerequestscoming fromthe client( browsers) and to write theformatted responseback to the client. public void service(ServletRequestrequest,ServletResponseresponse) throwsServletException,IOException { // code... } 4. getServletConfig(): An objectof ServletConfig iscreated by the web containerforeach servlet.This objectcan be used to get configuration information fromweb.xmlfile.getServletConfig() method of Servletinterfacereturnsthe objectof ServletConfig. ServletConfig config=getServletConfig(); 5. getServletInfo(): Returnsinformation abouttheservlet,such asauthor,version,and copyright. The string that this method returnsshould beplain text and notmarkup of any kind (such asHTML, XML, etc.). public java.lang.String getServletInfo() Q.8. Write a simple servletprogram that will displaythe factorial of a givennumber Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter anyNumber:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*;
PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); int a=Integer.parseInt(req.getParameter(“t1”)); Int fac=1; for(inti=1;i<n;i++) { fac=fac*i); } out.println("<h1>Result“+ fac + "</h1>"); } } } Q.9 What is the purpose ofHttpServletRequestinterface ofservletAPI? Explainwith suitable example Ans:  publicinterface HttpServletRequestextends ServletRequest  Extendsthe ServletRequestinterface toproviderequestinformationforHTTPservlets.  The servletcontainercreatesan HttpServletRequestobjectandpassesitasan argumentto the servlet'sservice methods(doGet, doPost,etc). import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } } Q.10 Write a servletprogram that will read a string from user. If the string is “Examination” thengreetthe user otherwise displayerror message. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter anyString:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE:
Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); Stringa=req.getParameter(“t1”); If(a==”Examination”) { out.println("<h1>Welcome “+ a + "</h1>"); } else { out.println("<h1>ERROR </h1>"); } } } Q.11 Explainthe reason why servletis preferredoverCGI Ans:  Requestis run in a separatethread,so fasterthan CGIs  Scalable,can servemany morerequests,  Robustand ObjectOriented.  Can be written in Java Programming language.  Platformindependent.  Accessto Logging Capabilities.  Error handling and Security. Q.12 Write a servletthat prints the sum of square of n integernumbers. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter any Number:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); int a=Integer.parseInt(req.getParameter(“t1”)); Int res=0; for(inti=0;i<n;i++) { res=res+(i*i); } out.println("<h1>Result“+ res + "</h1>"); } } }
Q.13 Explainthe methodthat RequestDispatcherinterface doesconsistof with the relevantcode specification Ans: The RequestDispacherinterfaceprovidesthefacility of dispatching therequestto anotherresourceit may be html,servlet or jsp. METHODS:  publicvoidforward(ServletRequestrequest,ServletResponse response)throws ServletException,java.io.IOException: Forwardsa request froma servlet to anotherresource (servlet,JSPfile, or HTML file) on the server.  publicvoidinclude(ServletRequestrequest,ServletResponseresponse)throws ServletException,java.io.IOException: Includesthecontentof a resource(servlet,JSPpage,or HTML file) in theresponse. Code Specification : INDEX .HTML <formaction="servlet1" method="post"> Name:<inputtype="text"name="userName"/><br/> Password:<input type="password"name="userPass"/><br/> <input type="submit"value="login"/> </form>
LOGIN . JAVA publicvoiddoPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcherrd=request.getRequestDispatcher("WelcomeServlet"); rd.forward(request, response); } else{ out.print("Sorry UserNameorPassword Error!"); RequestDispatcherrd=request.getRequestDispatcher("/index.html"); rd.include(request,response); } } WELCOMESERVLET . JAVA publicvoiddoPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome"+n); }

TY.BSc.IT Java QB U3

  • 1.
    QUESTION BANK UNIT –III Q.1What are servlets?Whatare the advantages of usingservlets? Ans: Java Servletsare programsthatrun on a Web or Application serverand act asa middle layer between a requestcoming froma Web browserorother HTTP client and databasesorapplicationson theHTTP server.  Servlets providea way to generatedynamicdocumentsthatisboth easier to write and fasterto run.  Provideall thepowerfullfeaturesof JAVA,such asException handling and garbagecollection.  Servlet enableseasy portability acrossWeb Servers.  Servlet can communicatewith differentservlet and servers.  Since all web applicationsarestatelessprotocol,servlet usesits own APIto maintain session Q.2 Explainthe lifecycle of servlet. Ans: A servletlifecycle canbe definedasthe entire processfromitscreationtill the destruction.The following are the pathsfollowedbyaservlet  The servletisinitializedbycallingthe init() method. The initmethodisdesignedtobe calledonlyonce.Itiscalledwhenthe servletisfirstcreated,andnot calledagainforeach userrequest. publicvoidinit() throwsServletException { // Initializationcode... }  The servletcalls service() methodtoprocessaclient'srequest. The service() methodisthe mainmethodtoperformthe actual task.The servletcontainer(i.e.webserver) callsthe service() methodtohandle requestscomingfromthe client( browsers)andtowrite the formatted response backto the client. publicvoidservice(ServletRequestrequest,ServletResponseresponse) throwsServletException,IOException { // code... }  The servletisterminatedbycallingthe destroy() method. The destroy() methodiscalledonlyonce atthe endof the life cycle of a servlet.Thismethodgivesyour servletachance toclose database connections,haltbackgroundthreads,writecookie listsorhitcountsto disk,andperformothersuch cleanupactivities. publicvoiddestroy(){ // Finalizationcode... }
  • 2.
    Q.3 Write aservletprogram to display the simple sentence Welcome alongwiththe name enteredby the user through an HTML form. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter yourName:<inputtype=textname=t1> <inputtype=submitvalue=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); Stringa=req.getParameter(“t1”) out.println("<h1>Welcome “+ a + "</h1>"); } } Q.4 Explainthe followingelementsofthe web.xml file ofservlet 1. <servlet> 2. <servlet-mapping> 3. <session-config> 4. <welcome-file-list> 5. <web-app> Ans: 1. <servlet>: The servletelementcontainsthedeclarativedata of a servlet. 2. <servlet-mapping>: The servlet-mapping elementdefinesa mapping between a servlet and a URL pattern. 3. <session-config>: The session-config elementdefinesthesession attributesforthisWeb application. 4. <welcome-file-list>: The welcome-file-listelementof web-app,isused to definea list of welcome files. Itssub
  • 3.
    element iswelcome-filethatis usedto definethe welcomefile. 5. <web-app>: The XML Schema forthe Servlet2.4 deploymentdescriptor.WebLogicServerfully supports HTTP servlets as defined in theServlet2.4 specification fromSun Microsystems.However, theversion attributed mustbesetto 2.4 in orderto enforce2.4 behavior. Q.5 What is CGI?Whatare the disadvantagesof CGI? Ans:  The Common Gateway Interface(CGI) isan interfaceto the Web serverthatenablesyou to extend theserver's functionality.  Using CGI,you can interact with users who accessyoursite.  CGI enablesyou to extend thecapability of yourserverto parse (interpret) inputfromthe browserand return information based on userinput.  CGI is an interfacethatenablesthe programmerto write programsthatcan easily communicatewiththe server. Disadvantages: 1. Responsetime is high,the creation of an Shell is an heavy weightactivity 2. CGI is not scalable 3. Notalwayssecureor object-oriented 4. No separation of presentation and businesslogic 5. Scripting languagesareoften platform-dependent Q.6 Explainwith suitable diagram request/response paradigmof servlet Ans: In theHTTP based request-responseparadigm,a clientuser agent(a web browseror any such application thatcan makeHTTP requestsand receive HTTP responses) establishesa connection with a web server and sendsa requestto theserver. If the web server hasa mapping to a servlet forthe specified URL in the request,theweb server delegates the requestto thespecified servlet.The servlet in turn processestherequestand generatesa HTTP response. HTTP Request: The interface HttpServletRequestisthe first abstraction provided by theservletAPI.When a requestis received by the servlet engine,an objectof this typeis constructed and passed on to a servlet. This objectprovidesmethodsforaccessing parameternamesand valuesof therequest & otherattributes of the request. HTTP Response: The HttpServletResponseinterfaceof theservletAPI providesan encapsulation of theHTTP responsegenerated by a servlet. This interfacedefinesan objectcreated by the servlet enginethat lets a servlet generatecontentin responseto a user agent'srequest. ApplicationLogicandContent Generation: The HttpServletinterfacespecifies methodsforimplementing the application logic and generating contentin responseto a HTTP request. Q.7. Explainthe followingmethodof servletinterface 1.init 2.destroy 3.service 4.getServletConfig 5.getServletInfo Ans: These are 5 methodsin Servlet interface. Servletinterfaceneeds to be implemented forcreating any servlet
  • 4.
    (either directly orindirectly).It provides3 life cycle methodsthatare used to initialize the servlet, to service the requests,and to destroy theservlet and 2 non-lifecycle methods. 1. Init() : The init method isdesigned to be called only once.It is called when the servlet is first created,and not called again foreach user request. public void init() throwsServletException { // Initialization code... } 2. Destroy(): The destroy() method iscalled only onceat the end of the life cycle of a servlet.This method givesyour servlet a chanceto close databaseconnections,haltbackground threads,writecookielists or hit countsto disk,and performothersuch cleanup activities. public void destroy() { // Finalization code... } 3. Service(): The service() method is the main method to performthe actualtask.The servlet container(i.e.web server) calls the service() method to handlerequestscoming fromthe client( browsers) and to write theformatted responseback to the client. public void service(ServletRequestrequest,ServletResponseresponse) throwsServletException,IOException { // code... } 4. getServletConfig(): An objectof ServletConfig iscreated by the web containerforeach servlet.This objectcan be used to get configuration information fromweb.xmlfile.getServletConfig() method of Servletinterfacereturnsthe objectof ServletConfig. ServletConfig config=getServletConfig(); 5. getServletInfo(): Returnsinformation abouttheservlet,such asauthor,version,and copyright. The string that this method returnsshould beplain text and notmarkup of any kind (such asHTML, XML, etc.). public java.lang.String getServletInfo() Q.8. Write a simple servletprogram that will displaythe factorial of a givennumber Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter anyNumber:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*;
  • 5.
    PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout=res.getWriter(); int a=Integer.parseInt(req.getParameter(“t1”)); Int fac=1; for(inti=1;i<n;i++) { fac=fac*i); } out.println("<h1>Result“+ fac + "</h1>"); } } } Q.9 What is the purpose ofHttpServletRequestinterface ofservletAPI? Explainwith suitable example Ans:  publicinterface HttpServletRequestextends ServletRequest  Extendsthe ServletRequestinterface toproviderequestinformationforHTTPservlets.  The servletcontainercreatesan HttpServletRequestobjectandpassesitasan argumentto the servlet'sservice methods(doGet, doPost,etc). import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } } Q.10 Write a servletprogram that will read a string from user. If the string is “Examination” thengreetthe user otherwise displayerror message. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter anyString:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE:
  • 6.
    Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout=res.getWriter(); Stringa=req.getParameter(“t1”); If(a==”Examination”) { out.println("<h1>Welcome “+ a + "</h1>"); } else { out.println("<h1>ERROR </h1>"); } } } Q.11 Explainthe reason why servletis preferredoverCGI Ans:  Requestis run in a separatethread,so fasterthan CGIs  Scalable,can servemany morerequests,  Robustand ObjectOriented.  Can be written in Java Programming language.  Platformindependent.  Accessto Logging Capabilities.  Error handling and Security. Q.12 Write a servletthat prints the sum of square of n integernumbers. Ans: HTML CODE: <form method=postaction=”DisplayServlet”> <pre> Enter any Number:<inputtype=”text”name=”t1”> <inputtype=”submit”value=”Clickhere”> </pre> </form> SERVLET CODE: Importjavax.servlet.*; Importjavax.servlet.http.* Importjava.io.*; PublicclassDisplayServletextendsHTTPServlet { PublicvoiddoPost(HTTPServletRequest req,HTTPServletResponse res) throwsException{ res.setContentType("text/html"); PrintWriterout= res.getWriter(); int a=Integer.parseInt(req.getParameter(“t1”)); Int res=0; for(inti=0;i<n;i++) { res=res+(i*i); } out.println("<h1>Result“+ res + "</h1>"); } } }
  • 7.
    Q.13 Explainthe methodthatRequestDispatcherinterface doesconsistof with the relevantcode specification Ans: The RequestDispacherinterfaceprovidesthefacility of dispatching therequestto anotherresourceit may be html,servlet or jsp. METHODS:  publicvoidforward(ServletRequestrequest,ServletResponse response)throws ServletException,java.io.IOException: Forwardsa request froma servlet to anotherresource (servlet,JSPfile, or HTML file) on the server.  publicvoidinclude(ServletRequestrequest,ServletResponseresponse)throws ServletException,java.io.IOException: Includesthecontentof a resource(servlet,JSPpage,or HTML file) in theresponse. Code Specification : INDEX .HTML <formaction="servlet1" method="post"> Name:<inputtype="text"name="userName"/><br/> Password:<input type="password"name="userPass"/><br/> <input type="submit"value="login"/> </form>
  • 8.
    LOGIN . JAVA publicvoiddoPost(HttpServletRequestrequest, HttpServletResponseresponse) throwsServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcherrd=request.getRequestDispatcher("WelcomeServlet"); rd.forward(request, response); } else{ out.print("Sorry UserNameorPassword Error!"); RequestDispatcherrd=request.getRequestDispatcher("/index.html"); rd.include(request,response); } } WELCOMESERVLET . JAVA publicvoiddoPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome"+n); }