dayjavaweb之文件和課件so easy系列servlet教程_第1頁
dayjavaweb之文件和課件so easy系列servlet教程_第2頁
dayjavaweb之文件和課件so easy系列servlet教程_第3頁
dayjavaweb之文件和課件so easy系列servlet教程_第4頁
dayjavaweb之文件和課件so easy系列servlet教程_第5頁
已閱讀5頁,還剩37頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

SoEasy列ServletServlet介1.1.百ServletJavaappletJavaapplet用Java編程語言實(shí)現(xiàn)。在通信量大的服務(wù)器上,Javaservlet的優(yōu)點(diǎn)在于它們的執(zhí)行速度更快于CGI1.2.百AppletServletServletServletServletHTTPWebServletJavaSoftJavaWebServerJavaServlet什么Servlet的某些方法來完成整個(gè)處理過程的。ServletTomcatServlet容器Servlet是不用程序指定調(diào)用的。Web程序報(bào)錯(cuò)。JavaEETomcatServlet\JSP版JavaEE版Java運(yùn)行環(huán)Servlet2.3\JSPJavaEEJDKServlet2.4\JSPJavaEEJDKServlet2.5\JSPJavaEEJDKServlet3.0\JSPJavaEEJDK如果使用Tomcat服務(wù)器的高版本時(shí),可以向下兼容Servlet\JSP、JavaEE及Java運(yùn)行環(huán)境的版本。Servlet2.5JavaEEJavaEE5.0在Tomcat服務(wù)器與JavaEE中,分別提供了有關(guān)Servlet的幫助文檔信息。如果在Tomcat服務(wù)器中查看Servlet的相關(guān)信息在Tomcat服務(wù)器的安裝中,webapps 中的docs API幫助文檔。JavaEE提供了幫助文檔,TomcatServlet2.5版本的幫助文檔。編寫一Eclipse創(chuàng)建開發(fā)工具Eclipse或MyEclipse本身提供了創(chuàng)建Servlet的功能下面我們首先利用開發(fā)工具來創(chuàng)建Servlet,具體步驟如下:Web在Web工程的 下,鼠標(biāo)“New”選項(xiàng),選擇“Servlet”選項(xiàng)ServletServletServletServlet的包名、名稱及相關(guān)方法后,點(diǎn)擊“NextServletweb.xmlServlet/JSPClassName:ServletServlet/JSPName:ServletServlet/JSPMapURL:配置Servlet的路徑,客戶端通過該路徑ServletFilePathofweb.xmlweb.xmlDisyName:顯示名稱配置完畢之后,點(diǎn)擊“FinishServlet創(chuàng)建完成之后,當(dāng)前Web工程的變化是在 下多了一個(gè)Servlet的Java文件,在WEB-web.xmlServlet相關(guān)配置信息。ServletJava文件內(nèi)容:publicclassFirstServletextendsHttpServletpublicvoidinit()throwsServletExceptionpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{PrintWriterout=response.getWriter();out.println("<!DOCTYPEHTML>");out.println("<HEAD><TITLE>AServlet</TITLE></HEAD>");out.println("<BODY>");out.println(" Thisis"+this.getClass()+",usingtheGETout.println("</BODY>");}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{PrintWriterout=response.getWriter();out.println("<!DOCTYPEHTML>");out.println("<HEAD><TITLE>AServlet</TITLE></HEAD>");out.println("<BODY>");out.println(" Thisis"+this.getClass()+",usingtheGETout.println("</BODY>");}publicvoiddestroy()}Webweb.xml<?xmlversion="1.0"encoding="UTF-<web-app <description>ThisisthedescriptionofmyJ2EE y-name>Thisisthedis ynameofmyJ2EE 將當(dāng)前Web應(yīng)用程序發(fā)布到Tomcat服務(wù)器,并啟動(dòng)Tomcat服務(wù)器運(yùn)試當(dāng)前創(chuàng)建的EclipseMyEclipseWebTomcatTomcat,打開瀏覽器在地址欄中輸入servlet/servlet/FirstServlet服務(wù)器Servlet內(nèi)容。,Servlet手動(dòng)編寫一個(gè)ServletHttpServletServletJavapublicpublicclassSecondServletextendsHttpServlet{publicvoidinit(throwsServletException}protectedvoiddoGet(HttpServletRequestreq,HttpServletResponsethrowsServletExceptionIOException}protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{System.out.println("這是doPost()方法}publicvoidpublicvoiddestroy(){}}web.xml<?<?xmlversion="1.0"encoding="UTF-<web-app"h :用于配置Servlet的名稱和完整路徑servlet- :用于為對(duì)應(yīng)的Servlet設(shè)置名稱servlet- :用于設(shè)置對(duì)應(yīng)的Servlet的完整路徑servlet-servlet-url-:用于配置客戶端請(qǐng)求路徑:用于設(shè)置對(duì)應(yīng)使用的Servlet名稱:路徑相對(duì)路徑絕對(duì)路徑 <<<將當(dāng)前Web應(yīng)用程序發(fā)布到Tomcat服務(wù)器,并啟動(dòng)Tomcat服務(wù)器運(yùn)試當(dāng)前創(chuàng)建的EclipseMyEclipseWebTomcatTomcat打開瀏覽器,在地址欄中輸入servlet/servlet/SecondServlet,服Servlet內(nèi)容。EclipseMyEclipseconsoleServlet的繼承Method req, CalledbytheMethod req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaGET req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaPOST req, ReceivesstandardHTTPrequestsfromthepublicservicemethodanddispatchesthemtothedoXXXmethodsdefinedinthisclass. req, requeststotheprotectedserviceMethodCalledbytheservletcontainertoindicatetoaservletthattheservletisbeingtakenoutAconveniencemethodwhichcanbeoverriddensothatthere'snoneedtoMethodCalledbytheservletcontainertoindicatetoaservletthattheservletisbeingtakenoutAconveniencemethodwhichcanbeoverriddensothatthere'snoneedto req, CalledbytheservletcontainertoallowtheservlettorespondtoaMethodCalledbytheservletMethodCalledbytheservletcontainertoindicatetoaservletthattheservletisbeingtakenoutReturnsaServletConfigobject,whichcontainsinitializationandstartupparametersthisReturnsinformationabouttheservlet,suchasauthor,version,and Calledbytheservletcontainertoindicatetoaservletthattheservletisbeingced req, Calledbytheservletcontainertoallowtheservlettorespondtoa所以,initdestroyServlet接口提供的方法。通過上述的查找,我們已經(jīng)很清晰的知道Servlet的繼承關(guān)系,具體如下圖:Servlet工作流利用Servlet完成的Web應(yīng)用的實(shí)際工作流程是通過Tomcat服務(wù)器發(fā)布服務(wù)客戶端與服務(wù)器端Http協(xié)議完成的。具體工作流程如下:TomcatServletWebweb.xmlServletServletTomcatServlet容器向客戶端瀏覽器進(jìn)行響應(yīng)。Servlet具體的工作流程。Servlet注意事值得注意的是Servlet內(nèi)容是屬于JavaEE內(nèi)容和使用JavaSE內(nèi)容一樣都是需要引入JAR包的。javaee.jarServlet的所有內(nèi)容。WebTomcat服務(wù)器的時(shí)候,發(fā)現(xiàn)對(duì)應(yīng)的中并沒有javaee.jar包。JARTomcatServlet運(yùn)行所需要的環(huán)境。在Tomcat服務(wù)器的安裝 中的lib 供了Servlet運(yùn)行所需的環(huán)境。Servlet 中的 創(chuàng)建Web工程名稱 結(jié)構(gòu)Servlet在對(duì)應(yīng)Web工 中的web.xml進(jìn)行配置深入掌Servlet的生命周一般情況下,自定義Servlet都是繼承HttpServlet。但通過HttpServlet的繼承鏈,我們知道HttpServletServletServletMethodCalledbytheservletcontainertoindicatetoaservletthattheservletisbeingtakenoutReturnsaServletConfigobject,whichcontainsinitializationandstartupparametersthisReturnsinformationabouttheservlet,suchasauthor,version,and Calledbytheservletcontainertoindicatetoaservletthattheservletisbeingced req, Calledbytheservletcontainertoallowtheservlettorespondtoa上述所有方法中,init()、service()destroy()Servlet的生命周期。下面我們分別討論一init()init()Servletinit()方法被正確執(zhí)行。ServletServletdestroy()Servlet實(shí)destroy()ServletServletServletpublicpublicclassLifeServletimplementsServletpublicSystem.out.println("這里創(chuàng)建了一個(gè)Servlet實(shí)例對(duì)象}publicvoidinit(ServletConfigconfigthrowsServletException}publicvoidservice(ServletRequestreq,ServletResponsethrowsServletExceptionIOException}publicvoiddestroy(){}publicServletConfiggetServletConfig()return}publicStringgetServletInfo()return}}web.xmlServlet<?<?xmlversion="1.0"encoding="UTF-<web-app" 九月12,20148:00:41下午org.apache.catalina.core.AprLifecycleListenerINFO:LoadedAPRbasedApacheTomcatNativelibrary1.1.31usingAPRversion九月12,20148:00:41下午org.apache.catalina.core.AprLifecycleListenerINFO:APRcapabilities:IPv6[true],sendfile[true],acceptfilters[false],random九月12,20148:00:42下午org.apache.catalina.core.AprLifecycleListenerinitializeSSLINFO:OpenSSLsuccessfullyinitialized(OpenSSL1.0.1h5Jun2014)九月12,20148:00:42下午org.apache.coyote. ProtocolinitINFO:InitializingProtocolHandler["http-apr-8080"]九月12,20148:00:42下午org.apache.coyote. ProtocolinitINFO:InitializingProtocolHandler["ajp-apr-8009"]九月12,20148:00:42下午org.apache.catalina.startup.CatalinaloadINFO:Initializationprocessedin1417ms九月12,20148:00:42下午org.apache.catalina.core.StandardServicestartInternalINFO:StartingserviceCatalina九月12,20148:00:42下午org.apache.catalina.core.StandardEnginestartInternalINFO:StartingServletEngine:ApacheTomcat/7.0.55九月12,20148:00:43下午org.apache.catalina.startup.HostConfigINFO:DeployingwebapplicationdirectoryC:\Tools\apache-tomcat-九月12,20148:00:43下午org.apache.catalina.startup.HostConfigINFO:DeploymentofwebapplicationdirectoryC:\Tools\apache-tomcat-7.0.55\webapps\08_servlethasfinishedin377ms九月12,20148:00:44下午org.apache.catalina.startup.CatalinaINFO:Serverstartupin1766ServletServletServletservice()方法來處理請(qǐng)求。第二次向Servletservice()Servletinit()方法。在停止Tomcat服務(wù)器時(shí),Servletdestroy()方法被調(diào)用,釋放所使用的資源。Servlet的線程安在Servlet的整個(gè)生命周期中構(gòu)造方法只被執(zhí)行一次也就是說Servlet的整個(gè)生命周期中,ServletServlet是單例多線程的,可能會(huì)引起線程安全問題。所謂線程安全就是一個(gè)Servlet實(shí)例對(duì)象會(huì)同時(shí)處理多個(gè)請(qǐng)求這樣的Servlet工作效率的確很高。Servlet中包含成員變量的話,可能一個(gè)線程對(duì)該成員變量進(jìn)行寫操作,而另一個(gè)線程對(duì)該成Servlet不能創(chuàng)建成員變量。服務(wù)器啟動(dòng)創(chuàng)建創(chuàng)建一個(gè)Servlet實(shí)例對(duì)象如果可以在Tomcat服務(wù)器啟動(dòng)時(shí)進(jìn)行創(chuàng)建實(shí)例對(duì)象并完成初始化工作,service()方法處理請(qǐng)求邏輯即可。web.xml<?<?xmlversion="1.0"encoding="UTF-<web-app" load-on- :配置當(dāng)前Servlet 中的數(shù)字,表示級(jí)別(0-9級(jí)),一般設(shè)置為0即可 <<<TomcatServlet實(shí)url-pattern的三種配在web.xml配置文件中配置有關(guān)Servlet的時(shí)候,<url-pattern>是用于配置當(dāng)前Servlet的路徑,也就是說,客戶端瀏覽器<url-pattern>配置的路徑才能對(duì)應(yīng)Servlet內(nèi)容。關(guān)于路徑的配置方式其實(shí)有三種方式*問路徑為匹配:是以“/”開始,以“/*”結(jié)尾的,例如:/firstServlet/*,表示路徑路徑下任意內(nèi)容。以多個(gè)不同路徑的。上述三種配置路徑方式具有優(yōu)先級(jí):完全路徑匹配-> 匹配->擴(kuò)展名匹配。Servlet1Servlet2Servlet3Servlet4/abca.html/abc/*/abc/*”和“/abc/*”和“/*”和“/*”和“如果客戶端瀏覽器請(qǐng)求的路徑是錯(cuò)誤時(shí),頁面會(huì)顯示404錯(cuò)誤內(nèi)容。這是因?yàn)樗邪l(fā)布到Tomcat服務(wù)器的Web應(yīng)用程序的web.xmlTomcat服務(wù)器安裝中conf中的web.xml文 相對(duì)路徑與絕對(duì)路個(gè)頁面來Servlet應(yīng)該怎么樣呢?下面我們來看一看:在Web工程中的WebRoot “html, 新的HTML頁面。<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv=" <metahttp-equiv="description"content="thisismy<metahttp-equiv="content-type"content="text/html;<h1>相對(duì)路 <ahref="">相對(duì)路徑<h1>絕對(duì)路徑<ahref="">絕對(duì)路徑在Web工程中的 下,創(chuàng)建一個(gè)新的HTML頁面<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-"<metahttp-equiv="description"content="thisismy<metahttp-equiv="content-type"content="text/html;<h1>相對(duì)路 <ahref="">相對(duì)路 <h1>絕對(duì)路 <ahref="">絕對(duì)路 WebServletpublicpublicclassPathServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{到}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doGet(request,}}Webweb.xml<?<?xmlversion="1.0"encoding="UTF-<web-app" <<<打開瀏覽器,分別01.html、02.html和PathServlet 01.html的路徑:servlet/html/01.html。 02.html的路徑:servlet/02.html。 PathServlet的路徑:servlet/pathServlet。根據(jù)上述的路徑,可以知道在01.html和02.html頁面中,通過絕對(duì)路徑在01.html和02.html頁面中,通過相對(duì)路徑PathServlet是不同的在01.html頁面中利用相對(duì)路徑PathServlet應(yīng)該是../pathServlet。原因是是在01.html頁面的父 中<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv=" <metahttp-equiv="description"content="thisismy<metahttp-equiv="content-type"content="text/html;<h1>相對(duì)路徑<ahref="../pathServlet">相對(duì)路徑<h1>絕對(duì)路 <<a">在01.html頁面中利用相對(duì)路徑PathServlet應(yīng)該是./pathServlet或直接名pathServlet。原因是pathServlet與02.html頁面處在同一級(jí)別 中<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv=" <metahttp-equiv="description"content="thisismy<metahttp-equiv="content-type"content="text/html;<h1>相對(duì)路徑<ahref="pathServlet">相對(duì)路 <h1>絕對(duì)路徑<h1>絕對(duì)路<a">絕對(duì)路絕對(duì)路徑:就是無論當(dāng)前資源在什么位置,都能通過當(dāng)前資源到目標(biāo)資源相對(duì)路徑:就是判斷當(dāng)前資源與目標(biāo)資源的相對(duì)位置,找出相對(duì)當(dāng)前資源可以到目標(biāo)資研究掌HttpServlet概在大多數(shù)的Web應(yīng)用程序中,客戶端都是通過Http協(xié)議去服務(wù)器端的資源,而我們編寫的司在javax.servlet.http包中提供了一個(gè)抽象類HttpServlet,它繼承于GenericServlet,用于創(chuàng)建適合基HttpWebServlet。 classHttpServletextendsGenericServletHttpServletMethod req, req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaGET req, ReceivesanHTTPHEADrequestfromtheprotectedservicemethodandhandles req, Calledbytheserver(viatheservicemethod)toallowaservlettohandlea req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaPOST req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaPUT req, Calledbytheserver(viatheservicemethod)toallowaservlettohandleaTRACE ReturnsthetimetheHttpServletRequestobjectwaslastmodified,inmillisecondssincemidnightJanuary1,1970GMT. req, ReceivesstandardHTTPrequestsfromthepublicservicemethodanddispatchesthemtothedoXXXmethodsdefinedinthisclass. req, requeststotheprotectedserviceHttpServlet重寫的service()方HttpServletservice() classHttpServletextendsGenericServlet{publicvoidservice(ServletRequestreq,ServletResponseres)throwsServletException,IOException{HttpServletRequestrequest;HttpServletResponsetryrequest=(HttpServletRequest)req;response=(HttpServletResponse)res;}catch(ClassCastExceptione)thrownewServletException("non-HTTPrequestor}service(request,}protectedvoidservice(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{Stringmethod=if(method.equals(METHOD_GET))longlastModified=getLastModified(req);maybeSetLastModified(resp,lastModified);doGet(req,resp);}elseif(method.equals(METHOD_HEAD)){longlastModified=getLastModified(req);maybeSetLastModified(resp,lastModified);doHead(req,resp);}elseif(method.equals(METHOD_POST)){doPost(req,resp);}elseif(method.equals(METHOD_PUT)){doPut(req,resp);}elseif(method.equals(METHOD_DELETE)){doDelete(req,resp);}elseif(method.equals(METHOD_OPTIONS)){}}elseif(method.equals(METHOD_TRACE)){}elseStringerrMsgObject[]errArgs=newObject[1];errArgs[0]=method;errMsg=MessageFormat.format(errMsg,errArgs);}}}通過查看HttpServletservice()方法是GenericServlet類中的service()方法,對(duì)客戶端的請(qǐng)求進(jìn)行處理。在第二個(gè)service()針對(duì)Http1.1協(xié)議中定義的7種請(qǐng)求方式GetPostHeadPutDelete、TraceOptions7種處理方法。7HttpServlet類中的service()ServletHttpServlet對(duì)象的請(qǐng)求時(shí),調(diào)用該對(duì)service()HttpServletRequestHttpServletResponse,然后service()方法。service()Http請(qǐng)求方法的名字,然后根據(jù)請(qǐng)求方法的類型,調(diào)用響doXXX()方法。因此,我們?cè)谧远xServlet繼承于HttpServlet的時(shí)候,通常不需要重寫service()方法,只需重寫doXXX()方法即可。七種請(qǐng)求處理方HttpServletHttp1.17Get、Post、Head、Put、Delete、TraceOptions7種處理方法:protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoHead(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoPut(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoDelete(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoTrace(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,protectedvoiddoOptions(HttpServletRequestreq,HttpServletResponseresp)throws要重寫doTrace()和doOptions()方法而對(duì)于其他的5種請(qǐng)求處理方法,HttpServlet類提供的實(shí)現(xiàn)都是返回Http錯(cuò)誤。對(duì)于Http1.0的客戶端請(qǐng)求,這些方法返回的狀態(tài)碼為400,表示客戶端發(fā)送的請(qǐng)求寫doGet()和doPost()兩個(gè)請(qǐng)求處理方法。其中doGet()方法用來處理Get方式的請(qǐng)求,doPost()方法用Post方式的請(qǐng)求,下面我們通過一個(gè)案例來看一看:HTML<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv="content-type"content="text/html;<h1>GET方式請(qǐng)求<formid="userinfo"method="get"用戶名:<inputtype="textid="username<inputtype="submitid="submitvalue="提交<h1>POST方式請(qǐng)求<formid="userinfo"method="post"用戶名:<inputtype="textid="username<inputtype="submitid="submitvalue="提交ServletpublicpublicclassThreeServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{System.out.println("這是GET方式發(fā)送的請(qǐng)求,Servlet使用doGet()方法來理}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{System.out.println("這是POST方式發(fā)送的請(qǐng)求,Servlet使用doPost()方法來理}}web.xml<?<?xmlversion="1.0"encoding="UTF-<web-app" <<<打開瀏覽器,在地址欄中輸入servlet/index.html利用GET方式發(fā)送請(qǐng)求,控制臺(tái)會(huì)打印doGet()方法的內(nèi)容。利用POST方式發(fā)送請(qǐng)求,控制臺(tái)會(huì)doPost()方法的內(nèi)容。RequestHttpServlet提供的service()方法與7HttpServletRequest繼承于ServletRequest,是用于處理Http協(xié)議中的請(qǐng)求,一個(gè)是HttpServletResponse繼承于ServletResponseHttp協(xié)議中的響應(yīng)。HttpServletRequestHttpServletResponse研究掌GenericServlet概如果我們直接通過實(shí)現(xiàn)Servlet接口來編寫一個(gè)Servlet類,就需要實(shí)現(xiàn)Servlet接口定義的5種方Servletjavax.servletGenericServlet,該類提供了除ServletServletServletConfig接口。 classGenericServletimplementsServlet,GenericServletMethodCalledbytheservletcontainertoindicatetoaservletthattheservletisbeingtakenoutgReturnsthisservlet'sServletConfigReturnsareferencetotheServletContextinwhichthisservletisAconveniencemethodwhichcanbeoverriddensothatthere'snoneedto Calledbytheservletcontainertoindicatetoaservletthattheservletisbeingced req, Calledbytheservletcontainertoallowtheservlettorespondtoa重寫的init()方ServletGenericServletGenericServletinit()publicvoidinit(ServletConfigconfig)throwspublicvoidinit()throwstransientinit()方法。GenericServletSerlvetinit()方ServletConfig對(duì)javax.servletServletConfig接口。ServletServletConfigServlet初SerlvetWebweb.xmlServlet<?xmlversion="1.0"encoding="UTF-<web-app <description>ThisisthedescriptionofmyJ2EE y-name>Thisisthedis ynameofmyJ2EE GenericServletinit(ServletConfigconfig)ServletConfigpublicpublicclassConfigServletextendsGenericServletprivateServletConfigpublicvoidinit(ServletConfigconfig)throwsServletExceptionthis.config=}publicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException}}ServletConfigServletConfigservletConfig=ServletConfigMethod ReturnsaStringcontainingthevalueofthenamedinitializationparameter,ornulliftheparameterdoesnotexist.Returnsthenamesoftheservlet'sinitializationparametersasanEnumerationStringobjects,oranemptyEnumerationiftheservlethasnoinitializationtReturnsareferencetotheServletContextinwhichthecallerisReturnsthenameofthisservletgetServletName()web.xmlServletServletConfiggetServletName()publicpublicvoidservice(ServletRequestreq,ServletResponsethrowsthrowsServletException,IOException{ServletConfigservletConfig=getServletConfig();StringservletName=servletConfig.getServletName();}ConfigServletnull值。web.xmlServlet<?<?xmlversion="1.0"encoding="UTF-<web-app" Servletservice()publicpublicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException{ServletConfigservletConfig=getServletConfig();Stringname=servletConfig.getInitParameter("name");Stringblog=servletConfig.getInitParameter("blog");System.out.println(name+"'sblogis"+blog);}運(yùn)行Web應(yīng)用程序,在控制臺(tái)中打印“jyl'sblogis Enumeration是 tor的前身,用法與 tor一致publicpublicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException{ServletConfigservletConfig=getServletConfig();Enumerationenumeration=while(enumeration.hasMoreElements())Stringelement=(String)enumeration.nex Stringvalue=servletConfig.getInitParameter(element);System.out.println(element+":"+value);}}Webname:jylblog:http://wServletConfigstruts1ServletConfig<!--<!--StandardActionServletConfiguration(withdebugging)--<servlet-name>action</servlet-<servlet-class>org.apache.struts.action.ActionServlet</servlet-<init-<param-name>config</param-<param-/WEB-INF/struts-/WEB-INF/struts-config-</param-</init-<load-on-startup>2</load-on-<!--StandardActionServlet --<servlet- <servlet-name>action</servlet-<url-pattern>*.do</url-</servlet- ServletContext對(duì)ServletContext概ServletContextServletWebServletContext象,該對(duì)象是Web應(yīng)用程序的全局對(duì)象或者上下文。Tomcat服務(wù)器在啟動(dòng)時(shí),會(huì)自動(dòng)創(chuàng)建一個(gè)ServletContext對(duì)象,ServletContextWeb應(yīng)用中共享數(shù)據(jù)資源。ServletContextMethod Returnstheservletcontainerattributewiththegivenname,ornullifthereisnoattributebythatname.ReturnsanEnumerationcontainingtheattributenamesavailablewithinthis ReturnsaStringcontainingthevalueofthenamedcontext-wideinitializationparameter,ornulliftheparameterdoesnotexist.Returnsthenamesofthecontext'sinitializationparametersasanEnumerationStringobjects,oranemptyEnumerationifthecontexthasnoinitialization ReturnstheMIMEtypeofthespecifiedfile,ornulliftheMIMEtypeisnot ReturnsaStringcontainingtherealpathforagivenvirtualReturnsthenameofthiswebapplicationcorrespondingtothisServletContextspecifiedinthedeploymentdescriptorforthiswebapplicationbythedisy-nameDeprecated.AsofJavaServletAPI2.1,withnore Writesthespecifiedmessagetoaservletlogfile,usuallyanevent Removestheattributewiththegivennamefromtheservlet name, BindsanobjecttoagivenattributenameinthisservletServletServletContext通過繼承GenericServlet類或HttpServlet類,調(diào)用GenericServlet類或HttpServlet類的ServletServletContextpublicpublicclassAServletextendsGenericServlet{publicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException{ServletConfigconfig=getServletConfig();ServletContextcontext1=config.getServletContext();ServletContextcontext2=getServletContext();context2.log("這是通過繼承GenericServlet類獲取到的ServletContext對(duì)象}}web.xmlServlet<?<?xmlversion="1.0"encoding="UTF-<web-app" ServletContextlog(Stirngmsg)配置全局初始化參在web.xml<init-param>Servlet是無權(quán)限當(dāng)前Servlet下配置的初始化參數(shù)的。而可以使用ServletContext在web.xml文件中配置全局初始化參數(shù),這樣當(dāng)前Web應(yīng)用程序中的所有Servlet都可以。<?xmlversion="1.0"encoding="UTF-<web-app ServletServletContextpublicpublicclassBServletextendsGenericServlet{publicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException{ServletContextcontext=getServletContext();Stringweixin=context.getInitParameter("weixin");}}打開瀏覽器,在地址欄中分別輸入servlet/servlet/AServlet和servlet/servlet/BServlet,在控制臺(tái)打印相關(guān)信息。ervltervltCottInitaamerStringe)ervltCottInitaamerName方法獲取所有全局初始化參數(shù)的名稱。ServletContextgetMineType(Stringfile)MIME類publicpublicclassBServletextendsGenericServlet{publicvoidservice(ServletRequestreq,ServletResponsethrowsServletException,IOException{ServletContextcontext=getServletContext();Stringhtml=context.getMimeType("1.html");Stringcss=context.getMimeType("2.css");Stringjavascript=context.getMimeType("3.js");System.out.println("HTML的文件類型為"+html+CSS的文件類型為"+css+",}}HTMLHTML的擴(kuò)展名為text/htmlCSS的擴(kuò)展名為text/cssjavascript的擴(kuò)展名為ServletContext對(duì)象的getMineType(Stringfile)方自動(dòng)Tomcat安 中 中web.xml<?<?xmlversion="1.0"encoding="UTF-<web-app" > Servlet共享數(shù)在同一個(gè)Web應(yīng)用程序中,多個(gè)Servlet之間可以共享ServletContext對(duì)象中的數(shù)據(jù)信息。主要是通過ServletContext對(duì)象的setAttribute(Stringname,Objectobject)方法和getAttribute(Stringname)方法創(chuàng)建一個(gè)VisitServlet用來獲取次數(shù),并在ServletContext對(duì)象中publicclassVisitServletextendsHttpServlet{publicvoidinit()throwsServletException{ServletContextcontext=getServletContext();context.setAttribute("times",0);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ServletContextcontext=inttimes=(Integer)context.getAttribute("times");times++;context.setAttribute("times",}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doGet(request,}}創(chuàng)建一個(gè)ShowTimeServlet用來顯示次數(shù)publicpublicclassShowTimeServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ServletContextcontext=inttimes=PrintWriterout=response.getWriter(); }publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doGet(request,}}web.xmlSe

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論