1.
Introduction
ServletisaJavaprogramminglanguageclass,partofJavaEnterpriseEdition(JavaEE).SunMicrosystemsdevelopeditsfirstversion1.0
intheyear1997.ItscurrentVersionisServlet3.1.
[Link]
integratedwithaServletcontainer.
1.1ServletProcess
Theprocessofaservletisshownbelow:
Figure1:servletprocessingofuserrequests
[Link].
TheWebserversearchesfortheservletandinitiatesit.
Theclientrequestisprocessedbytheservletanditsendstheresponsebacktotheserver.
TheServerresponseisthenforwardedtotheclient.
1.2Merits
Servletsareplatformindependentastheycanrunonanyplatform.
TheServletAPIinheritsallthefeaturesoftheJavaplatform.
Itbuildsandmodifiesthesecuritylogicforserversideextensions.
ServletsinheritthesecurityprovidedbytheWebServer.
InServlet,[Link],itsavesthememory
byremovingtheoverheadofcreatinganewprocessforeachrequest.
[Link]
Servletlifecycledescribeshowtheservletcontainermanagestheservletobject.
LoadServletClass
ServletInstanceiscreatedbythewebcontainerwhentheservletclassisloaded
init() :[Link].
1 publicvoidinit()throwsServletException
{
2
3 }
service() :[Link]
webcontainercallsthismethodeachtimewhenrequestfortheservletisreceived.
Itcalls doGet() , doPost() , doTrace() , doPut() , doDelete() andothermethods
doGet() :
1 publicvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
2 throwsServletException,IOException{
3 //code
4 }
doPost() :
1 publicvoiddoPost(HttpServletRequest
request,HttpServletResponseresponse)
2 throwsServletException,IOException{
3 //code
4 }
destroy() :Itisusedtocleanresourcesandcalledbeforeremovingtheservletinstance.
1 publicvoiddestroy()
Figure2:ServletLifeCycle
[Link]
ItisknownasservletenginewhichmanagesJavaServletcomponentsontopofawebservertotherequestsendbytheclient.
3.1Services
ServletContainerprovidesthefollowingservices:
Itmanagestheservletlifecycle.
Theresourceslikeservlets,JSPpagesandHTMLfilesaremanagedbyservletcontainer.
ItappendssessionIDtotheURLpathtomaintainsession.
Providessecurityservice.
Itloadsaservletclassfromnetworkservices,filesystemslikeremotefilesystemandlocalfilesystem.
3.2ServletContainerConfigurations
Theservletcontainercanbeconfiguredwiththewebservertomanageservletsinthreewayslistedbelow:
Standalonecontainer
Inprocesscontainer
Outprocesscontainer
Standalonecontainer:[Link],thecontainerisstrongly
coupledwiththeWebserver.
InProcesscontainer:InthisthecontainerrunswithintheWebserverprocess.
OutProcesscontainer:[Link]
usedinsomecaseslikeifthereisaneedtorunServletsandServletcontainerindifferentprocess/systems.
[Link]:Tostartwith
[Link].
Step1:OpenNetBeansIDE>File>NewProject>WebApplication>SetProjectnameasWebApplicationServletDemo
Figure3:CreatenewWebApplicationprojectinNetBeansIDE:WebApplicationServletDemo
Step2:NowclickonNext>[Link].
Figure4:ProjectDirectory
aftercreatingnewproject
Step3:CreatenewservletapplicationbyRightClickingonProjectDirectory>New>Servlet
Figure5:AddingServletfile
Step4:AddtheServletClassNameasServletDemoandclickonNext.
Figure6:AddingServletClassName
Step5:Now,ConfigureServletDeploymentbycheckingAddinformationtodeploymentdescriptor([Link])andaddingURLPattern
(thelinkvisible)[Link].
Figure7:ConfiguringServletDeployment
Step6:ClickonFinishasshownabove,[Link]
DirectoryStructure:
Figure8:Changesunderproject
directoryafterconfiguring
Hereisthecodefordeploymentdescriptor([Link])withURLpatteras/ServletDemo:
Listing1:[Link]
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="[Link]
instance"xsi:schemaLocation="[Link]
app_3_1.xsd">
03 <servlet>
04 <servletname>ServletDemo</servletname>
05 <servletclass>ServletDemo</servletclass>
06 </servlet>
07 <servletmapping>
08 <servletname>ServletDemo</servlet
name>
09 <urlpattern>/ServletDemo</url
pattern>
10 </servletmapping>
11 <sessionconfig>
12 <sessiontimeout>
13 30
14 </sessiontimeout>
15 </sessionconfig>
16 </webapp>
Here,
1 <servletname>:namegiventoServlet
2 <servletclass>:servletclass
3 <servletmapping>:mapsinternalnameto
URL
4 <urlpattern>:linkdisplayswhenServlet
runs
[Link],whentheuserwillclickonit,thepagewillredirecttoServletDemoservletwhose
urlpatternismentionedasServetDemo:
Listing2:[Link]
01 <html>
02 <head>
03 <title>Welcome</title>
04 <metacharset="UTF8">
05 <metaname="viewport"content="width=device
width,initialscale=1.0">
06 </head>
07 <body>
08 <div><h2>Welcome</h2></div>
09 <p>We'restillunderdevelopmentstage.
StayTunedforourwebsite'snewdesign
andlearningcontent.</p>
10 <ahref="ServletDemo"><b>Next</b></a>
11 </body>
12 </html>
Listing3:[Link]
01 [Link];
02 [Link];
03 [Link];
04 [Link];
05 [Link];
06 [Link];
07
08 publicclassServletDemoextendsHttpServlet
{
09
10 protectedvoidprocessRequest(HttpServletRequest
request,HttpServletResponseresponse)
11 throwsServletException,
IOException{
12 [Link]("text/html;charset=UTF
8");
13 try(PrintWriterout=
[Link]()){
14 [Link]("<!DOCTYPE
html>");
15 [Link]("<html>");
16 [Link]("<head>");
17 [Link]("<title>Servlet
ServletDemo</title>");
18 [Link]("</head>");
19 [Link]("<body>");
20 [Link]("<h1>Servlet
ServletDemoat"+
[Link]()+"</h1>");
21 [Link]("</body>");
22 [Link]("</html>");
23 }
24 }
25
26 @Override
27 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
28 throwsServletException,
IOException{
29 [Link]("text/html;charset=UTF
8");
30 PrintWriterout=
[Link]();
31 try{
32 /*TODOoutputyourpagehere.
Youmayusefollowingsamplecode.*/
33 [Link]("<!DOCTYPE
html>");
34 [Link]("<html>");
35 [Link]("<head>");
36 [Link]("
<title>Servlets</title>");
37 [Link]("</head>");
38 [Link]("<body>");
39 [Link]("<br/><p><h2>First
DemoServletapplication</h2><br/>Here,the
[Link],
theaddressis
<i>WebApplicationServletDemo/ServletDemo</i>.
</p>");
40 [Link]("<br/><br/><a
href=\"[Link]\">PreviousPage</a>");
41 [Link]("</body>");
42 [Link]("</html>");
43 }
44 finally
45 {
46 [Link]();
47 }
48 }
49 }
Figure9:[Link]
Figure10:[Link]
[Link]
Filterstransformthecontentofrequests,responses,[Link].
Filterclassisdeclaredinthedeploymentdescriptor.
Itisusedtowritereusablecomponents.
Therequestisprocessbeforeitiscalledusingfilters.
Itcanbeusedunderawebapplicationforsometaskslike:
Validation
Compression
Verification
Internationalization
5.1Interface
Itconsistsofthese3filters:
Figure11:FilterAPIInterfaces
Filter
Thisistheinitialandbasicinterfacewhichallfilterclassshouldimplement. [Link] interfacehasthefollowingmethods:
Methods Description
init(FilterConfig) Thismethod
initializesafilter
doFilter(ServletRequest, Thismethod
ServletResponse, FilterChain) encapsulatesthe
servicelogicon
ServletRequestto
generate
ServletResponse.
FilterChainisto
forward
request/response
pairtothenext
filter.
destroy() Itdestroysthe
instanceofthe
filterclass.
FilterConfig
[Link]([Link])[Link]
[Link]:
Methods Description
getFilterName() Itreturnsthenameoffilterin
[Link]
getInitParameter(String) Itreturnsspecified
initializationparameters
[Link]
getInitParameterNames() Itreturnsenumerationofall
initializationparametersof
filter.
getServletContext() ItreturnsServletContext
object.
FilterChain
Itstoresinformationaboutmorethan1filter(chain).Allfiltersinthischainshouldbeappliedonrequestbeforeprocessingofa
request.
5.2Example
[Link]
[Link]>New>
Filter
Figure12:AddnewFiltertowebapplication
Figure13:AddClassNameasNewFilterandclickonNext
ConfigureFilterDeploymentbycheckingAddinformationtodeploymentdescriptor([Link]).Now,theNextbuttonisdisabledhere
[Link].
Figure14:ConfigureFilterDeploymentbycheckingAddinformationtodeployment
descriptor([Link])
Now,filterismappedbyaddingURLpatternasshowninFigure15.
Figure15:Filtermapping
AfteraddingnewfilterandclickingonOK,[Link],[Link].
Figure16:Addinginitparameter
Listing4:[Link]
TheFilterNewFiltercanbeappliedtoeveryservletas/*isspecifiedhereforURLpattern.
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="[Link]
instance"xsi:schemaLocation="[Link]
app_3_1.xsd">
03 <filter>
04 <filtername>NewFilter</filtername>
05 <filterclass>NewFilter</filterclass>
06 <initparam>
07 <paramname>newParam</paramname>
08 <paramvalue>valueOne</paramvalue>
09 </initparam>
10 </filter>
11 <filtermapping>
12 <filtername>NewFilter</filtername>
13 <urlpattern>/*</urlpattern>
14 </filtermapping>
15 <sessionconfig>
16 <sessiontimeout>
17 30
18 </sessiontimeout>
19 </sessionconfig>
20 </webapp>
Listing5:[Link]
01 [Link].*;
02 [Link].*;
03 [Link].*;
04 [Link].*;
05
06 publicclassNewFilterimplementsFilter{
07
08 publicvoidinit(FilterConfigfilterConfig)
{
09 //initparameter
10 Stringvalue=
[Link]("newParam");
11
12 //displayinginitparametervalue
13 [Link]("TheParameter
value:"+value);
14 }
15
16 publicvoiddoFilter(ServletRequest
request,ServletResponseresponse,
FilterChainchain)
17 throwsIOException,
ServletException{
18
19 //IPaddressoftheclient
machine.
20 StringremoteAddress=
[Link]();
21
22 //Returnstheremoteaddress
23 [Link]("Remote
InternetProtoclAddress:"+
remoteAddress);
24
25 [Link](request,response);
26 }
27
28 publicvoiddestroy(){
29
30 }
31 }
Figure17:Showingconsoleoutput
[Link]
[Link]
servletengine.
6.1SessionHandling
[Link]
[Link]
tracking.
6.2MechanismsofSessionHandling
Therearefourmechanismsforsessionhandling:
URLrewriting:ThesessiondatarequiredinthenextrequestisappendedtotheURLpathusedbytheclienttomakethenext
request.
QueryString:[Link]?character.
Example1): [Link]
PathInfo:[Link].
Example2): [Link]
Hiddenformfield:[Link]:textbox,passwordetc.
[Link].
Example3: <input type="hidden" username="name" value="nameOne"/>
Cookies:[Link]
transmittedtoclients(fromserver)throughtheHTTPresponseheader.
[Link],value,domain,versionnumber,path,
[Link] [Link] consistsofaclassnamesCookie.
Somemethodsin [Link] classarelistedbelow:
setValue (String)
getValue()
getName()
setComment(String)
getComment()
setVersion(String)
getVersion()
setDomain(String)
setPath(String)
getPath()
setSecure(boolean)
getSecure(boolean)
HTTPsession:ItprovidesasessionmanagementserviceimplementedthroughHttpSessionobject.
SomeHttpSessionobjectmethodsarelistedherethisisreferredfromtheofficialOracleDocumentation:
Method Description
public Object Itreturnstheobjectboundwith
getAttribute(String name) thespecifiednameinthissession
ornullifnoobjectisboundunder
thename.
public Enumeration Itreturns
getAttributeNames() EnumerationofStringobjects
containingthenamesofallthe
objectsboundtothissession.
public String getId() Itreturnsastringcontainingthe
uniqueidentifierassignedtothis
session.
public long Itreturnsthetimewhenthis
getCreationTime() sessionwascreated,measured
inmillisecondssincemidnight
January1,1970GMT.
public long Itreturnsthelasttimetheclient
getLastAccessedTime() sentarequestassociatedwith
thissession.
public int Itreturnsthemaximumtime
getMaxInactiveInterval() interval,insecondsthatthe
servletcontainerwillkeepthis
sessionopenbetweenclient
accesses.
public void invalidate() ItInvalidatesthissessionthen
unbindsanyobjectsboundtoit.
public boolean isNew() Itreturnstrueiftheclientdoesnot
yetknowaboutthesessionorif
theclientchoosesnottojointhe
session.
6.3Example
SessionInformationlikesessionid,sessioncreationtime,lastaccessedtimeandothersisprintedunderthisexample.
Listing6:[Link]
01 [Link];
02 [Link];
03 [Link];
04 [Link];
05 [Link];
06 [Link];
07 [Link];
08 [Link];
09
10 publicclassServletSessionextendsHttpServlet
{
11
12 @Override
13 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
14 throwsServletException,
IOException{
15 //sessionobjectcreation
16 HttpSessionnewSession=
[Link](true);
17 //Sessioncreationtime.
18 DatecTime
=newDate([Link]());
19 //Thelasttimetheclientsenta
request.
20 DatelTime=newDate(
[Link]());
21
22 /*setsthetime,inseconds,
betweenclientrequestsbeforetheservlet
container
23 invalidatesthissession*/
24 [Link](1*60*60);
25 Stringstr="Website|Session";
26
27 [Link]("text/html");
28 PrintWriterout=
[Link]();
29
30 Stringdocument=
31 "<!doctypehtmlpublic\"//w3c//dtd
html4.0"+
32 "transitional//en\">\n";
33 [Link](document+
34 "<html>\n"+
35 "<head><title>"+str+"
</title></head>\n"+
36 "<body
bgcolor=\"#bbf5f0\">\n"+
37 "<h2>Website:Displaying
SessionInformation</h2>\n"+
38 "<tableborder=\"2\">\n"+
39 "<tr>\n"+
40 "<td>Uniqueidentifier
assignedtothissession</td>\n"+
41 "<td>"+
[Link]()+"</td>"
[Link]()+"</td>"
42 +"</tr>\n"+
43 "<tr>\n"+
44 "<td>Thetimewhenthis
sessionwascreated</td>\n"+
45 "<td>"+cTime+
46 "</td>"
47 +"</tr>\n"+
48 "<tr>\n"+
49 "<td>Thelasttimethe
clientsentarequestassociatedwiththis
session</td>\n"
50 +"<td>"+lTime+
51 "</td>"
52 +"</tr>\n"+
53 "</tr>\n"+
54 "<tr>\n"+
55 "<td>themaximumtime
interval,insecondsthattheservlet
containerwillkeepthissessionopen
betweenclientaccesses.</td>\n"+
56 "<td>"+
[Link]()+
57 "</td>"
58 +"</tr>\n"+
59 "</table>\n"+
60 "</body></html>");
61 }
62 }
Figure18:Displayingoutput
[Link]
[Link]
[Link],in
[Link].
7.1ErrorCodeConfiguration
The/HandlerClassservletgetscalledwhenanerrorwithstatuscode403occursasshownbelow:
Listing7:ForErrorcode403
1 <errorpage>
2 <errorcode>403</errorcode>
3 <location>/HandlerClass</location>
4 </errorpage>
7.2ExceptionTypeConfiguration
IftheapplicationthrowsIOException,then/HandlerClassservletgetscalledbythecontainer:
Listing8:ForExceptionTypeIOException
1 <errorpage>
2 <exception
type>[Link]</exceptiontype>
3 <location>/HandlerClass</location>
4 </errorpage>
Ifyouwanttoavoidtheoverheadofaddingseparateelements,thenuse [Link] asexceptiontype:
Listing9:[Link]:
1 <errorpage>
2 <exception
type>[Link]</exceptiontype>
3 <location>/HandlerClass</location>
4 </errorpage>
[Link]
[Link]
[Link]
locationwarningsanderrors.
8.1MessageLogging
[Link]
cangeneratethisinformationusinglog()[Link],theselogscanbefoundinTomcatDirectory/logs.
8.2JavaDebugger
[Link].
Setdebuggersclasspathforfindingthefollowingclasses:
[Link]
server_root/servletsandserver_root/classes:Throughthisthedebuggersetsbreakpointsinaservlet.
8.3Headers
[Link]
[Link]
guessingwhatisnotgoingwell.
8.4Refresh
[Link],browsershowsrequestperformed
[Link].
Listing21:[Link]
Here,ServletDebuggingisshownwhichdisplaystheerrorsinTomcatlog.
01 [Link];
02 [Link];
03 [Link];
04 [Link];
05 [Link];
06 [Link];
07 [Link];
08
09 publicclassServletDebuggingextendsHttpServlet
{
10
11 @Override
12 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
13 throwsServletException,
IOException{
14
15 //parameter"name"
16 Stringstrpm=
[Link]("name");
17
18 ServletContextcontext=
getServletContext();
19
20 //checksiftheparameterisset
ornot
21 if(strpm==null||
[Link](""))
22 [Link]("Nomessage
received:",newIllegalStateException("Sorry,
the
23 parameterismissing."));
24 else
25 [Link]("Hereisthevisitor's
message:"+strpm);
26
27 }
28 }
Figure19:OutputasvisibleinApacheTomcatlog
[Link]
Forbuildingaglobalwebsite,someimportantpointsareconsideredwhichincludeslanguagerelatedtousersnationality.
Internationalizationisenablingawebsiteforprovidingcontenttranslatedindifferentlanguagesaccordingtousersnationality.
9.1Methods
Forfindingvisitorslocalregionandlanguage,thesemethodsareused:
Method Description
String getCountry() Returnsthecountrycode.
String getDisplayCountry() Returnsanameforthevisitors
country.
String getLanguage() Returnsthelanguagecode.
String getDisplayLanguage() Returnsanameforthevisitors
language.
String getISO3Country() Returnsathreeletter
abbreviationforthevisitors
country.
String getISO3Language() Returnsathreeletter
abbreviationforthevisitors
language.
9.2Example
[Link]:
1 ProjectName:
WebApplicationInternationalization
2 ProjectLocation:
C:\Users\Test\Documents\NetBeansProjects
3 Servlet:ServletLocale
4 URLPattern:/ServletLocale
Listing22:[Link]
01 [Link];
02 [Link];
03 [Link];
04 [Link];
05 [Link];
06 [Link];
07 [Link];
08
09 publicclassServletLocaleextendsHttpServlet
{
10
11 @Override
12 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
13 throwsServletException,
IOException{
14 //Gettheclient'sLocale
15 Localenewloc=[Link]();
16 Stringcountry=
[Link]();
17
18 //Setresponsecontenttype
19 [Link]("text/html");
20 PrintWriterout=
[Link]();
21
22 //thissetsthepagetitleandbody
content
23 Stringtitle="FindingLocaleof
currentuser";
24 StringdocType=
25 "<!doctypehtmlpublic\"//w3c//dtd
html4.0"+
26 "transitional//en\">\n";
27 [Link](docType+
28 "<html>\n"+
29 "<head><title>"+title+"
</title></head>\n"+
30 "<bodybgcolor=\"#C0C0C0\">\n"+"
<h3>"+country+"</h3>\n"+
31 "</body></html>");
32 }
33 }
Listing23:[Link]
01 <html>
02 <head>
03 <title>User'sLocation</title>
04 <metacharset="UTF8">
05 <metaname="viewport"content="width=device
width,initialscale=1.0">
06 </head>
07 <body>
08 <p>Clickonthefollowinglinkfor
findingthelocaleofvisitor:</p>
09 <ahref="ServletLocale">
<b>Location</b></a>
10 </body>
11 </html>
Listing24:[Link]/ServletLocale
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="[Link]
instance"xsi:schemaLocation="[Link]
app_3_1.xsd">
03 <servlet>
04 <servletname>ServletLocale</servlet
name>
05 <servletclass>ServletLocale</servlet
class>
06 </servlet>
07 <servletmapping>
08 <servletname>ServletLocale</servlet
name>
09 <urlpattern>/ServletLocale</url
pattern>
10 </servletmapping>
11 <sessionconfig>
12 <sessiontimeout>
13 30
14 </sessiontimeout>
15 </sessionconfig>
16 </webapp>
Figure20:[Link]
Figure21:Displayingthelocaleasoutput
[Link]
10.1Website
10.1Website
OfficialOracleDocumentation
SunDeveloperNetwork
FreeNetBeansDownload
FreeApacheDownload
FreeJavaDownload
10.2Books
HeadFirstServletsandJSP:PassingtheSunCertifiedWebComponentDeveloperExam,byBryanBasham,KathySierra,BertBates
ServletandJSP(ATutorial),byBudiKurniawan
[Link]
ServletisfastinperformanceandeasytousewhencomparedwithtraditionalCommonGatewayInterfaces(CGI).Throughthisguide
[Link],soyouwillgetanidea
aboutsomeofitsamazinguserfriendlyfeaturesaswell.