版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
JavaServlet
OutlinesServletOverviewBackgroud:HTML&HTTPServletprocessflowBuidaservletDeploymentofServletAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerServletOverview
OutlinesBackgroud:HTML&HTTPServletprocessflowBuidaservletDeploymentofServletWhatisHTMLHTMLstandsforHyperTextMarkupLanguage.HTMListhebasicbuilding-blocksofwebpages.AmarkuplanguageusesasetofmarkuptagstodescribewebpagesExample:<html><!--thestartoftheweb><head><!–thebeginoftheheadpart--><title>helloworld!</title></head><body><!--thestartofthecontentoftheweb>
<h1>MyFirstHeading</h1>
<p>Myfirstparagraph.</p>
</body>
</html>MoreaboutHTMLDescribeLearnhowtocreatewebpages: Sometoolstocreatewebpages:NotepadDreamweaverMicrosoftOffice(Word,Frontpage)Client/BrowserHTTPGETrequestmusic.htmlReturn(response)music.htmlWebServerHTTPFlowstorequestawebpageHttp定義了與服務(wù)器交互的不同方法,最基本的方法有4種,分別是GET,POST,PUT,DELETE,分別對應(yīng)對請求資源的查,改,增,刪4個操作。GET和POST使用的比較多。其中,GET一般用于獲取/查詢資源信息,而POST一般用于提交數(shù)據(jù)/更新資源信息。HTTPRequestandResponseRequest:GET
/music.html
HTTP/1.1
Host:
User-Agent:Mozilla/5.0(Windows;U;WindowsNT5.1;en-US;rv:1.7.6)Gecko/20050225Firefox/1.0.1
Connection:Keep-AliveResponse:HTTP/1.1200OK
Date:Sat,31Dec200523:59:59GMT
Content-Type:text/html;charset=ISO-8859-1
Content-Length:122
<html>
<head>
<title>W(wǎng)roxHomepage</title>
</head>
<body>
<!--bodygoeshere-->
</body>
</html>OutlinesBackgroud:HTML&HTTPServletprocessflowBuidaservletDeploymentofServletWhatIsaServlet?Aservletisastandard,server-sidecomponentofaJ2EEapplicationwhichexecutesbusinesslogiconbehalfofanHTTPrequestRunsintheservertier(andnotintheclient)JavabasedManagedbytheWebcontainerinthe
serverrequestresponseURLrequestresponseApplicationServerWebServerBrowser(client)ServletInstanceServletProcessFlowClientmakesarequestnamingaservletaspartoftheURL(UniformResourceLocator,也即是網(wǎng)頁地址).Webserverforwardsrequesttoservletengine,whichlocatesaninstanceofaServletclass.Servletenginecallsservlet'sservicemethod.TheservletbuildsaresponsedynamicallyandpassesittotheWebserver.
TheWebserversendstheresponsebacktotheclient.Example(1)
...<formaction="/Music/SearchServlet"method="POST"><h3>MusicStoreSearch</h3><br><strong>Typeinthesongtitle:</strong><inputtype="text"size="55"name="song_title"><br><strong>Typeinthesongartist:</strong><inputtype="text"size="55"name="song_artist"><br><inputtype="submit"value="Search"><br><strong>Displaythefirst</strong>Example(2)ReturnedmusicSearch.html:Client/BrowserSubmitform(HTTP
POSTRequest)WebServer/ApplicationServerExample(3)POST/Music/SearchServletHTTP/1.0Referer:Connection:Keep-AliveUser-Agent:Mozilla/4.72[en](WinNT5.0;U)Host:localhost:8080Cookie:USERID=spotAccept:image/gif,image/x-xbitmap,image/jpeg,*/*Accept-Language:enAccept-Charset:iso-8859-1,*,utf-8Content-type:application/x-www-form-urlencodedContent-length:50song_title=Hello&song_artist=Jones&limit_number=20Example(4)Afterclickthesearchbutton,aHTTPPOSTrequestissenttoserver:ServletgeneratesanHTMLresponsebasedontheinputfromtheform.TheServerreturnstheHTMLdocument(response).Client/BrowserHTTPPOSTrequestWebServer/ApplicationServerExample(5)HTTP/1.1200okContent-Type:text/htmlSet-Cookie:sessionid=5H2HXGYAAAAAEWQAAAAZJCI;Path=/Cache-Control:no-cache="set-cookie,set-cookie2"Expires:Thu,01Dec199416:00:00GMTSet-Cookie:USERID=spot;Expires=Fri,08-Jun-200121:54:37GMTContent-Language:en<HTML><BODY><H1>Verysimpledynamicdocumentcreatedon01-Jun-2001</H1></BODY></HTML>Example(6)AfterreceivingtheHTTPrequest,thewebserverpasstherequesttothecorrespondingservlet.TheservletconstructtheHTTPResponseincluding:Statusinformation(200inourexample)HeadervaluesAblanklineOutputdocument(HTML)OutlinesBackgroud:HTML&HTTPServletprocessflowBuidaservletDeploymentofServletBuildingaSimpleJavaServletTocreateaservletwhichrespondstoHTTPrequests,youmust:Createaclasswhichextendsjavax.servlet.http.HttpServletOverridethedoGetordoPostmethodstoprocessHTTPGETorPOSTrequestsProcessinputvaluesintherequestInvokethebusinessprocessSettheresponseOutputHTMLtotheoutputbufferServletsareinherently(固有的)multithreadedpackagecom.ibm.example.servlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.ServletException;importjava.io.IOException;importjava.io.PrintWriter;publicclassVerySimpleServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsServletException,IOException{
Stringbrowser=request.getHeader("User-Agent");response.setStatus(HttpServletResponse.SC_OK);//defaultresponse.setContentType("text/html"); //default
PrintWriterout=response.getWriter(); out.println("<HTML><HEAD><TITLE>Simpleservlet");out.println("</TITLE></HEAD><BODY>"); out.println("Browserdetails:"+browser); out.println("</BODY></HTML>"); }publicvoiddoPost(HttpServletRequest
request,
HttpServletResponse
response){……}}ASimpleJavaServletExampleHttpServletdoGet(),anddoPost()methodseachhavetwoparameters:HttpServletRequest-providesaccesstorequestdata(parameters),Httpsessioninformation,andsoforthHttpServletResponse-providesservicestoallowtheservlettosupplyaresponsetotherequestingclientMostservletprogrammingamountstoreadingarequestandwritingaresponseURLrequestresponseApplicationServerWebServerBrowser(client)ServletInstancePOST/Music/SearchServletHTTP/1.0Referer:Connection:Keep-AliveUser-Agent:Mozilla/4.72[en](WinNT5.0;U)Host:localhost:8080Accept:image/gif,image/x-xbitmap,image/jpegAccept-Language:enAccept-Charset:iso-8859-1,*,utf-8Content-type:application/x-www-form-urlencodedContent-length:50song_title=Hello&song_artist=Jones&limit_number=20HttpServletRequest(1)Representsclient'srequestContainsgetters
foraspectsofrequest,forexample:Requestheader,contenttype,length,methodRequestURLasaStringandrequestservletpathClienttypeRequest
parametersHttpServletRequest(2)TheHttpServletRequestobjectencapsulatesallinformationfromtheclientrequest.Thefollowingmethodsareavailabletoaccessrequestheader:GetHeaderintheHTTPrequestMethod:getHeaders,getHeaderNames,
getHeaderGetInputdatatypeandlengthintheHeaderMethods:getContentTypeandgetContentLengthGetCookiesintheHeaderMethod:getCookiesGetIdentificationforauthorizationintheHeaderHeader:AuthorizationMethods:getAuthTypeandgetRemoteUserGetProtocolintheHeader(GETorPOST)Method:getMethod
Moreinformation:HttpServletRequest(3)Thefollowingmethodsareavailabletoaccessparameters:getParameterNames()ReturnsanEnumerationofparametersontheHTMLpagegetParameterValues(Stringname)ReturnsthevalueofamultivaluedparametergetParameter(Stringname)ReturnsthevalueofaspecificnamedparametergetReader()ReturnsaBufferedReadertoviewinput<P>Usethisformtosearchforthemusicyouwant.<FORM
METHOD="POST"ACTION="/Music/SearchServlet">
<P>Pleaseenteryoursearchcriteria:
<P>Songtitle:<INPUT
NAME="song_title"TYPE="TEXT"SIZE="12"MAXLENGTH="20"><P>Songartist:<INPUTNAME="song_artist"TYPE="TEXT"SIZE="15"MAXLENGTH="25"><P>Thankyou!<INPUT
TYPE="SUBMIT"><INPUT
TYPE="RESET"></FORM>Example(1)musicsearch.htmlExample(2)POST/Music/SearchServletHTTP/1.1Host:User-Agent:Mozilla/5.0(WindowsNT5.1;rv:10.0.2)Gecko/20100101Firefox/10.0.2Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language:zh-cn,zh;q=0.5Accept-Encoding:gzip,deflateConnection:keep-aliveContent-Type:application/x-www-form-urlencodedContent-Length:45song_title=Sunday+morning&song_artist=JacksonAftertheuserclickthesubmitbutton,aHTTPPOSTrequestwillbesenttotheserver:publicclassSearchServletextendsHttpServlet{
publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{ ...Enumerationenum=req.getParameterNames();
while(enum.hasMoreElements()){ Stringname=(String)enum.nextElement(); Stringvalue=req.getParameter(name);
//…dosomethingwitheachpair... }...
}Example(3)HttpServletResponse(1)RepresentscommunicationchannelbacktoclientSetsthecontenttypeandstatuscodeAllowstheservlettoreturndynamiccontentorerrorinformationAllowstheservlettoredirecttheclienttoanotherURLHttpServletResponse(2)
HttpServletResponse::setStatus(intstatusCode)StatuscodesforHTTP1.11xx:Informational-Requestreceived,continuingprocess(theclientneedstorespondinsomeway)2xx:Success-Theactionwassuccessful3xx:Redirection-Furtheractionmustbetakeninordertocompletetherequest4xx:ClientError-Therequestcontainsbadsyntaxorsomeotherclienterror5xx:ServerError-Therequestisvalid,buttheserverfailedtofulfilltherequestHttpServletResponsehasconstantsbeginningwith‘SC_’formostofthestandardstatuscodes.HttpServletResponse.SC_OK200HttpServletResponse(3)HttpServletResponse::setContentType(Stringtype)SetthecontenttypeforthisresponseTypeisaMIMEtype(MultipurposeInternetMailExtensionstype)(eg."text/html","image/gif”)
Maintype/subtypeDocumenttypeapplication/pdfAcrobatfile(.PDF)application/postscriptPostScriptfileapplication/vnd.lotus-notesLotusNotesfileapplication/x-gzipGziparchiveapplication/x-java-archiveJARfileapplication/zipZipArchiveaudio/x-wavWindowssoundfiletext/htmlHTMLdocumenttext/xmlXMLdocumentimage/gifGIFimage……HttpServletResponse(4)HttpServletResponse::getWriter()ReturnsareferencetothePrintWriterHttpServletResponse::getOutputStream()ReturnsareferencetotheServletOutputStreamUsedtocreatebinarydocuments
Moreinformation:publicclassMyServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
//getstreamtooutputHTMLon!res.setStatus(HttpServletResponse.SC_OK);res.setContentType("text/html");PrintWriterout=res.getWriter();
//sendoutasimplebannerout.println("<HTML><BODY><H1>Todayis"+(newDate()));out.println("</H1></BODY></HTML>");}}Example:CreateInitialize(Initializefailed)Unavailableforservice(Unavailableexceptionthrown)AvailableforserviceServicingrequestsUnloadDestroyJavaServletLifecycleOutlinesBackgroud:HTML&HTTPServletprocessflowBuidaservletDeploymentofServletWhatIsDeployment(部署)?DeploymentistheprocessofconfiguringaservletandprovidingaURLmappinginawebserver.Thewebservermustknow:thelocationoftheservletclassinitializationparameterstheURLmappingfortheservletsecurityinformationAllofaboveisrecordedinthedescriptionfile:web.xml.HowtodeployinnetbeansIDEConfigureweb.xml.Deploytheservletbysimplyclickthe‘deploy’buttonDeploytheprojectAdvancetopicofServlet
OutlinesAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerRedirectionRedirection(重定向):將瀏覽器重定向到另一個URL,而不是將內(nèi)容發(fā)送給用戶。應(yīng)用舉例:網(wǎng)頁地址發(fā)生變化時,確保站點在過渡交接期向原地址發(fā)起的訪問流量不會丟失。RequestURL1RedirectionResponseWebServerBrowser(client)RequestanotherURLResponseErrorSendingErrorSending:返回錯誤提示信息給瀏覽器RequestURL1ERRORINFORMATIONWebServerBrowser(client)RedirectionandErrorSendingUsethefollowingmethodsofHttpServletResponseobject:ResponseRedirect:sendRedirect(URL)SendsredirectionresponsetoclientURLspecifiestheredirectionlocationMaybeabsoluteorrelativeErrorSending:sendError(statuscode)
SetsaresponsestatuscodeServer-specificerrorpagedescribingtheerrorsentasresponseTheerrorpagesaredefinedintheWebdeploymentdescriptor:web.xmlprivatevoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)...{//processrequestheaders&querydata...
//redirecttoanotherURLStringurl="/YourResults.html";
if(test.equals("Error"))response.sendError(response.SC_BAD_REQUEST);//400
elseresponse.sendRedirect(response.encodeRedirectURL(url));
return;}RedirectionandSendError(Example)
MoredocumentaboutsendRedirect/sendError:OutlinesAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerRequestDispatchingRequestDispatching(分派):
Dispatchtherequesttoanotherservlet.TwokindsofDispatching:Forwarding.ForwardarequesttoanotherservletIncluding.includetheoutputfromanotherservletServletAServletBContentreturnedtoBrowserforwardServletAServletBContentreturnedtoBrowserincludeRequestDispatcherFlowWhat’sthedifferencecomparingwithRedirection?getServletContext().getRequestDispatcher("/pages/showBalance.jsp").
forward(request,response);getServletContext().getRequestDispatcher("/pages/navigation_bar.html").
include(request,response);SampleUseofRequestDispatcherprivatevoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse)...{//processrequestheaders&querydata
...//Forwardtherequest
if(errorFound){Stringres="/ErrorFound.html";
getServletContext().getRequestDispatcher(res).forward(request,response);
return;}}ForwardMethod(Example)privatevoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse)...{//processrequestheaders&querydata...//includetherequestresponse.setContentType("text/html");PrintWriterout=response.getWriter();out.println("<HTML><BODY>StartofINCLUDEDrequest");out.println("<P>Hi"+request.getParameter("name"));out.flush();
getServletContext().getRequestDispatcher("/ILSCS01/DispatcherInclude").
include(request,response);out.println("<P>Endofrequest</BODY></HTML>");}IncludeMethod(Example)OutlinesAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerThereareseveralwaystoshareobjectsbetweenservletsandJSPs:1)SharedamongallServletsbyusingServletContexobject.getServletContext().setAttribute("objectName",anObject);getServletContext().getAttribute("objectName");2)SharedamongtheServlets
handlingasamerequestbyusingHttpServletRequestobject.request.setAttribute("objectName",anObject);request.getAttribute("objectName");SharingObjects(1)SharingObjects(2)3)SharedbyallServletsservingthesameclientbyusingHttpSessionobject.HttpSessionsession=request.getSession();session.setAttribute("objectName",anObject);session.getAttribute("objectName");HttpServletRequestrequest//Servlet"A"publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresp)...{//processrequestheaders&querydataCustomercust;...
request.setAttribute("CUSTOMER",cust);Stringres="/Internal/ServletB";getServletContext().getRequestDispatcher(res).forward(request,resp);return;}//Servlet"B"publicvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)...{CustomeraCust=(Customer)req.getAttribute("CUSTOMER");...}HttpServletRequest"CUSTOMER"CustomerSharingObjectsExampleOutlinesAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerIntroducingFiltersFilter:Anobjectthatcantransformthecontentoftherequestorresponseforaresource.Typesoffunctionality:ProcesstherequestforaresourcebeforeitisinvokedProcesstheresponseforaresourceafteritisinvokedCanbeconfiguredintochainsofmultiplefiltersTypicalUsesofFiltersTypicalfilteruses:AuthenticationfiltersLoggingandauditingfiltersImageconversionfiltersDatacompressionfiltersEncryptionfiltersXSLTfilterstotransformXMLcontentCachingCreateaFilterCreateaclassthatimplementsthejavax.servlet.FilterinterfaceImplementmethods:doFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)classTestFilterimplementsFilter{……publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain){Access/Modifytherequest
chain.doFilter(request,response)Access/modifytheresponse}
}requestrequestresponseresponseFilterChainFilterscanbeconfiguredinachaindoFilter(){chain.doFilter()}doPost(){………….}doFilter(){chain.doFilter()}FirstFilterSecondFilterFilteredServletRequestResponseExampleConfigtheFilterinweb.xmlConfiguringtheFilterinweb.xmlFiltersareconfiguredinthedeploymentdescriptor(web.xml)Structureofthefilter’sdescribingelements<filter>:describesthefilter<filter-name>:nameofthefilter<filter-class>:nameoftheimplementingclass<init-param>:describesinitializationparametersofthefilter<param-name>:theinitializationparametername<param-value>:theinitializationparametervalueExampleofaFilterDescription<filter> <filter-name>FormChecker</filter-name> <display-name>FormChecker</display-name> <filter-class>com.ibm.filters.FormChecker</filter-class> <init-param> <param-name>__FORM_NAME</param-name> <param-value>PrimeFinder</param-value> </init-param> <init-param> <param-name>num</param-name> <param-value>Number</param-value></init-param></filter>ConfiguringtheFilterMappinginweb.xmlFiltermappings(whichfilterisdeployedtowhichresource?)areConfiguredinthedeploymentdescriptor(web.xml)Structureofthefilter’smappingelements<filter-mapping>:describesthefilter<filter-name>:nameofthefiltertobemapped<servlet-name>:nameoftheresourcetoapplythisfilter
OR
<url-pattern>:URLpatternoftheresourcetoapplythisfilterExamplesofFilterMapping<filter-mapping> <filter-name>Logger</filter-name> <servlet-name>Prime</servlet-name></filter-mapping><filter-mapping> <filter-name>eTrailer</filter-name> <url-pattern>e.jsp</url-pattern></filter-mapping>ConfiguringFilterChainingIfarequestedwebresourcematchesmultiple<filter-mapping>elementsinweb.xml,thematchedfilterswillformachainforthewebresource.Theorderofthefiltersinthechainisdeterminedbythefollowingrules:First,getfiltersthatmatchurl-patternelementofrequestedWebresourceSecond,getfiltersthatmatchservlet-nameelementofrequestedWebresourceIneachcase,thefilter’sorderinthechainisdeterminedbyitsorderinweb.xmlLastfilterinchaininvokestherequestedWebresourceExampleofConfiguringFilterChaining<filter-mapping>
<filter-name>FormChecker</filter-name>
<servlet-name>Prime</servlet-name></filter-mapping><filter-mapping>
<filter-name>Logger</filter-name>
<url-mapping>/*</url-mapping></filter-mapping><filter-mapping>
<filter-name>PrimeTrailer</filter-name>
<servlet-name>Prime</servlet-name></filter-mapping>Theorderofthefilters
fortheServlet‘Prime’?
(1)Logger (2)FormChecker (3)PrimeTrailerConfiguringFiltersforReuseFiltersaredesignedtobereusablecomponentsSameimplementationclasscanbeusedfordifferentfiltersDifferentfilter-nameelementPossiblydifferentinit-paramelementContainerinstantiatesaninstanceoftheclassforeach<filter>elementExampleofConfiguringFilterReuse<filter> <filter-name>eTrailer</filter-name> <filter-class>com.ibm.filters.Trailer</filter-class> <init-param> <param-name>msg</param-name> <param-value>WatchforournewWebSite!</param-value> </init-param></filter><filter><filter-name>DatabaseTrailer</filter-name> <filter-class>com.ibm.filters.Trailer</filter-class> <init-param> <param-name>msg</param-name> <param-value>Sorry,butthedatabaseiscurrentlydown.</param-value> </init-param></filter>ConfiguringFiltersfordifferenttypes
ofrequests(1)TherequestforaWebresourcecancomedirectlyfromclientorfromanotherservletbyinvokingforwarding,including,orsenderrormethods.Afiltercanbeconfiguredtofiltercertaintypesofrequest.Forward/IncludeFiltersWebResourceFiltersRequestResponseWebResourceConfiguringFiltersfordifferenttypes
ofrequests(2)New<dispatcher>elementintheDeploymentDescriptor:REQUESTfilterifrequestisdirectlyfromaclientFORWARDfilterifrequestisfromRequestDispatcher.forward()methodINCLUDEfilterifrequestisfromRequestDispatcher.include()methodERRORfilterifrequestisduetoerrorredirectionmechanismREQUESTisthedefaultwhenno<dispatcher>element<filter-mapping><filter-name>CustomerFilter</filter-name><url-pattern>/customers/*</url-pattern><dispatcher>FORWARD</dispatcher><dispatcher>REQUEST</dispatcher></filter-mapping><filter-mapping><filter-name>AccountFilter</filter-name><servlet-name>CustomerServlet</servlet-name><dispatcher>INCLUDE</dispatcher></filter-mapping>FilterCodeExamplesExampleFilters:web/bookstore1OrderFilter:Afiltertologtheorderrequestforabook.HitCounterFilter:AfilterthatappendsavisitorcountmessagetotheendofWebresource’sresponsepageExample1:OrderFilterFunctions:LogthetotalnumberofordersLogthetimetoreceivetheorderslogtheorderrequestsofthecurrentcustomerOrderFilter:ConfiguredinWeb.xml<filter><filter-name>OrderFilter</filter-name><filter-class>com.sun.bookstore1.filters.OrderFilter</filter-class></filter>
<filter-mapping><filter-name>OrderFilter</filter-name><servlet-name>ReceiptServlet</servlet-name></filter-mapping>ThiscanbeeasilyconfiguredbyusingNetbeans.OrderFilter:init()anddestroy()MethodsOrderFilter:doFilter()MethodExample2:HitCounterFilterFunctions:AppendsavisitorcountmessagetotheendofWebresource’sresponsepageHitCounterFilter:DeploymentDescriptor<filter><filter-name>HitCounterFilter</filter-name><filter-class> com.sun.bookstore1.filters.HitCounterFilter </filter-class></filter>
<filter-mapping><filter-name>HitCounterFilter</filter-name><servlet-name>BookStoreServlet</servlet-name></filter-mapping>HitCounterFilter:doFilter()Method……Wrapper(包裝器)模式UnitSummaryServletfiltersprovidepluggable,configurableservicestoservletsFiltersareimplementationsofthejavax.servlet.FilterinterfaceFiltersareconfiguredthroughentriesintheweb.xmlFilterdescription(implementationclass,name)FiltermappingFilterchainingFiltersmayusewrappedresponseandrequestobjectstopresentcustomversionsoftheseobjectstothefilteredresourcesOutlinesAdvancetopic:RedirectanderrorsendingRequestdispatchingSharingobjectFilteringListenerBasicConceptsofServletEventListenersWhatisaServletEventListener?AclassthatcanlistenandreacttocertaintypesofeventsandstatechangesinaWebapplicationAllowsdevelopersto:LetListenerobjectslistenforWebmodulestatechanges:ServletContext
lifecycle:CreationanddestructionServletContext
attributes:Addition,replacement,andremovalHttpSession
lifecycle:CreationanddestructionHttpSession
attributes:Addition,replacement,andremovalServletRequest
lifecycle:CreationanddestructionServletRequest
attributes:Addition,replacement,andremovalExecuteactionsinresponsetotheeventsAdvantages:CentralizedmonitoringandresponsetoeventsExamplesofServletListenerUseExamples:MonitorstartandstopofWebmodulestoperformstartupandshutdowntasksMonitorcreationanddestructionofsessionsLogimportantapplicationeventsAddattributestoServletContextorHttpSessionobjectsoncreationAdetailedScenario:Whenapplicationstarts,listenerisnotifiedandcreatesaconnectiontothedatabase.ConnectionisstoredinservletcontextattributeServletsaccesstheconnectionasneededfromtheservletcontextWhentheWebapplicationisshutdown,listenerisnotifiedandclosesdatabaseconnectionHowtoCreateaServletListenerCreateaclasstheimplementsatleastoneofthesixlistenerinterfacesServletContextListenerServletContextAttributesListenerHttpSessionListenerHttpSessionAttributesListenerServletRequestListenerServletRequestAttributesListenerOverridemethodsintheinterfaceMethodscorrespondtospecificeventsCodelogictorespondtoeventsAddthelistenertotheWebDeploymentDescriptor-web.xml.A<listener>elementdefinesthelisteneroruseNetbeanstoconfigureitSelectingServletListenerInterfacesSelectthelistenerinterfacestoimplementaccordingtotheobjectsandactionstomonitorObjectActionsInterfaceServletContextCreateDestroyjavax.servlet.ServletContextListenerServletContextAddattributeRemoveattributeReplaceattributejavax.servlet.ServletContextAttributesListenerHttpSessionCreateDestroyjavax.servlet.http.HttpSessionListenerHttpSessionAddattributeRemoveattributeReplaceattributejavax.servlet.http.HttpSessionAttributesListenerServletRequestCreateDestroyjavax.servlet.ServletRequestListenerServletRequestAddattributeRemoveattributeReplaceattributejavax.servlet.ServletRequestAttributesListenerSelectingMethodsforServletContextEvents
Tomonitorlifecycleevents(ServletContextListener
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年高職(鋼結(jié)構(gòu)工程技術(shù))鋼結(jié)構(gòu)工程施工試題及答案
- 2025年高職食品營養(yǎng)與檢測(營養(yǎng)配餐設(shè)計)試題及答案
- 2025年本科云計算與大數(shù)據(jù)技術(shù)(云計算架構(gòu)設(shè)計)試題及答案
- 2025年大學(xué)城市軌道交通工程技術(shù)(城軌工程設(shè)計)試題及答案
- 2025年高職臨床醫(yī)學(xué)基礎(chǔ)(臨床基礎(chǔ)理論)試題及答案
- 內(nèi)墻施工方案八局-中國建設(shè)銀行濟(jì)南分行濼源大街辦公樓裝修改造項目
- 河北省秦皇島市2025年八年級上學(xué)期期末考試物理試題附答案
- 近七年北京中考語文試題及答案2025
- 2026年汕頭招商局港口集團(tuán)有限公司招聘備考題庫參考答案詳解
- 養(yǎng)老院老人生活設(shè)施定期檢查制度
- 江西省贛州市2023-2024學(xué)年高三上學(xué)期期末考試化學(xué)試卷 附答案
- 國家職業(yè)技術(shù)技能標(biāo)準(zhǔn) 4-04-05-05 人工智能訓(xùn)練師 人社廳發(fā)202181號
- 嵌入式系統(tǒng)實現(xiàn)與創(chuàng)新應(yīng)用智慧樹知到期末考試答案章節(jié)答案2024年山東大學(xué)
- 無人機(jī)測試與評估標(biāo)準(zhǔn)
- 線纜及線束組件檢驗標(biāo)準(zhǔn)
- 人工智能在金融策略中的應(yīng)用
- 加工中心點檢表
- 水庫清淤工程可行性研究報告
- THBFIA 0004-2020 紅棗制品標(biāo)準(zhǔn)
- GB/T 25630-2010透平壓縮機(jī)性能試驗規(guī)程
評論
0/150
提交評論