WEB TECHNOLOGIES Servlet

jegadeesanram5 514 views 29 slides May 05, 2021
Slide 1
Slide 1 of 29
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29

About This Presentation

Servlet
Common Gateway Interface (CGI), Lifecycle of a Servlet, deploying a servlet, The Servlet API, Reading Servlet parameters, Reading Initialization parameters, Handling Http Request & Responses, Using Cookies and Sessions, connecting to a database using JDBC.


Slide Content

WEB TECHNOLOGIES Servlet
Dr R Jegadeesan Prof-CSE
Jyothishmathi Institute of Technology and Science,
karimnagar

Syllabus
UNIT–IIIServlet
CommonGatewayInterface(CGI),
LifecycleofaServlet,deployinga
servlet,TheServletAPI,Reading
Servletparameters,Reading
Initializationparameters,Handling
HttpRequest&Responses,Using
CookiesandSessions,connectingto
adatabaseusingJDBC.
2

UNIT -III : Servlet Programming
Aim&Objective:
➢TointroduceServerSideprogrammingwithJavaServlets.
➢ServletTechnologyisusedtocreatewebapplications.Servlet
technologyusesJavalanguagetocreatewebapplications.
Introduction to Java Servlet
3

UNIT -III : Servlet Programming
Webapplicationsarehelperapplicationsthatresidesatwebserverandbuilddynamicwebpages.
Adynamicpagecouldbeanythinglikeapagethatrandomlychoosespicturetodisplayorevena
pagethatdisplaysthecurrenttime.
Introduction to Servlet
4

UNIT -III : Servlets
BeforeServlets,CGI(Common GatewayInterface)programmingwasusedtocreatewebapplications.
Here'showaCGIprogramworks:UserclicksalinkthathasURLtoadynamicpageinsteadofastatic
page.TheURLdecideswhichCGIprogramtoexecute.
WebServersruntheCGIprograminseparateOSshell.TheshellincludesOSenvironmentandthe
processtoexecutecodeoftheCGIprogram.TheCGIresponseissentbacktotheWebServer,which
wrapstheresponseinanHTTPresponseandsenditbacktothewebbrowser.
CGI (Common Gateway Interface)
5

UNIT -III : Servlet
•Less response time because each request runs in a separate thread.
•Servlets are scalable.
•Servlets are robust and object oriented.
•Servlets are platform independent.
Advantages of Servlet
6

UNIT -III : Servlet
Servlet API consists of two important packages that encapsulates all the important classes and
interface, namely :
javax.servlet
javax.servlet.http
Servlet API
7
INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListenerServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
ServletRequestListene
r

UNIT -III : Servlet
Servlet Interface provides five methods. Out of these five methods, three methods are Servlet life
cyclemethods and rest two are non life cycle methods.
Servlet Interface
8

UNIT -III : Servlet
WebcontainerisresponsibleformanagingexecutionofservletsandJSPpagesforJavaEEapplication.
Whenarequestcomesinforaservlet,theserverhandstherequesttotheWebContainer.WebContaineris
responsibleforinstantiatingtheservletorcreatinganewthreadtohandletherequest.ItsthejobofWeb
Containertogettherequestandresponsetotheservlet.Thecontainercreatesmultiplethreadstoprocess
multiplerequeststoasingleservlet.
Servletsdon'thaveamain()method.WebContainermanagesthelifecycleofaServletinstance.
How a Servlet Application Works
9

UNIT -III : Servlet
Life Cycle of Servlet
10
LoadingServletClass:AServletclassisloadedwhenfirstrequestfortheservletis
receivedbytheWebContainer.
Servletinstancecreation:AftertheServletclassisloaded,WebContainercreatesthe
instanceofit.Servletinstanceiscreatedonlyonceinthelifecycle.
Calltotheinit()method:init()methodiscalledbytheWebContaineronservlet
instancetoinitializetheservlet.

UNIT -II : XML
Signatureofinit()method:
publicvoidinit(ServletConfigconfig)throwsServletException
Calltotheservice()method:Thecontainerscalltheservice()methodeachtimetherequestfor
servletisreceived.Theservice()methodwillthencallthedoGet()ordoPost()methosbasedont
ehtypeoftheHTTPrequest,asexplainedinpreviouslessons.
Signatureofservice()method:
publicvoidservice(ServletRequestrequest,ServletResponseresponse)throwsServletException,
IOException
Calltodestroy()method:TheWebContainercallthedestroy()methodbeforeremovingservlet
instance,givingitachanceforcleanupactivity.
Life cycle of Servlet
11

UNIT -III : Servlet
GenericServlet is an abstract class that provides implementation of most of the basic servlet
methods. This is a very important class.
Methods of GenericServlet class
public void init(ServletConfig)
public abstract void service(ServletRequest request,ServletResposne response)
public void destroy()
public ServletConfig getServletConfig()
public String getServletInfo()
public ServletContext getServletContext()
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public String getServletName()
public void log(String msg)
public void log(String msg, Throwable t)
GenericServlet Class
12

UNIT -III : Servlet
HttpServletisalsoanabstractclass.Thisclassgivesimplementationofvariousservice()methods
ofServletinterface.
Tocreateaservlet,weshouldcreateaclassthatextendsHttpServletabstractclass.TheServlet
classthatwewillcreate,mustnotoverrideservice()method.Ourservletclasswilloverrideonlythe
doGet()and/ordoPost()methods.
Theservice()methodofHttpServletclasslistenstotheHttpmethods(GET,POSTetc)fromrequest
streamandinvokesdoGet()ordoPost()methodsbasedonHttpMethodtype.
HTTP Servlet Class
13

UNIT -III : Servlet
WebcontainerisresponsibleformanagingexecutionofservletsandJSPpagesforJavaEE
application.
Whenarequestcomesinforaservlet,theserverhandstherequesttotheWebContainer.Web
Containerisresponsibleforinstantiatingtheservletorcreatinganewthreadtohandletherequest.
ItsthejobofWebContainertogettherequestandresponsetotheservlet.Thecontainercreates
multiplethreadstoprocessmultiplerequeststoasingleservlet.
Servletsdon'thaveamain()method.WebContainermanagesthelifecycleofaServletinstance.
How a Servlet Application Works
14

UNIT -III : Servlet
ServletscanbeusedforhandlingboththeGETRequestsandthePOSTRequests.TheHttpServlet
classisusedforhandlingHTTPGETRequestsasithassomespecializedmethodsthatcan
efficientlyhandletheHTTPrequests.
Thesemethodsare:
doGet(),
doPost(),
doPut(),
doDelete,etc
Handling HTTP request & Responses
15

UNIT -III : Servlet
<html><body>
<formaction="numServlet">
selecttheNumber:
<selectname="number"size="3">
<optionvalue="one">One</option>
<optionvalue="Two">Two</option>
<optionvalue="Three">Three</option>
</select>
<inputtype="submit">
</body></html>
Handling HTTP request & Responses
16

UNIT -III : Servlet
Handling HTTP request & Responses
17

TheServletRequestclassincludesmethodsthatallowyoutoreadthenamesandvaluesof
parametersthatareincludedinaclientrequest.Wewilldevelopaservletthatillustratestheir
use.Theexamplecontainstwofiles.
A Web page is defined insum.htmland a servlet is defined inAdd.java
<html><body><center>
<form name="Form1" method="post" action="Add">
<table><tr><td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25" value=""></td>
</tr>
<tr><td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25" value=""></td>
</tr></table>
<input type=submit value="Submit“></body></html>
UNIT -III : Servlet
Reading Servlet Parameters

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add
extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Get print writer.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
UNIT -III : Servlet
Handling HTTP request & Responses

while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close(); } }
UNIT -III : Servlet
Handling HTTP request & Responses

•ThesourcecodeforAdd.javacontainsdoPost()methodisoverriddentoprocessclientrequests.
•ThegetParameterNames()methodreturnsanenumerationoftheparameternames.Theseare
processedinaloop.
•We can see that the parameter name and value are output to the client. The parameter value is
obtained via the getParameter( ) method.
URL : http://localhost:8080/servlets/sum.html
UNIT -III : Servlet
Handling HTTP request & Responses

UNIT III: Servlet
Reference
22
BookDetails:
TEXTBOOKS:
1.WebTechnologies,UttamKRoy,OxfordUniversityPress
2.TheCompleteReferencePHP–StevenHolzner,TataMcGraw-Hill
REFERENCEBOOKS:
1.WebProgramming,buildinginternetapplications,ChrisBates2ndedition,WileyDreamtech
2.JavaServerPages–HansBergsten,SPDO’Reilly
3.JavaScript,D.Flanagan,O’Reilly,SPD.
4.BeginningWebProgramming-JonDuckettWROX.
5.ProgrammingWorldWideWeb,R.W.Sebesta,FourthEdition,Pearson.
6.InternetandWorldWideWeb–Howtoprogram,DietelandNieto,Pearson.

UNIT III : Servlet
Video Reference
23
Video Link details (NPTEL, YOUTUBE Lectures and etc.)
➢https://nptel.ac.in/content/storage2/nptel_data3/html/mhrd/ict/text/106106093/lec39.pdf
➢http://www.nptelvideos.in/2012/11/internet-technologies.html
➢https://nptel.ac.in/courses/106105191/

UNIT III : Servlet
Courses
24
courses available on <www.coursera.org>, andhttp://neat.aicte-india.org
https://www.coursera.org/
Course1:WebApplicationsforEverybodySpecialization
Builddynamicdatabase-backedwebsites..UsePHP,MySQL,jQuery,andHandlebarstobuildweb
anddatabaseapplications.
Course2:JavaProgramming:SolvingProblemswithSoftware
LearntoDesignandCreateWebsites.Buildaresponsiveandaccessiblewebportfoliousing
HTML5,JavaServlet,XML,CSS3,andJavaScript

UNIT-III : Servlet Programming
Tutorial Topic
25
Tutorial topic wise
➢www.geeksforgeeks.org › introduction-java-servlets
➢www.edureka.co › blog › java-servlets
➢beginnersbook.com › servlet-tutorial
➢www.tutorialspoint.com › servlets
➢www.javatpoint.com › servlet-tutorial

UNIT-III : Servlet
Multiple Choice Questions
26
Servlet–MCQs
1.WhichofthefollowingcodeisusedtogetanattributeinaHTTPSessionobjectinservlets?
A.session.getAttribute(Stringname) B.session.alterAttribute(Stringname)
C.session.updateAttribute(Stringname) D.session.setAttribute(Stringname)
2.WhichmethodisusedtospecifybeforeanylinesthatusesthePintWriter?
A.setPageType()B.setContextType()
C.setContentType() D.setResponseType()
3.WhatarethefunctionsofServletcontainer?
A.Lifecyclemanagement B.Communicationsupport
C.Multithreadingsupport D.Alloftheabove
4.Whatisbytecode?
A.Machine-specificcode B.Javacode
C.Machine-independentcode D.Noneofthementioned
5.WhichobjectofHttpSessioncanbeusedtoviewandmanipulateinformationabouta
session?
A.sessionidentifier B.creationtime
C.lastaccessedtime D.Allmentionedabove

UNIT-III : Servlet
Servlet-Tutorial Problems
27
Servlet –Tutorial Problems:
1.Write a Servlet program to read employee details
2.Write a Servlet program to uploads files to remote directory

UNIT-III : Servlet
Question Bank
28
PHP –universities & Important Questions:
1.Defineasessiontrackerthattracksthenumberofaccessesandlastaccessdataofa
particularwebpage.
2.WhatisthesecurityissuesrelatedtoServlets.
3.ExplainhowHTTPPOSTrequestisprocessedusingServlets
4.Explainhowcookiesareusedforsessiontracking?
5.ExplainaboutTomcatwebserver.
6.WhatisServlet?ExplainlifecycleofaServlet?
7.WhataretheadvantagesofServletsoverCGI
8.Whatissessiontracking?Explaindifferentmechanismsofsessiontracking?
9.WhatisthedifferencebetweenServletsandapplets?
10.WhatisthedifferencebetweendoGet()anddoPost()?

Thank you
29