版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
4636a實(shí)驗(yàn)8Servlet過濾器與監(jiān)聽器第一局部Servlet過濾器一、實(shí)驗(yàn)?zāi)康?.了解過濾器的作用;2.掌握過濾器的開發(fā)與部署的步驟;3.了解過濾器鏈。二、實(shí)驗(yàn)原理過濾器是web效勞器上的組件,它們對(duì)客戶和資源之間的請(qǐng)求和響應(yīng)進(jìn)行過濾。過濾器的工作原理是:當(dāng)servlet容器接收到對(duì)某個(gè)資源的請(qǐng)求,它要檢查是否有過濾器與之關(guān)聯(lián)。如果有過濾器與該資源關(guān)聯(lián),servlet容器將把該請(qǐng)求發(fā)送給過濾器。在過濾器處理完請(qǐng)求后,它將做下面3件事:產(chǎn)生響應(yīng)并將其返回給客戶;如果有過濾器鏈,它將把〔修改正或沒有修改正〕請(qǐng)求傳遞給下一個(gè)過濾器;將請(qǐng)求傳遞給不同的資源。當(dāng)請(qǐng)求返回到客戶時(shí),它是以相反的方向經(jīng)過同一組過濾器返回。過濾器鏈中的每個(gè)過濾器夠可能修改響應(yīng)。過濾器API主要包括:Filter、FilterConfig和FilterChain接口。三、實(shí)驗(yàn)內(nèi)容與步驟〔一〕編寫一個(gè)過濾器審計(jì)用戶對(duì)資源的訪問?!静襟E1】該過濾器實(shí)現(xiàn)的功能是,當(dāng)用戶訪問應(yīng)用程序任何資源時(shí),將用戶的IP地址和主機(jī)名寫入日志文件中,過濾器代碼如下:packagefilter;importjava.io.IOException;importjavax.servlet.*;importjavax.servlet..*;publicclassAuditFilterimplementsFilter{ protectedFilterConfigconfig;publicvoidinit(FilterConfigfilterConfig) throwsServletException{ this.config=filterConfig; } publicvoiddoFilter(ServletRequestrequest, ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ServletRequestreq=(ServletRequest)request; ServletResponseres=(ServletResponse)response; Stringaddr=req.getRemoteAddr(); Stringuser=req.getRemoteHost();config.getServletContext().log("RemoteAddress:"+addr+",RemoteHost:"+user);chain.doFilter(req,res); } publicvoiddestroy(){ }}【步驟2】配置過濾器。在部署描述文件web.xml中配置過濾器:<filter><filter-name>AuditFilter</filter-name><filter-class>filter.AuditFilter</filter-class></filter><filter-mapping><filter-name>AuditFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>上述代碼中過濾器映射使用的URL模式為/*,這表示將該過濾器映射到Web應(yīng)用程序的任何資源。如果只對(duì)某些資源〔如JSP頁面審計(jì),那么可以指定具體的資源〕?!静襟E3】訪問該應(yīng)用程序中的任何一個(gè)資源,如使用下面的URL訪問onlineCount.jsp:://localhost:8080/helloapp/onlineCount.jsp然后翻開<CATALINA_HOME>\logs目錄中的localhost.2006-02-05.log文件中有下面一行〔訪問多個(gè)資源就會(huì)有多行〕:〔二〕編寫一個(gè)過濾器改變請(qǐng)求編碼?!静襟E1】編寫一個(gè)loginform.html文件,代碼如下:<html><head><title>使用過濾器改變請(qǐng)求編碼</title><meta-equiv="Content-Type"content="text/html;charset=GB2312"></head><body><center><h2>請(qǐng)輸入用戶名和口令:</h2><formmethod="post"action="servlet/check"> <table> <tr> <td>用戶名:</td> <td><inputname="name"type="text"></td> </tr> <tr> <td>口令:</td> <td><inputname="pass"type="password"></td> </tr> <tr> <td></td><td><inputname="ok"type="submit"value="提交"><inputname="cancel"type="reset"value="重置"></td> </tr> </table></form></center></body></html>【步驟2】編寫處理請(qǐng)求參數(shù)的Servlet,代碼如下:importjava.io.*;importjavax.servlet.*;importjavax.servlet..*;publicclassCheckParamServletextendsServlet{publicvoiddoGet(ServletRequestrequest,ServletResponseresponse)throwsServletException,IOException{Stringname=request.getParameter("name");Stringpass=request.getParameter("pass");response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();out.println("<html><head><title>ParamTest</title></head>");out.println("<h3align=center>你的用戶名為:"+name+"</h3>");out.println("<h3align=center>你的口令為:"+pass+"</h3>");out.println("</body></html>");}publicvoiddoPost(ServletRequestrequest,ServletResponseresponse)throwsServletException,IOException{doGet(request,response);}}【步驟3】修改web.xml文件,參加下面代碼:<servlet><servlet-name>CheckParamServlet</servlet-name><servlet-class>CheckParamServlet</servlet-class></servlet><servlet-mapping><servlet-name>CheckParamServlet</servlet-name><url-pattern>/servlet/check</url-pattern></servlet-mapping>【步驟4】在瀏覽器的地址欄中輸入下面URL:://localhost:8080/helloapp/loginform.html輸入用戶名和口令,如下列圖所示:loginform.html頁面的運(yùn)行結(jié)果然后點(diǎn)擊“提交〞按鈕,經(jīng)CheckParamServlet處理后返回的結(jié)果如下列圖所示::CheckParamServlet程序的運(yùn)行結(jié)果從這里我們可以看到,從效勞器返回的漢字成了亂碼。原因是沒有指定request的編碼。下面通過編寫一個(gè)過濾器改變請(qǐng)求編碼。【步驟5】過濾器代碼如下:packagefilter;importjava.io.IOException;importjavax.servlet.*;publicclassEncodingFilterimplementsFilter{ protectedStringencoding=null; protectedFilterConfigconfig; publicvoidinit(FilterConfigfilterConfig)throwsServletException{ this.config=filterConfig; //得到在web.xml中配置的編碼 this.encoding=filterConfig.getInitParameter("Encoding"); } publicvoiddoFilter( ServletRequestrequest, ServletResponseresponse, FilterChainchain) throwsIOException,ServletException{ if(request.getCharacterEncoding()==null){ //得到指定的編碼 Stringencode=getEncoding(); if(encode!=null){ //設(shè)置request的編碼 request.setCharacterEncoding(encode); response.setCharacterEncoding(encode); } } chain.doFilter(request,response); } protectedStringgetEncoding(){ returnencoding; } publicvoiddestroy(){ }}【步驟6】在web.xml文件中配置過濾器,參加下面代碼:<filter><filter-name>EncodingFilter</filter-name><filter-class>filter.EncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>gb2312</param-value></init-param></filter><filter-mapping><filter-name>EncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>【步驟7】重復(fù)第〔4〕步操作,結(jié)果如下:EncodingFilter程序的運(yùn)行結(jié)果四、思考題1.試簡(jiǎn)述過濾器有哪些功能?2.如何理解過濾器鏈。第二局部Servlet監(jiān)聽器一、實(shí)驗(yàn)?zāi)康?.了解在哪些對(duì)象上可以產(chǎn)生事件;2.掌握ServletContext和Session對(duì)象上的事件處理方法。3.了解在ServletRequest對(duì)象上的事件及處理方法。二、實(shí)驗(yàn)原理在Web應(yīng)用程序中,事件的處理也是通過事件監(jiān)聽器接口處理的。Web應(yīng)用事件處理的原理為:當(dāng)Web應(yīng)用中某些狀態(tài)改變時(shí),Servlet容器就產(chǎn)生某種事件,如ServletContext對(duì)象初始化時(shí)會(huì)產(chǎn)生ServletContextEvent事件,此時(shí)Servlet容器就會(huì)從注冊(cè)的事件監(jiān)聽器中尋找處理該事件的監(jiān)聽器對(duì)象,并執(zhí)行相應(yīng)的代碼。在Servlet2.4標(biāo)準(zhǔn)中共定義了6種事件類型和8個(gè)事件監(jiān)聽器接口,它們可以處理三種對(duì)象上的事件,如表13.1所示:監(jiān)聽器接口與事件類監(jiān)聽對(duì)象監(jiān)聽器接口監(jiān)聽事件ServletContextServletContextListenerServletContextEventServletContextAttributeListenerServletContextAttributeEventSessionSessionListenerSessionEventSessionActivationListenerSessionAttributeListenerSessionBindingEventSessionBindingListenerServletRequestServletRequestListenerServletRequestEventServletRequestAttributeListenerServletRequestAttributeEvent三、實(shí)驗(yàn)內(nèi)容與步驟〔一〕編寫一個(gè)ServletContext事件監(jiān)聽器。該事件監(jiān)聽器的功能是當(dāng)Web應(yīng)用程序初始化和銷毀時(shí)以及在ServletContext對(duì)象上添加屬性、刪除屬性和替換屬性時(shí),在Tomcat日志中記錄有關(guān)信息。【步驟1】編寫監(jiān)聽器類packagelistener;importjava.io.*;importjava.util.Date;importjavax.servlet.*;publicfinalclassMyServletContextListenerimplementsServletContextListener,ServletContextAttributeListener{privateServletContextcontext=null;publicvoidcontextInitialized(ServletContextEventsce){ context=sce.getServletContext(); context.log("應(yīng)用程序已啟動(dòng):"+newDate());}publicvoidcontextDestroyed(ServletContextEventsce){ context=sce.getServletContext(); context.log("應(yīng)用程序已關(guān)閉:"+newDate());}publicvoidattributeAdded(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("添加一個(gè)屬性:"+sce.getName()+":"+sce.getValue());}publicvoidattributeRemoved(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("刪除一個(gè)屬性:"+sce.getName()+":"+sce.getValue());}publicvoidattributeReplaced(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("替換一個(gè)屬性:"+sce.getName()+":"+sce.getValue());}}【步驟2】注冊(cè)監(jiān)聽器類。修改web.xml文件,參加下面代碼:<listener><listener-class>listener.MyServletContextListener</listener-class></listener>【步驟3】編寫一個(gè)測(cè)試Servlet。importjava.io.*;importjava.util.Date;importjavax.servlet.*;importjavax.servlet..*;publicclassEventTestServletextendsServlet{ServletContextcontext=null;publicvoidinit(){ context=getServletConfig().getServletContext();}publicvoiddoGet(ServletRequestrequest,ServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html");PrintWriterout=response.getWriter();out.println("<html><head><title>EventTest</title></head>");IntegeranInteger=newInteger(100);DateaDate=newDate();context.setAttribute("obj",anInteger);//添加屬性context.setAttribute("obj",aDate);//替換屬性context.removeAttribute("obj");//刪除屬性out.println("<h3align=center>"+"已在ServletContext對(duì)象上添加、替換和刪除了屬性</h3>");out.println("</body></html>");out.close();}}【步驟4】修改web.xml,參加下面代碼:<servlet><servlet-name>EventTestServlet</servlet-name><servlet-class>EventTestServlet</servlet-class></servlet><servlet-mapping><servlet-name>EventTestServlet</servlet-name><url-pattern>/eventtest</url-pattern></servlet-mapping>【步驟5】重新啟動(dòng)Tomcat,然后使用下面URL訪問EventTestServlet:://localhost:8080/helloapp/eventtest顯示界面如下:EventTestServlet程序的運(yùn)行結(jié)果【步驟6】檢查日志文件翻開<CATALINA_HOME>\logs目錄中的localhost.2006-02-05.log日志文件〔你的文件名可能與此不同〕,在其中可以找到下面這些行:信息:應(yīng)用程序已關(guān)閉:SunFeb0512:42:33CST2006信息:應(yīng)用程序已啟動(dòng):SunFeb0512:42:57CST2006信息:添加一個(gè)屬性:obj:100信息:替換一個(gè)屬性:obj:100信息:刪除一個(gè)屬性:obj:SunFeb0512:43:30CST2006這些信息就是執(zhí)行事件監(jiān)聽器后寫到日志文件中的?!捕尘帉懸粋€(gè)Session事件監(jiān)聽器用來記錄當(dāng)前在線人數(shù)?!静襟E1】編寫SessionListener監(jiān)聽器類packagelistener;importjavax.servlet..SessionEvent;importjavax.servlet..SessionListener;publicfinalclassMySessionListenerimplementsSessionListener{privateintcount=0;publicvoidsessionCreated(SessionEventse){count++;se.getSession().getServletContext().setAttribute("onlineCount",newInteger(count)); }publicvoidsessionDestroyed(SessionEventse){ count--; se.getSession().getServletContext().setAttribute("onlineCount",newInteger(count)); }}【步驟2】注冊(cè)事件監(jiān)聽器,在web.xml文件中參加下面代碼:<listener><listener-class>listener.MySessionListener</listener-class></listener>【步驟3】編寫一個(gè)測(cè)試Servlet,如下所示:importjava.io.*;importjavax.servlet.*;importjavax.servlet..*;publicclassOnlineCountServletextendsServlet{publicvoiddoGet(ServletRequestrequest,ServletResponseresponse)throwsServletException,IOException{Sessionsession=request.getSession(true);ServletContextcontext=getServletConfig().getServletContext();Integercount=(Integer)context.getAttribute("onlineCount");response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();out.println("<html><head><title>SessionEventTest</title></head>");out.println("<h3align=center><fontcolor=\"#ff0000\">"+"當(dāng)前在線人數(shù):"+count+"</h3>");out.println("</body></html>");out.close();}}【步驟4】修改web.xml文件,參加下面代碼:<servlet><servlet-name>OnlineCountServlet</servlet-name><servlet-class>OnlineCountServlet</servlet-class></servlet><servlet-mapping><servlet-name>OnlineCountServlet</servlet-name><url-pattern>/online</url-pattern></servlet-mapping>【步驟5】使用下面URL訪問OnlineCountServlet:://localhost:8080/helloapp/online再啟動(dòng)兩個(gè)瀏覽器窗口訪問該Servlet,計(jì)數(shù)器就會(huì)增加,而點(diǎn)擊瀏覽器的“刷新〞按鈕,計(jì)數(shù)器不會(huì)增加〔因?yàn)闆]有開始新會(huì)話〕。On
溫馨提示
- 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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 福建省福州市九校聯(lián)考2025-2026學(xué)年七年級(jí)上學(xué)期期中語文試題(含答案)(含解析)
- 2026年行政人員職業(yè)素養(yǎng)進(jìn)階培訓(xùn)
- 2026福建中醫(yī)藥大學(xué)附屬人民醫(yī)院招聘非在編合同制人員40人備考題庫(一)完整參考答案詳解
- 城市公共停車場(chǎng)管理手冊(cè)
- 2026年農(nóng)業(yè)科技創(chuàng)新成果轉(zhuǎn)化路徑
- 職業(yè)噪聲與心血管疾病精準(zhǔn)預(yù)防策略
- 口腔種植技術(shù)年終總結(jié)(3篇)
- 2022~2023初級(jí)護(hù)師考試題庫及答案第653期
- 中國北京科學(xué)院科技戰(zhàn)略咨詢研究院2022年招聘人員試題及答案解析1
- 職業(yè)健康遠(yuǎn)程隨訪的醫(yī)患協(xié)同管理策略優(yōu)化
- ISO9001-2015質(zhì)量管理體系版標(biāo)準(zhǔn)
- 翻建房屋四鄰協(xié)議書范本
- 打樁承包合同
- 輸煤棧橋彩鋼板更換施工方案
- 農(nóng)田水利施工安全事故應(yīng)急預(yù)案
- 某電廠380v開關(guān)柜改造電氣施工方案
- 江西省景德鎮(zhèn)市2024-2025學(xué)年七年級(jí)上學(xué)期期中地理試卷(含答案)
- 財(cái)務(wù)經(jīng)理年終總結(jié)2024
- 2024年職教高考《機(jī)械制圖》考試題庫
- 開發(fā)區(qū)蒸汽管道工程施工組織設(shè)計(jì)
- DL∕T 593-2016 高壓開關(guān)設(shè)備和控制設(shè)備標(biāo)準(zhǔn)的共用技術(shù)要求
評(píng)論
0/150
提交評(píng)論