




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
4636a實驗8Servlet過濾器與監(jiān)聽器第一局部Servlet過濾器一、實驗?zāi)康?.了解過濾器的作用;2.掌握過濾器的開發(fā)與部署的步驟;3.了解過濾器鏈。二、實驗原理過濾器是web效勞器上的組件,它們對客戶和資源之間的請求和響應(yīng)進行過濾。過濾器的工作原理是:當servlet容器接收到對某個資源的請求,它要檢查是否有過濾器與之關(guān)聯(lián)。如果有過濾器與該資源關(guān)聯(lián),servlet容器將把該請求發(fā)送給過濾器。在過濾器處理完請求后,它將做下面3件事:產(chǎn)生響應(yīng)并將其返回給客戶;如果有過濾器鏈,它將把〔修改正或沒有修改正〕請求傳遞給下一個過濾器;將請求傳遞給不同的資源。當請求返回到客戶時,它是以相反的方向經(jīng)過同一組過濾器返回。過濾器鏈中的每個過濾器夠可能修改響應(yīng)。過濾器API主要包括:Filter、FilterConfig和FilterChain接口。三、實驗內(nèi)容與步驟〔一〕編寫一個過濾器審計用戶對資源的訪問?!静襟E1】該過濾器實現(xiàn)的功能是,當用戶訪問應(yīng)用程序任何資源時,將用戶的IP地址和主機名寫入日志文件中,過濾器代碼如下: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)用程序的任何資源。如果只對某些資源〔如JSP頁面審計,那么可以指定具體的資源〕?!静襟E3】訪問該應(yīng)用程序中的任何一個資源,如使用下面的URL訪問onlineCount.jsp:://localhost:8080/helloapp/onlineCount.jsp然后翻開<CATALINA_HOME>\logs目錄中的localhost.2006-02-05.log文件中有下面一行〔訪問多個資源就會有多行〕:〔二〕編寫一個過濾器改變請求編碼?!静襟E1】編寫一個loginform.html文件,代碼如下:<html><head><title>使用過濾器改變請求編碼</title><meta-equiv="Content-Type"content="text/html;charset=GB2312"></head><body><center><h2>請輸入用戶名和口令:</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】編寫處理請求參數(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頁面的運行結(jié)果然后點擊“提交〞按鈕,經(jīng)CheckParamServlet處理后返回的結(jié)果如下列圖所示::CheckParamServlet程序的運行結(jié)果從這里我們可以看到,從效勞器返回的漢字成了亂碼。原因是沒有指定request的編碼。下面通過編寫一個過濾器改變請求編碼?!静襟E5】過濾器代碼如下: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】重復第〔4〕步操作,結(jié)果如下:EncodingFilter程序的運行結(jié)果四、思考題1.試簡述過濾器有哪些功能?2.如何理解過濾器鏈。第二局部Servlet監(jiān)聽器一、實驗?zāi)康?.了解在哪些對象上可以產(chǎn)生事件;2.掌握ServletContext和Session對象上的事件處理方法。3.了解在ServletRequest對象上的事件及處理方法。二、實驗原理在Web應(yīng)用程序中,事件的處理也是通過事件監(jiān)聽器接口處理的。Web應(yīng)用事件處理的原理為:當Web應(yīng)用中某些狀態(tài)改變時,Servlet容器就產(chǎn)生某種事件,如ServletContext對象初始化時會產(chǎn)生ServletContextEvent事件,此時Servlet容器就會從注冊的事件監(jiān)聽器中尋找處理該事件的監(jiān)聽器對象,并執(zhí)行相應(yīng)的代碼。在Servlet2.4標準中共定義了6種事件類型和8個事件監(jiān)聽器接口,它們可以處理三種對象上的事件,如表13.1所示:監(jiān)聽器接口與事件類監(jiān)聽對象監(jiān)聽器接口監(jiān)聽事件ServletContextServletContextListenerServletContextEventServletContextAttributeListenerServletContextAttributeEventSessionSessionListenerSessionEventSessionActivationListenerSessionAttributeListenerSessionBindingEventSessionBindingListenerServletRequestServletRequestListenerServletRequestEventServletRequestAttributeListenerServletRequestAttributeEvent三、實驗內(nèi)容與步驟〔一〕編寫一個ServletContext事件監(jiān)聽器。該事件監(jiān)聽器的功能是當Web應(yīng)用程序初始化和銷毀時以及在ServletContext對象上添加屬性、刪除屬性和替換屬性時,在Tomcat日志中記錄有關(guān)信息?!静襟E1】編寫監(jiān)聽器類packagelistener;importjava.io.*;importjava.util.Date;importjavax.servlet.*;publicfinalclassMyServletContextListenerimplementsServletContextListener,ServletContextAttributeListener{privateServletContextcontext=null;publicvoidcontextInitialized(ServletContextEventsce){ context=sce.getServletContext(); context.log("應(yīng)用程序已啟動:"+newDate());}publicvoidcontextDestroyed(ServletContextEventsce){ context=sce.getServletContext(); context.log("應(yīng)用程序已關(guān)閉:"+newDate());}publicvoidattributeAdded(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("添加一個屬性:"+sce.getName()+":"+sce.getValue());}publicvoidattributeRemoved(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("刪除一個屬性:"+sce.getName()+":"+sce.getValue());}publicvoidattributeReplaced(ServletContextAttributeEventsce){ context=sce.getServletContext(); context.log("替換一個屬性:"+sce.getName()+":"+sce.getValue());}}【步驟2】注冊監(jiān)聽器類。修改web.xml文件,參加下面代碼:<listener><listener-class>listener.MyServletContextListener</listener-class></listener>【步驟3】編寫一個測試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對象上添加、替換和刪除了屬性</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】重新啟動Tomcat,然后使用下面URL訪問EventTestServlet:://localhost:8080/helloapp/eventtest顯示界面如下:EventTestServlet程序的運行結(jié)果【步驟6】檢查日志文件翻開<CATALINA_HOME>\logs目錄中的localhost.2006-02-05.log日志文件〔你的文件名可能與此不同〕,在其中可以找到下面這些行:信息:應(yīng)用程序已關(guān)閉:SunFeb0512:42:33CST2006信息:應(yīng)用程序已啟動:SunFeb0512:42:57CST2006信息:添加一個屬性:obj:100信息:替換一個屬性:obj:100信息:刪除一個屬性:obj:SunFeb0512:43:30CST2006這些信息就是執(zhí)行事件監(jiān)聽器后寫到日志文件中的?!捕尘帉懸粋€Session事件監(jiān)聽器用來記錄當前在線人數(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】注冊事件監(jiān)聽器,在web.xml文件中參加下面代碼:<listener><listener-class>listener.MySessionListener</listener-class></listener>【步驟3】編寫一個測試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\">"+"當前在線人數(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再啟動兩個瀏覽器窗口訪問該Servlet,計數(shù)器就會增加,而點擊瀏覽器的“刷新〞按鈕,計數(shù)器不會增加〔因為沒有開始新會話〕。On
溫馨提示
- 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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 二手機器買賣服務(wù)合同范本
- 2025年惠州貨運上崗證模擬考試0題
- 業(yè)務(wù)外合同范本
- 2025年景德鎮(zhèn)貨運資格證考試答案
- 供應(yīng)商代發(fā)合同范本
- 臨時用工解除協(xié)議合同范本
- 初設(shè)評審合同范本
- 書供貨采購合同范本
- 佛山團購合同范本
- 買車合作合同范本
- 一至六年級下冊音樂期末試卷及答案
- 黃金太陽漆黑的黎明金手指
- 節(jié)水灌溉理論與技術(shù)
- 多介質(zhì)過濾器計算書
- 鑼鼓曲譜16762
- 三、QHLY系列——露頂式弧形門閘門液壓啟閉機
- 工商企業(yè)管理專業(yè)專科畢業(yè)論文
- 皮帶機提升機鏈運機功率計算
- 《病毒性肝炎》課件.ppt
- 法恩莎衛(wèi)浴潔具價格表
- 干部職工《出國境管理辦法》政策解讀及工作要求PPT課件
評論
0/150
提交評論