SlideShare a Scribd company logo
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);
}

More Related Content

What's hot (20)

PDF
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PDF
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
PPT
Struts Introduction Course
guest764934
 
PDF
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 
PPT
Struts course material
Vibrant Technologies & Computers
 
PDF
Servlets lecture1
Tata Consultancy Services
 
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
PPT
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
PDF
Overview of JEE Technology
People Strategists
 
PDF
Lecture 3: Servlets - Session Management
Fahad Golra
 
PPT
Spring MVC Basics
Bozhidar Bozhanov
 
PDF
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
PDF
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
PDF
JSP Technology I
People Strategists
 
PPT
Spring 3.x - Spring MVC
Guy Nir
 
PDF
Spring Framework - III
People Strategists
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
PDF
Spring Framework-II
People Strategists
 
PDF
JSP Technology II
People Strategists
 
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
Struts Introduction Course
guest764934
 
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 
Struts course material
Vibrant Technologies & Computers
 
Servlets lecture1
Tata Consultancy Services
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Overview of JEE Technology
People Strategists
 
Lecture 3: Servlets - Session Management
Fahad Golra
 
Spring MVC Basics
Bozhidar Bozhanov
 
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
JSP Technology I
People Strategists
 
Spring 3.x - Spring MVC
Guy Nir
 
Spring Framework - III
People Strategists
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring Framework-II
People Strategists
 
JSP Technology II
People Strategists
 

Viewers also liked (12)

PPTX
HP Software Testing project (Advanced)
Lokesh Singrol
 
PPTX
Testing project (basic)
Lokesh Singrol
 
PDF
What Makes Great Infographics
SlideShare
 
PDF
Masters of SlideShare
Kapost
 
PDF
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
Empowered Presentations
 
PDF
You Suck At PowerPoint!
Jesse Desjardins - @jessedee
 
PDF
10 Ways to Win at SlideShare SEO & Presentation Optimization
Oneupweb
 
PDF
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
Content Marketing Institute
 
PDF
2015 Upload Campaigns Calendar - SlideShare
SlideShare
 
PPTX
What to Upload to SlideShare
SlideShare
 
PDF
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
PDF
Getting Started With SlideShare
SlideShare
 
HP Software Testing project (Advanced)
Lokesh Singrol
 
Testing project (basic)
Lokesh Singrol
 
What Makes Great Infographics
SlideShare
 
Masters of SlideShare
Kapost
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
Empowered Presentations
 
You Suck At PowerPoint!
Jesse Desjardins - @jessedee
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
Oneupweb
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
Content Marketing Institute
 
2015 Upload Campaigns Calendar - SlideShare
SlideShare
 
What to Upload to SlideShare
SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Getting Started With SlideShare
SlideShare
 
Ad

Similar to TY.BSc.IT Java QB U3 (20)

PDF
SERVER SIDE PROGRAMMING
Prabu U
 
PPTX
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
PPTX
UNIT-3 Servlet
ssbd6985
 
PPTX
Java servlets
yuvarani p
 
PPTX
java Servlet technology
Tanmoy Barman
 
DOCX
Servlet
Dhara Joshi
 
PPTX
Java Servlet
Yoga Raja
 
PPTX
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
PPT
Servlet 01
Bharat777
 
PPTX
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
PPTX
J servlets
reddivarihareesh
 
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
PPTX
Java servlets
VijayapriyaPandi
 
PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPTX
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
PPT
Lecture 2
Ahmed Madkor
 
PPTX
Servlets
Akshay Ballarpure
 
PPTX
Javax.servlet,http packages
vamsi krishna
 
SERVER SIDE PROGRAMMING
Prabu U
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
UNIT-3 Servlet
ssbd6985
 
Java servlets
yuvarani p
 
java Servlet technology
Tanmoy Barman
 
Servlet
Dhara Joshi
 
Java Servlet
Yoga Raja
 
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
Servlet 01
Bharat777
 
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
J servlets
reddivarihareesh
 
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Java servlets
VijayapriyaPandi
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
Lecture 2
Ahmed Madkor
 
Javax.servlet,http packages
vamsi krishna
 
Ad

More from Lokesh Singrol (13)

PDF
MCLS 45 Lab Manual
Lokesh Singrol
 
PDF
MCSL 036 (Jan 2018)
Lokesh Singrol
 
DOCX
TY.BSc.IT Java QB U2
Lokesh Singrol
 
PDF
Project black book TYIT
Lokesh Singrol
 
PPTX
Computer institute website(TYIT project)
Lokesh Singrol
 
PPT
Internet of Things
Lokesh Singrol
 
PPTX
Top Technology product failure
Lokesh Singrol
 
PPTX
Computer institute Website(TYIT project)
Lokesh Singrol
 
PPTX
Trees and graphs
Lokesh Singrol
 
PPTX
behavioral model (DFD & state diagram)
Lokesh Singrol
 
PPTX
Desktop system,clustered system,Handheld system
Lokesh Singrol
 
PPTX
Raster Scan display
Lokesh Singrol
 
PPT
Flash memory
Lokesh Singrol
 
MCLS 45 Lab Manual
Lokesh Singrol
 
MCSL 036 (Jan 2018)
Lokesh Singrol
 
TY.BSc.IT Java QB U2
Lokesh Singrol
 
Project black book TYIT
Lokesh Singrol
 
Computer institute website(TYIT project)
Lokesh Singrol
 
Internet of Things
Lokesh Singrol
 
Top Technology product failure
Lokesh Singrol
 
Computer institute Website(TYIT project)
Lokesh Singrol
 
Trees and graphs
Lokesh Singrol
 
behavioral model (DFD & state diagram)
Lokesh Singrol
 
Desktop system,clustered system,Handheld system
Lokesh Singrol
 
Raster Scan display
Lokesh Singrol
 
Flash memory
Lokesh Singrol
 

Recently uploaded (20)

PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
epi editorial commitee meeting presentation
MIPLM
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
infertility, types,causes, impact, and management
Ritu480198
 

TY.BSc.IT Java QB U3

  • 1. 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... }
  • 2. 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
  • 3. 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
  • 4. (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.*;
  • 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 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>
  • 8. 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); }