版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
JavaWeb開發(fā)從入門到實(shí)踐JavaWebDevelopmentFromIntroductiontoPractice過濾器和監(jiān)聽器Chap07提綱過濾器和監(jiān)聽器過濾器和監(jiān)聽器分別用于處理用戶輸入的事件和動態(tài)監(jiān)控應(yīng)用程序的狀態(tài)變化。7.1過濾器7.2監(jiān)聽器7.3本章小結(jié)7.1過濾器7.1.1過濾器的概念7.1.2配置過濾器7.1.3過濾器的生命周期7.1.4過濾器的鏈及執(zhí)行順序7.1.5過濾器的應(yīng)用7.1.1過濾器的概念過濾器(Filter)的作用就是把瀏覽器對資源的請求攔截下來。圖
7-1
過濾器的工作原理7.1.1過濾器的概念過濾器需要實(shí)現(xiàn)jakarta.servlet.Filter接口publicvoidinit(FilterConfigfilterConfig)throwsServletException{}
publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{}
publicvoiddestroy(){}init()方法該方法用來初始化過濾器對象doFilter()方法該方法是主要實(shí)現(xiàn)過濾的方法destroy()方法該方法的作用是釋放過濾器中使用的資源,是在關(guān)閉Web服務(wù)器時執(zhí)行
7.1.2配置過濾器配置過濾器有兩種方法一是在web.xml中配置二是通過注解配置<filter>
<filter-name>myFilter</filter-name>
<filter-class>com.swxy.filter.MyFilter</filter-class></filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>@WebFilter(filterName="myFilter",
//指定Filter的name屬性,等價于<filter-name>標(biāo)簽 urlPatterns="/*",
//指定Filter的URL匹配模式
initParams={
//設(shè)置過濾器的初始參數(shù)
@WebInitParam(name="username",value="Charles")})
publicclassMyFilterimplementsFilter{//省略}7.1.3過濾器的生命周期過濾器的生命周期是:實(shí)例化→初始化→過濾→銷毀。圖
7-2
過濾器和Servlet的生命周期7.1.3過濾器的生命周期案例:過濾器、Servlet的生命周期示例MyFilter.java@WebFilter("/*")
publicclassMyFilterimplementsFilter{
publicMyFilter(){
System.out.println("Filter構(gòu)造方法");
}
@Override
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
System.out.println("Filter初始化");
}
7.1.3過濾器的生命周期@Override
publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{
System.out.println("過濾前");
filterChain.doFilter(servletRequest,servletResponse);//放行
System.out.println("過濾后");
}
@Override
publicvoiddestroy(){
System.out.println("Filter銷毀方法");
}
}7.1.3過濾器的生命周期@WebServlet("/myServlet") publicclassMyServletextendsHttpServlet{ publicMyServlet(){System.out.println("Servlet構(gòu)造方法");} @Override publicvoidinit()throwsServletException{ System.out.println("Servlet初始化方法"); } @Override protectedvoidservice(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ System.out.println("Servlet的service()方法"); } @Override publicvoiddestroy(){ System.out.println("Servlet銷毀方法"); } }MyServlet.java7.1.3過濾器的生命周期查看測試結(jié)果Filter構(gòu)造方法Filter初始化Servlet構(gòu)造方法Servlet初始化方法過濾前Servlet的service()方法過濾后Servlet銷毀方法Filter銷毀方法7.1.4過濾器的鏈及執(zhí)行順序過濾器鏈?zhǔn)侵冈谝粋€Web應(yīng)用,可以配置多個過濾器,這些過濾器稱為過濾器鏈。圖
7-3
過濾器鏈過濾器鏈7.1.4過濾器的鏈及執(zhí)行順序執(zhí)行過濾器1的放行前邏輯代碼執(zhí)行過濾器1的放行代碼執(zhí)行過濾器2的放行前邏輯代碼執(zhí)行過濾器2的放行代碼執(zhí)行過濾器3的放行前邏輯代碼執(zhí)行過濾器3的放行代碼訪問Web資源執(zhí)行過濾器3的放行后邏輯代碼執(zhí)行過濾器2的放行后邏輯代碼執(zhí)行過濾器1的放行后邏輯代碼7.1.4過濾器的鏈及執(zhí)行順序過濾器的執(zhí)行順序過濾器的攔截路徑相同時:首先按照<filter-mapping>標(biāo)記在web.xml中出現(xiàn)的先后順序執(zhí)行過濾器然后接照過濾器類名的字典順序執(zhí)行注解的過濾器。7.1.5過濾器的應(yīng)用JavaWeb過濾器是一種用于攔截、處理和修改請求和響應(yīng)的組件,用于實(shí)現(xiàn)一些通用的功能字符編碼轉(zhuǎn)換過濾器1、EncodingFilter.java@WebFilter(urlPatterns="/*", initParams={@WebInitParam(name="encoding",value="UTF-8")})
publicclassEncodingFilterimplementsFilter{
privateStringencoding="";
@Override
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
this.encoding=filterConfig.getInitParameter("encoding");
}
7.1.5過濾器的應(yīng)用@Override
publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{
HttpServletRequestrequest=(HttpServletRequest)servletRequest;
//轉(zhuǎn)子接口
HttpServletResponseresponse=(HttpServletResponse)servletResponse;//轉(zhuǎn)子接口
Stringmethod=request.getMethod();//獲取請求方式(如GET、POST等)
if("POST".equals(method)){//請求方式為POST時,中文亂碼的處理
request.setCharacterEncoding(encoding);
}else{//請求方式為GET時,中文亂碼的處理
Enumeration<String>parameterNames=request.getParameterNames();
while(parameterNames.hasMoreElements()){
Stringelement=parameterNames.nextElement();
Stringvalue=request.getParameter(element);
if(value!=null&&!"".equals(value)){
value=newString(value.trim().getBytes("ISO-8859-1"),encoding);
}
}
}filterChain.doFilter(servletRequest,servletResponse);//過濾器放行
}
7.1.5過濾器的應(yīng)用 @Override
publicvoiddestroy(){
Filter.super.destroy();
}
}2、EncodingFilter.java@WebServlet("/encodingServlet")
publicclassEncodingServletextendsHttpServlet{
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
Stringusername=req.getParameter("username");System.out.println(username);
}
}7.1.5過濾器的應(yīng)用臟字過濾器1、準(zhǔn)備屬性文件perties。在項目src下新建文件夾“resource”,在該文件夾下創(chuàng)建文件perties狗屁=***廢物=***該文件經(jīng)過native2ascii編碼后才能使用,命令語法如下:native2ascii-encodingutf-8源文件轉(zhuǎn)換后文件7.1.5過濾器的應(yīng)用2、定義響應(yīng)器包裝類publicclassReplaceWrapperextendsHttpServletResponseWrapper{
privateCharArrayWritercharWriter=newCharArrayWriter();
publicReplaceWrapper(HttpServletResponseresponse){
super(response);//必須調(diào)用父類構(gòu)造方法
}
publicPrintWritergetWriter()throwsIOException{
returnnewPrintWriter(charWriter);//字符數(shù)組緩存輸出內(nèi)容
}
publicCharArrayWritergetCharWriter(){
returncharWriter;
}
}7.1.5過濾器的應(yīng)用3、定義用來替換臟字的過濾器@WebFilter(urlPatterns="/*",initParams={@WebInitParam(name="path",value="resource/perties")})publicclassReplaceFilterimplementsFilter{ privatePropertiesproperties=newProperties(); @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{
Stringpath=filterConfig.getInitParameter("path");//獲取初始化參數(shù)(文件名) try{ //加載資源文件 properties.load(ReplaceFilter.class.getClassLoader().getResourceAsStream(path)); }catch(Exceptione){ e.printStackTrace(); }
}
7.1.5過濾器的應(yīng)用 @Override publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException{
HttpServletResponseresponse=(HttpServletResponse)servletResponse; ReplaceWrapperresp=newReplaceWrapper(response);//實(shí)例化響應(yīng)器包裝類 filterChain.doFilter(servletRequest,resp); Stringstr=resp.getCharWriter().toString();//緩存輸出字符 for(Objecto:properties.keySet()){//循環(huán)文件(如:perties)中的key Stringkey=(String)o;
str=str.replace(key,properties.getProperty(key));//替換非法字符 } PrintWriterout=response.getWriter();//使用原來的HttpServletResponse輸出字符 out.write(str); }}7.1.5過濾器的應(yīng)用@WebServlet("/replaceFilterServlet")publicclassReplaceFilterServletextendsHttpServlet{ @Override protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ resp.setContentType("text/html;charset=UTF-8"); PrintWriterout=resp.getWriter(); out.println("<!DOCTYPEhtml>"); out.println("<HTML>"); out.println("<HEAD><TITLE>臟字過濾器的使用</TITLE></HEAD>"); out.println("helloeveryone!大家好<br/>狗屁<br/>廢物"); out.println("</HTML>"); out.flush(); out.close(); }}4、編寫一個Servlet用來測試臟字過濾器7.1.5過濾器的應(yīng)用5、測試結(jié)果圖
7-5
測試臟字過濾器7.2監(jiān)聽器7.2.1監(jiān)聽對象生命周期的監(jiān)聽器7.2.2監(jiān)聽對象屬性的監(jiān)聽器7.2.3監(jiān)聽Session對象狀態(tài)變化的監(jiān)聽器7.2監(jiān)聽器表
7-1
監(jiān)聽器接口和方法類別監(jiān)聽接口方法生命周期監(jiān)聽器ServletContextListenervoidcontextInitialized(ServletContextEventsce)voidcontextDestroyed(ServletContextEventsce)HttpSessionListenervoidsessionCreated(HttpSessionEventse)voidsessionDestroyed(HttpSessionEventse)ServletRequestListenervoidrequestDestroyed(ServletRequestEventsre)voidrequestInitialized(ServletRequestEventsre)對象屬性監(jiān)聽器ServletContextAttributeListenervoidattributeAdded(ServletContextAttributeEventscae)voidattributeRemoved(ServletContextAttributeEventscae)voidattributeReplaced(ServletContextAttributeEventscae)HttpSessionAttributeListenervoidattributeAdded(HttpSessionBindingEventse)voidattributeRemoved(HttpSessionBindingEventse)voidattributeReplaced(HttpSessionBindingEventse)ServletRequestAttributeListenervoidattributeAdded(ServletRequestAttributeEventsrae)voidattributeRemoved(ServletRequestAttributeEventsrae)voidattributeReplaced(ServletRequestAttributeEventsrae)Session對象狀態(tài)變化監(jiān)聽器HttpSessionBindingListenervoidvalueBound(HttpSessionBindingEventevent)voidvalueUnbound(HttpSessionBindingEventevent)HttpSessionActivationListenervoidsessionWillPassivate(HttpSessionEventse)voidsessionDidActivate(HttpSessionEventse)在Web應(yīng)用中,監(jiān)聽器是指應(yīng)用通過監(jiān)聽事件來監(jiān)聽請求中的行為而創(chuàng)建的一組類。7.2.1監(jiān)聽對象生命周期的監(jiān)聽器監(jiān)聽對象生命周期的監(jiān)聽器有三個:ServletContextListener、HttpSessionListener和ServletRequestListener。ServletContextListener用于監(jiān)聽?wèi)?yīng)用啟動和停止事件,提供了兩個抽象方法publicvoidcontextInitialized(ServletContextEventsce){}//已完成加載Web應(yīng)用和初始化參數(shù)publicvoidcontextDestroyed(ServletContextEventsce){}//Web應(yīng)用即將關(guān)閉7.2.1監(jiān)聽對象生命周期的監(jiān)聽器案例:ServletContextListener的使用1、MyServletContextListener類,實(shí)現(xiàn)ServletContextListener接口publicclassMyServletContextListenerimplementsServletContextListener{
@Override
publicvoidcontextInitialized(ServletContextEventsce){
ServletContextservletContext=sce.getServletContext();//獲取ServletContext對象
Stringusername=servletContext.getInitParameter("username");//獲取初始化值
System.out.println("參數(shù)username:"+username);
}
@Override
publicvoidcontextDestroyed(ServletContextEventsce){
System.out.println("釋放資源");
}
}7.2.1監(jiān)聽對象生命周期的監(jiān)聽器2、在web.xml中配置監(jiān)聽器<context-param> <param-name>username</param-name> <param-value>Charles</param-value></context-param><listener> <listener-class>com.swxy.listener.MyServletContextListener</listener-class></listener>圖
7-6
啟動服務(wù)器獲取初始化參數(shù)3、啟動服務(wù)器Tomcat7.2.1監(jiān)聽對象生命周期的監(jiān)聽器HttpSessionListenerHttpSessionListener接口提供了二個抽象方法voidsessionCreated(HttpSessionEventse){}//創(chuàng)新了新的會話
voidsessionDestroyed(HttpSessionEventse){}//銷毀了一個會話7.2.1監(jiān)聽對象生命周期的監(jiān)聽器案例:利用HttpSessionListener統(tǒng)計在線人數(shù)1、創(chuàng)建類MyHttpSessionListener實(shí)現(xiàn)HttpSessionListener接口packagecom.swxy.listener;
//導(dǎo)入包省略
@WebListener
publicclassMyHttpSessionListenerimplementsHttpSessionListener{
intonline=1;//記錄在線人數(shù)
@Override
publicvoidsessionCreated(HttpSessionEventse){
ServletContextservletContext=se.getSession().getServletContext();//獲取Application對象
Objectcount=servletContext.getAttribute("count");
if(count!=null){
online=Integer.parseInt(count.toString());
online++;//創(chuàng)建Session時,在線人數(shù)+1
}
servletContext.setAttribute("count",online);//在線人數(shù)存儲到Application作用域中
7.2.1監(jiān)聽對象生命周期的監(jiān)聽器}@Override
publicvoidsessionDestroyed(HttpSessionEventse){
ServletContextservletContext=se.getSession().getServletContext();
Objectcount=servletContext.getAttribute("count");
if(count!=null){
online=Integer.parseInt(count.toString());
online--;//銷毀Session對象時,在線人數(shù)-1
}
servletContext.setAttribute("count",online);
}
}7.2.1監(jiān)聽對象生命周期的監(jiān)聽器2、創(chuàng)建類OnLineServlet繼承HttpServlet@WebServlet("/OnLineServlet")publicclassOnLineServletextendsHttpServlet{ @Override protectedvoidservice(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ resp.setContentType("text/html;charset=UTF-8");//設(shè)置響應(yīng)類型及編碼 HttpSessionsession=req.getSession();//創(chuàng)建Session對象 Stringlogout=req.getParameter("logout"); if("true".equals(logout)){ session.invalidate(); }
7.2.1監(jiān)聽對象生命周期的監(jiān)聽器2、創(chuàng)建類OnLineServlet繼承HttpServlet Integercount=(Integer)session.getServletContext().getAttribute("count");//獲取在線人數(shù) PrintWriterout=resp.getWriter(); out.write("<h2>在線人數(shù):"+count+"</h2>"); out.write("<h3><ahref='OnLineServlet?logout=true'>注銷</a></h3>"); }}3、測試結(jié)果圖
7-7
運(yùn)行結(jié)果圖
7-8
點(diǎn)擊注銷后的運(yùn)行結(jié)果7.2.1監(jiān)聽對象生命周期的監(jiān)聽器ServletRequestListenerServletRequestListener接口提供了二個抽象方法publicvoidrequestInitialized(ServletRequestEventsre){}//創(chuàng)建了新的Request對象publicvoidrequestDestroyed(ServletRequestEventsre){}//已經(jīng)銷毀了Request對象在Web應(yīng)用中,有以下兩種方式配置ServletRequestListener1、在web.xml文件中配置<listener>
<listener-class>com.swxy.listener.MyServletRequestListener</listener-class></listener>2、注解方式@WebListenerpublicclassMyServletRequestListenerimplementsServletRequestListener{}7.2.2監(jiān)聽對象屬性的監(jiān)聽器監(jiān)聽對象生命周期的監(jiān)聽器有三個:ServletContextAttributeListener、HttpSessionAttributeListener、ServletRequestAttributeListener。ServletContextAttributeListenerServletContextAttributeListener接口提供了三個抽象方法voidattributeAdded(ServletContextAttributeEventscae){}//屬性被添加到Application中時調(diào)用voidattributeRemoved(ServletContextAttributeEventscae){}//屬性從Application中移除時調(diào)
voidattributeReplaced(ServletContextAttributeEventscae){}//屬性被修改時調(diào)用在Web應(yīng)用中,有以下兩種方式配置ServletContextAttributeListener。1、在web.xml文件中配置<listener>
<listener-class>com.swxy.listener.MyServletContextAttributeListener</listener-class></listener>7.2.2監(jiān)聽對象屬性的監(jiān)聽器2、注解方式@WebListenerpublicclassMyServletContextAttributeListenerimplementsServletContextAttributeListener{}7.2.2監(jiān)聽對象屬性的監(jiān)聽器HttpSessionAttributeListenervoidattributeAdded(HttpSessionBindingEventse){}//屬性被添加到Session中時調(diào)用voidattributeRemoved(HttpSessionBindingEventse){}//屬性從Session中移除時調(diào)用voidattributeReplaced(HttpSessionBindingEventse){}//屬性被修改時調(diào)用HttpSessionAttributeListener接口提供了三個抽象方法ServletRequestAttributeListenervoidattributeAdded(ServletRequestAttributeEventsrae){}//屬性被添加到Request中時調(diào)用voidattributeRemoved(ServletRequestAttributeEventsrae){}//屬性從Request中移除時調(diào)用voidattributeReplaced(ServletRequestAttributeEventsrae){}//屬性被修改時調(diào)用ServletRequestAttributeListener接口可以用來監(jiān)聽Request對象加入屬性、移除屬性和替換屬性時響應(yīng)的動作事件,該接口提供了三個抽象方法在Web應(yīng)用中,配置方式同樣有二種方式:在web.xml中配置和注解,與ServletContextAttributeListener配置類似。7.2.3監(jiān)聽Session對象狀態(tài)變化的監(jiān)聽器監(jiān)聽Session對象狀態(tài)變化的監(jiān)聽器有二個:HttpSessionBindingListener和HttpSessionActivationListenerHttpSessionBindingListenerHttpSessionBindingListener是“HttpSession對象綁定監(jiān)聽器”,用來監(jiān)聽HttpSession中,設(shè)置成HttpSession屬性或從HttpSession中移除時得到Session的通知。voidvalueBound(HttpSessionBindingEventevent){}//已經(jīng)綁定一個Session范圍的對象或者變量voidvalueUnbound(HttpSessionBindingEventevent){}//已經(jīng)解綁了Session范圍的對象或者變量HttpSessionActivationListenerHttpSessionActivationListener是“HttpSession對象轉(zhuǎn)移監(jiān)聽器”,HttpSessionActivationListener的實(shí)現(xiàn)類也必須實(shí)現(xiàn)Serializable接口voidsessionWillPassivate(HttpSessionEventse){}//session中的對象持久化到存儲設(shè)備時調(diào)用voidsessionDidActivate(HttpSessionEventse){}//對象被重新加載時執(zhí)行該方法7.2.3監(jiān)聽Session對象狀態(tài)變化的監(jiān)聽器應(yīng)用實(shí)例創(chuàng)建類MyHttpSessionBindingActivationListenerpublicclassMyHttpSessionBindingActivationListenerimplementsHttpSessionBindingListener,
HttpSessionActivationListener,Serializable{
@Override
publicvoidsessionWillPassivate(Ht
溫馨提示
- 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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 個人搬家服務(wù)2024年度合同3篇
- 二零二五版KTV消防安全檢查與整改服務(wù)合同2篇
- 二零二五年方管產(chǎn)品綠色包裝設(shè)計與實(shí)施合同3篇
- 2024年高端定制家具制造合同
- 2024無人機(jī)航拍與監(jiān)測服務(wù)合同
- 二零二五版歷史文化名城保護(hù)項目技術(shù)咨詢合同3篇
- 二零二五版廢鐵回收處理與環(huán)保服務(wù)合同3篇
- 2024年薪資隱私協(xié)議3篇
- 二零二五年白酒質(zhì)量檢測與認(rèn)證服務(wù)合同2篇
- 武漢華夏理工學(xué)院《世界音樂文化》2023-2024學(xué)年第一學(xué)期期末試卷
- 《如何存款最合算》課件
- 2023年全國統(tǒng)一高考數(shù)學(xué)甲卷【文科+理科】試題及答案解析
- 社區(qū)團(tuán)支部工作計劃
- 廢品處置招標(biāo)書
- GA/T 1280-2024銀行自助設(shè)備安全性規(guī)范
- 數(shù)據(jù)標(biāo)注基地項目實(shí)施方案
- 教培行業(yè)研究系列(七):出國考培的再研究供需變化的新趨勢
- 靜脈治療??谱o(hù)士競聘
- 2024年第一季度醫(yī)療安全(不良)事件分析報告
- 中醫(yī)課件英語教學(xué)課件
- 《哪吒鬧?!冯娪百p析
評論
0/150
提交評論