Java Servlet Tutorial - The ULTIMATE Guide (PDF Download)
Java Servlet Tutorial - The ULTIMATE Guide (PDF Download)
Introduction
ServletisaJavaprogramminglanguageclass,partofJavaEnterpriseEdition(JavaEE).SunMicrosystemsdevelopeditsfirstversion1.0
intheyear1997.ItscurrentVersionisServlet3.1.
Servletsareusedforcreatingdynamicwebapplicationsinjavabyextendingthecapabilityofaserver.Itcanrunonanywebserver
integratedwithaServletcontainer.
1.1ServletProcess
Theprocessofaservletisshownbelow:
Figure1:servletprocessingofuserrequests
ARequestissentbyaclienttoaservletcontainer.ThecontaineractsasaWebserver.
TheWebserversearchesfortheservletandinitiatesit.
Theclientrequestisprocessedbytheservletanditsendstheresponsebacktotheserver.
TheServerresponseisthenforwardedtotheclient.
1.2Merits
Servletsareplatformindependentastheycanrunonanyplatform.
TheServletAPIinheritsallthefeaturesoftheJavaplatform.
Itbuildsandmodifiesthesecuritylogicforserversideextensions.
ServletsinheritthesecurityprovidedbytheWebServer.
InServlet,onlyasingleinstanceoftherequestsrunsconcurrently.Itdoesnotruninaseparateprocess.So,itsavesthememory
byremovingtheoverheadofcreatinganewprocessforeachrequest.
2.LifeCycle
Servletlifecycledescribeshowtheservletcontainermanagestheservletobject.
LoadServletClass
ServletInstanceiscreatedbythewebcontainerwhentheservletclassisloaded
init() :Thisiscalledonlyoncewhentheservletiscreated.Thereisnoneedtocallitagainandagainformultiplerequests.
1 publicvoidinit()throwsServletException
{
2
3 }
service() :Itiscalledbythewebcontainertohandlerequestfromclients.Heretheactualfunctioningofthecodeisdone.The
webcontainercallsthismethodeachtimewhenrequestfortheservletisreceived.
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
3.Container
ItisknownasservletenginewhichmanagesJavaServletcomponentsontopofawebservertotherequestsendbytheclient.
3.1Services
ServletContainerprovidesthefollowingservices:
Itmanagestheservletlifecycle.
Theresourceslikeservlets,JSPpagesandHTMLfilesaremanagedbyservletcontainer.
ItappendssessionIDtotheURLpathtomaintainsession.
Providessecurityservice.
Itloadsaservletclassfromnetworkservices,filesystemslikeremotefilesystemandlocalfilesystem.
3.2ServletContainerConfigurations
Theservletcontainercanbeconfiguredwiththewebservertomanageservletsinthreewayslistedbelow:
Standalonecontainer
Inprocesscontainer
Outprocesscontainer
Standalonecontainer:InthistypetheWebServerfunctionalityistakenbytheServletcontainer.Here,thecontainerisstrongly
coupledwiththeWebserver.
InProcesscontainer:InthisthecontainerrunswithintheWebserverprocess.
OutProcesscontainer:InthistypethereisaneedtoconfiguretheservletcontainertorunoutsidetheWebserverprocess.Itis
usedinsomecaseslikeifthereisaneedtorunServletsandServletcontainerindifferentprocess/systems.
4.Demo:Tostartwith
HereisanexampleshowingDemoServlet.FollowthesestepstostartwithyourfirstServletApplicationinNetBeansIDE.
Step1:OpenNetBeansIDE>File>NewProject>WebApplication>SetProjectnameasWebApplicationServletDemo
Figure3:CreatenewWebApplicationprojectinNetBeansIDE:WebApplicationServletDemo
Step2:NowclickonNext>asshownabove.Thiswillcreatenewprojectwiththefollowingdirectorystructure.
Figure4:ProjectDirectory
aftercreatingnewproject
Step3:CreatenewservletapplicationbyRightClickingonProjectDirectory>New>Servlet
Figure5:AddingServletfile
Step4:AddtheServletClassNameasServletDemoandclickonNext.
Figure6:AddingServletClassName
Step5:Now,ConfigureServletDeploymentbycheckingAddinformationtodeploymentdescriptor(web.xml)andaddingURLPattern
(thelinkvisible)asServletDemo.Thisstepwillgenerateweb.xmlfileinWEBINFfolder.
Figure7:ConfiguringServletDeployment
Step6:ClickonFinishasshownabove,thiswilladdServletDemo.javaservletunderprojectdirectory.Checkthechangesunder
DirectoryStructure:
Figure8:Changesunderproject
directoryafterconfiguring
Hereisthecodefordeploymentdescriptor(web.xml)withURLpatteras/ServletDemo:
Listing1:web.xml
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web
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
ThehyperlinkNextismentionedasServletDemo.So,whentheuserwillclickonit,thepagewillredirecttoServletDemoservletwhose
urlpatternismentionedasServetDemo:
Listing2:index.html
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:ServletDemo.java
01 importjava.io.IOException;
02 importjava.io.PrintWriter;
03 importjavax.servlet.ServletException;
04 importjavax.servlet.http.HttpServlet;
05 importjavax.servlet.http.HttpServletRequest;
06 importjavax.servlet.http.HttpServletResponse;
07
08 publicclassServletDemoextendsHttpServlet
{
09
10 protectedvoidprocessRequest(HttpServletRequest
request,HttpServletResponseresponse)
11 throwsServletException,
IOException{
12 response.setContentType("text/html;charset=UTF
8");
13 try(PrintWriterout=
response.getWriter()){
14 out.println("<!DOCTYPE
html>");
15 out.println("<html>");
16 out.println("<head>");
17 out.println("<title>Servlet
ServletDemo</title>");
18 out.println("</head>");
19 out.println("<body>");
20 out.println("<h1>Servlet
ServletDemoat"+
request.getContextPath()+"</h1>");
21 out.println("</body>");
22 out.println("</html>");
23 }
24 }
25
26 @Override
27 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
28 throwsServletException,
IOException{
29 response.setContentType("text/html;charset=UTF
8");
30 PrintWriterout=
response.getWriter();
31 try{
32 /*TODOoutputyourpagehere.
Youmayusefollowingsamplecode.*/
33 out.println("<!DOCTYPE
html>");
34 out.println("<html>");
35 out.println("<head>");
36 out.println("
<title>Servlets</title>");
37 out.println("</head>");
38 out.println("<body>");
39 out.println("<br/><p><h2>First
DemoServletapplication</h2><br/>Here,the
URLpatternisServletDemoinweb.xml.So,
theaddressis
<i>WebApplicationServletDemo/ServletDemo</i>.
</p>");
40 out.println("<br/><br/><a
href=\"index.html\">PreviousPage</a>");
41 out.println("</body>");
42 out.println("</html>");
43 }
44 finally
45 {
46 out.close();
47 }
48 }
49 }
Figure9:Outputshowingindex.htmlwelcomepage
Figure10:OutputshowingredirectiontoServletDemo.java
5.Filter
Filterstransformthecontentofrequests,responses,andheaderinformationfromoneformattoanother.Thesearereusablecodes.
Filterclassisdeclaredinthedeploymentdescriptor.
Itisusedtowritereusablecomponents.
Therequestisprocessbeforeitiscalledusingfilters.
Itcanbeusedunderawebapplicationforsometaskslike:
Validation
Compression
Verification
Internationalization
5.1Interface
Itconsistsofthese3filters:
Figure11:FilterAPIInterfaces
Filter
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
Itsobjectisusedwhenthefiltersareinitialized.Deploymentdescriptor(web.xml)consistsofconfigurationinformation.Theobjectof
FilterConfiginterfaceisusedtofetchconfigurationinformationaboutfilterspecifiedinweb.xml.Itsmethodsarementionedbelow:
Methods Description
getFilterName() Itreturnsthenameoffilterin
web.xml
getInitParameter(String) Itreturnsspecified
initializationparameters
valuefromweb.xml
getInitParameterNames() Itreturnsenumerationofall
initializationparametersof
filter.
getServletContext() ItreturnsServletContext
object.
FilterChain
Itstoresinformationaboutmorethan1filter(chain).Allfiltersinthischainshouldbeappliedonrequestbeforeprocessingofa
request.
5.2Example
ThisisanexampleshowingfiltersapplicationinNetBeansIDE.CreateaWebApplicationprojectWebApplicationFilterDemointhesame
waysasshownunderDemosection.NewFiltercanbeaddedinthewebapplicationbyRightClickingonProjectDirectory>New>
Filter
Figure12:AddnewFiltertowebapplication
Figure13:AddClassNameasNewFilterandclickonNext
ConfigureFilterDeploymentbycheckingAddinformationtodeploymentdescriptor(web.xml).Now,theNextbuttonisdisabledhere
duetoanerrorhighlightedinFigure13.TheerrorEnteratleastoneURLpatterncanbesolvedbyclickingonNew.
Figure14:ConfigureFilterDeploymentbycheckingAddinformationtodeployment
descriptor(web.xml)
Now,filterismappedbyaddingURLpatternasshowninFigure15.
Figure15:Filtermapping
AfteraddingnewfilterandclickingonOK,theerrorwillgetresolved.Now,addinitparameterwithnameandvalue.ThenclickFinish.
Figure16:Addinginitparameter
Listing4:web.xml
TheFilterNewFiltercanbeappliedtoeveryservletas/*isspecifiedhereforURLpattern.
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web
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:NewFilter.java
01 importjava.io.*;
02 importjavax.servlet.*;
03 importjavax.servlet.http.*;
04 importjava.util.*;
05
06 publicclassNewFilterimplementsFilter{
07
08 publicvoidinit(FilterConfigfilterConfig)
{
09 //initparameter
10 Stringvalue=
filterConfig.getInitParameter("newParam");
11
12 //displayinginitparametervalue
13 System.out.println("TheParameter
value:"+value);
14 }
15
16 publicvoiddoFilter(ServletRequest
request,ServletResponseresponse,
FilterChainchain)
17 throwsIOException,
ServletException{
18
19 //IPaddressoftheclient
machine.
20 StringremoteAddress=
request.getRemoteAddr();
21
22 //Returnstheremoteaddress
23 System.out.println("Remote
InternetProtoclAddress:"+
remoteAddress);
24
25 chain.doFilter(request,response);
26 }
27
28 publicvoiddestroy(){
29
30 }
31 }
Figure17:Showingconsoleoutput
6.Session
ItisacollectionofHTTPrequestsbetweenclientandserver.Thesessionisdestroyedwhenitexpiresanditsresourcesarebacktothe
servletengine.
6.1SessionHandling
Itisameanstokeeptrackofsessiondata.Thisrepresentsthedatatransferredinasession.Itisusedwhensessiondatafromone
sessionmayberequiredbyawebserverforcompletingtasksinsameordifferentsessions.Sessionhandlingisalsoknownassession
tracking.
6.2MechanismsofSessionHandling
Therearefourmechanismsforsessionhandling:
URLrewriting:ThesessiondatarequiredinthenextrequestisappendedtotheURLpathusedbytheclienttomakethenext
request.
QueryString:AstringappendedaftertherequestedURIisquerystring.Thestringisappendedwithseparatoras?character.
Example1): http://localhost:8080/newproject/login?user=test&passwd=abcde
PathInfo:ItisthepartoftherequestURI.SessiondatacanbeaddedtothepathinfopartoftherequestURI.
Example2): http://localhost:8080/newproject/myweb/login;user=test&passwd=abcde
Hiddenformfield:AtypeofHTMLformfieldwhichremainshiddenintheview.Someotherformfieldsare:textbox,passwordetc.
Thisapproachcanbeusedwithformbasedrequests.Itisjustusedforhidinguserdatafromotherdifferenttypesofusers.
Cookies:Itisafilecontainingtheinformationthatissenttoaclientbyaserver.Cookiesaresavedattheclientsideafterbeing
transmittedtoclients(fromserver)throughtheHTTPresponseheader.
Cookiesareconsideredbestwhenwewanttoreducethenetworktraffic.Itsattributesarename,value,domain,versionnumber,path,
andcomment.Thepackage javax.servlet.http consistsofaclassnamesCookie.
setValue (String)
getValue()
getName()
setComment(String)
getComment()
setVersion(String)
getVersion()
setDomain(String)
setPath(String)
getPath()
setSecure(boolean)
getSecure(boolean)
HTTPsession:ItprovidesasessionmanagementserviceimplementedthroughHttpSessionobject.
SomeHttpSessionobjectmethodsarelistedherethisisreferredfromtheofficialOracleDocumentation:
Method Description
6.3Example
SessionInformationlikesessionid,sessioncreationtime,lastaccessedtimeandothersisprintedunderthisexample.
Listing6:ServletSession.java
01 importjava.io.IOException;
02 importjava.io.PrintWriter;
03 importjava.util.Date;
04 importjavax.servlet.ServletException;
05 importjavax.servlet.http.HttpServlet;
06 importjavax.servlet.http.HttpServletRequest;
07 importjavax.servlet.http.HttpServletResponse;
08 importjavax.servlet.http.HttpSession;
09
10 publicclassServletSessionextendsHttpServlet
{
11
12 @Override
13 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
14 throwsServletException,
IOException{
15 //sessionobjectcreation
16 HttpSessionnewSession=
request.getSession(true);
17 //Sessioncreationtime.
18 DatecTime
=newDate(newSession.getCreationTime());
19 //Thelasttimetheclientsenta
request.
20 DatelTime=newDate(
newSession.getLastAccessedTime());
21
22 /*setsthetime,inseconds,
betweenclientrequestsbeforetheservlet
container
23 invalidatesthissession*/
24 newSession.setMaxInactiveInterval(1*60*60);
25 Stringstr="Website|Session";
26
27 response.setContentType("text/html");
28 PrintWriterout=
response.getWriter();
29
30 Stringdocument=
31 "<!doctypehtmlpublic\"//w3c//dtd
html4.0"+
32 "transitional//en\">\n";
33 out.println(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>"+
newSession.getId()+"</td>"
newSession.getId()+"</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>"+
newSession.getMaxInactiveInterval()+
57 "</td>"
58 +"</tr>\n"+
59 "</table>\n"+
60 "</body></html>");
61 }
62 }
Figure18:Displayingoutput
7.ExceptionHandling
Exceptionsareusedtohandleerrors.Itisareactiontounbearableconditions.Herecomestheroleofweb.xmli.e.deployment
descriptionwhichisusedtorunJSPandservletpages.Thecontainersearchestheconfigurationsinweb.xmlforamatch.So,in
web.xmlusetheseexceptiontypeelementsformatchwiththethrownexceptiontypewhenaservletthrowsanexception.
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>java.io.IOException</exceptiontype>
3 <location>/HandlerClass</location>
4 </errorpage>
Listing9:Forallexceptionsmentionjava.lang.Throwable:
1 <errorpage>
2 <exception
type>java.lang.Throwable</exceptiontype>
3 <location>/HandlerClass</location>
4 </errorpage>
8.Debugging
8.Debugging
ClientserverinteractionsareinlargenumberinServlets.Thismakeserrorsdifficulttolocate.Differentwayscanbefollowedfor
locationwarningsanderrors.
8.1MessageLogging
Logsareprovidedforgettinginformationaboutwarninganderrormessages.Forthisastandardloggingmethodisused.ServletAPI
cangeneratethisinformationusinglog()method.UsingApacheTomcat,theselogscanbefoundinTomcatDirectory/logs.
8.2JavaDebugger
ServletscanbedebuggedusingJDBDebuggeri.e.JavaDebugger.Inthistheprogrambeingdebuggedissun.servlet.http.HttpServer.
Setdebuggersclasspathforfindingthefollowingclasses:
servlet.http.HttpServer
server_root/servletsandserver_root/classes:Throughthisthedebuggersetsbreakpointsinaservlet.
8.3Headers
UsersshouldhavesomeinformationrelatedtostructureofHTTPheaders.Issuescanbejudgedusingthemwhichcanfurtherlocate
someunknownerrors.InformationrelatedtoHTTPheaderscanhelpyouinlocatingerrors.Studyingrequestandresponsecanhelpin
guessingwhatisnotgoingwell.
8.4Refresh
Refreshyourbrowserswebpagetoavoiditfromcachingpreviousrequest.Atsomestages,browsershowsrequestperformed
previously.Thisisaknownpointbutcanbeaproblemforthosewhoareworkingcorrectlybutunabletodisplaytheresultproperly.
Listing21:ServletDebugging.java
Here,ServletDebuggingisshownwhichdisplaystheerrorsinTomcatlog.
01 importjava.io.IOException;
02 importjava.io.PrintWriter;
03 importjavax.servlet.ServletContext;
04 importjavax.servlet.ServletException;
05 importjavax.servlet.http.HttpServlet;
06 importjavax.servlet.http.HttpServletRequest;
07 importjavax.servlet.http.HttpServletResponse;
08
09 publicclassServletDebuggingextendsHttpServlet
{
10
11 @Override
12 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
13 throwsServletException,
IOException{
14
15 //parameter"name"
16 Stringstrpm=
request.getParameter("name");
17
18 ServletContextcontext=
getServletContext();
19
20 //checksiftheparameterisset
ornot
21 if(strpm==null||
strpm.equals(""))
22 context.log("Nomessage
received:",newIllegalStateException("Sorry,
the
23 parameterismissing."));
24 else
25 context.log("Hereisthevisitor's
message:"+strpm);
26
27 }
28 }
Figure19:OutputasvisibleinApacheTomcatlog
9.Internationalization
Forbuildingaglobalwebsite,someimportantpointsareconsideredwhichincludeslanguagerelatedtousersnationality.
Internationalizationisenablingawebsiteforprovidingcontenttranslatedindifferentlanguagesaccordingtousersnationality.
9.1Methods
Forfindingvisitorslocalregionandlanguage,thesemethodsareused:
Method Description
9.2Example
Theexampledisplaysthecurrentlocaleofauser.FollowingprojectiscreatedinNetBeansIDE:
1 ProjectName:
WebApplicationInternationalization
2 ProjectLocation:
C:\Users\Test\Documents\NetBeansProjects
3 Servlet:ServletLocale
4 URLPattern:/ServletLocale
Listing22:ServletLocale.java
01 importjava.io.IOException;
02 importjava.io.PrintWriter;
03 importjava.util.Locale;
04 importjavax.servlet.ServletException;
05 importjavax.servlet.http.HttpServlet;
06 importjavax.servlet.http.HttpServletRequest;
07 importjavax.servlet.http.HttpServletResponse;
08
09 publicclassServletLocaleextendsHttpServlet
{
10
11 @Override
12 protectedvoiddoGet(HttpServletRequest
request,HttpServletResponseresponse)
13 throwsServletException,
IOException{
14 //Gettheclient'sLocale
15 Localenewloc=request.getLocale();
16 Stringcountry=
newloc.getCountry();
17
18 //Setresponsecontenttype
19 response.setContentType("text/html");
20 PrintWriterout=
response.getWriter();
21
22 //thissetsthepagetitleandbody
content
23 Stringtitle="FindingLocaleof
currentuser";
24 StringdocType=
25 "<!doctypehtmlpublic\"//w3c//dtd
html4.0"+
26 "transitional//en\">\n";
27 out.println(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:index.htmlwithlocationhyperlinkasURLpatternServletLocale
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:web.xmlwithURLpatternas/ServletLocale
01 <?xmlversion="1.0"encoding="UTF8"?>
02 <web
appversion="3.1"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web
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:Displayingindex.html
Figure21:Displayingthelocaleasoutput
10.References
10.1Website
10.1Website
OfficialOracleDocumentation
SunDeveloperNetwork
FreeNetBeansDownload
FreeApacheDownload
FreeJavaDownload
10.2Books
HeadFirstServletsandJSP:PassingtheSunCertifiedWebComponentDeveloperExam,byBryanBasham,KathySierra,BertBates
ServletandJSP(ATutorial),byBudiKurniawan
11.Conclusion
ServletisfastinperformanceandeasytousewhencomparedwithtraditionalCommonGatewayInterfaces(CGI).Throughthisguide
youcaneasilylearntheconceptsrelatedtoJavaServlets.TheprojectcodesaredevelopedunderNetBeansIDE,soyouwillgetanidea
aboutsomeofitsamazinguserfriendlyfeaturesaswell.