Java中的過濾器和監聽器

過濾器


一個過濾器能夠附加到一個或者多個Servlet上,一個Servlet能夠附加一個或者多個Filter。一個過濾器必須實現javax.servlet.Filter接口並實現其中的三個方法。html

  • init()方法:java

    這個方法在實例化過濾器時被調用,主要用於使過濾器爲處理作準備。容器爲這個方法傳遞一個FilterConfig對象,其中包含配置信息。web

  • doFilter():bash

    這個方法用於處理請求和相應。它接受3個輸入參數:ServletRequestServletReponseFilterChain對象。FilterChain對於正確的過濾操做相當重要。doFilter()方法必須調用FilterChaindoFilter()方法,除非該方法用來攔截之後的下游處理session

  • destroy():app

    該方法由容器在銷燬過濾器實例以前調用。jsp

    package com.tz.filter;
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class EncodingFilter implements Filter{
    	String encoding = null;
    	FilterConfig config = null;
    	@Override
    	public void destroy() {
    		// TODO Auto-generated method stub
    		this.config=null;
    		this.encoding=null;
    	}
    	@Override
    	public void doFilter(ServletRequest request, ServletResponse response,
    			FilterChain chain) throws IOException, ServletException {
    		// TODO Auto-generated method stub
    		if(encoding!=null){
    			//對請求進行編碼設置
    			request.setCharacterEncoding(encoding);
    		}
    		chain.doFilter(request, response);
    	}
    	@Override
    	public void init(FilterConfig config) throws ServletException {
    		// TODO Auto-generated method stub
    		this.config = config;
    		this.encoding = config.getInitParameter("encoding");
    	}
    	
    }
    複製代碼

    web.xml配置:ide

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    		 xmlns="http://java.sun.com/xml/ns/javaee" 
    		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    		 					 id="WebApp_ID" version="3.0">
      <display-name>test</display-name>
      <filter>
      	<filter-name>encodingFilter</filter-name>
      	<filter-class>com.tz.filter.EncodingFilter</filter-class>
      	<init-param>
      		<param-name>encoding</param-name>
      		<param-value>utf-8</param-value>
      	</init-param>
      </filter>
      <filter-mapping>
      	<filter-name>encodingFilter</filter-name>
      	<url-pattern>/*</url-pattern>
      </filter-mapping>
      
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    複製代碼

    Jsp文件:post

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>編碼過濾器測試</title>
    	<meta http-equiv="content-type" content="text/html;charset=utf-8">
      </head>
      
      <body>
        <form action="process.jsp" name="form1" method="post">
        	姓名:<input type="text" name="userName" />
        	<input type="submit" value="提交" name="submit">
        </form>
      </body>
    </html>
    複製代碼

    process.jsp:測試

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>編碼過濾器測試</title>
    	<meta http-equiv="content-type" content="text/html;charset=utf-8">
      </head>
      
      <body>
        <p><%=request.getParameter("userName") %>,你好!</p>
        <%=request.getCharacterEncoding() %>
      </body>
    </html>
    複製代碼

監聽器


在定義監聽器類時,只須要實現相應的監聽器接口便可。如實現了 ServletContextListenerServletContextAttributeListener的類就能夠監聽到ServletContext對象的生命週期變化狀況和ServletContext對象中屬性的變化狀況。實現了HttpSessionListenerHttpServletAttributeListener接口的類就能夠監聽到HttpSession對象的生命週期變化和HttpSession對象中的屬性變化。

package com.tz.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListenerTest implements ServletContextListener,ServletContextAttributeListener{

	//當應用被移除到容器時觸發
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("監聽到應用被移除。。。。。。");
	}

	//當應用在容器中啓動時觸發
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("監聽到應用被啓動。。。。。。");
	}

	//ServletContext中新增屬性時執行此方法
	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		System.out.println("監聽到新增了一個叫"+event.getName()+"的屬性!");
	}

	@Override
	public void attributeRemoved(ServletContextAttributeEvent arg0) {
		System.out.println("removed......");
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent arg0) {
		System.out.println("replaced......");
	}

}
複製代碼
package com.tz.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListenerTest implements HttpSessionListener,HttpSessionAttributeListener{
	
	//在線人數統計
	int count = 0;
	
	//當產生一個新的HttpSession對象時(新用戶上線)執行此方法
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		event.getSession().getServletContext().setAttribute("count",++count);
		System.out.println("監聽到新用戶"+event.getSession().getId()+"上線了!");
	}
	
	//當一個HttpSession銷燬(用戶下線)時執行此方法
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		event.getSession().getServletContext().setAttribute("count",--count);
		System.out.println("監聽到新用戶"+event.getSession().getId()+"下線了!");
	}
	
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		System.out.println("監聽到"+ event.getName()+"屬性新增了,屬性值是"+event.getValue());
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		System.out.println("監聽到"+ event.getName()+"屬性被刪除了");
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		System.out.println("監聽到"+ event.getName()+"屬性被修改了");
		
	}
	

}
複製代碼

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		 xmlns="http://java.sun.com/xml/ns/javaee" 
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
		 					 id="WebApp_ID" version="3.0">
  <display-name>test</display-name>
  
  <listener>
  	<listener-class>com.tz.listener.ContextListenerTest</listener-class>
  </listener>
  
  <listener>
  	<listener-class>com.tz.listener.SessionListenerTest</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
複製代碼

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>編碼過濾器測試</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8">
  </head>
  
  <body>
    
    <h2>Listener應用實例測試</h2>
    <%
    	application.setAttribute("admin", "liubin");
    	application.setAttribute("admin", "xiaohuang");
    	application.removeAttribute("admin");
    	session.setAttribute("now", new Date());
    	session.setAttribute("now", "2016-05-09");
    	session.removeAttribute("now");
     %>
            目前在線人數:<%=application.getAttribute("count") %>人!
     <a href="logout.jsp" style="list-style: none">註銷</a>
  </body>
</html>
複製代碼

logout.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>Listener應用實例</title>
	<meta http-equiv="content-type" content="utf-8">
  </head>
  
  <body>
  	<h2>Listener應用實例</h2>
    <%
    	//銷燬session對象
    	session.invalidate();
     %>
     	恭喜你註銷成功!目前在線人數:<%=application.getAttribute("count") %>
  </body>
</html>
複製代碼
相關文章
相關標籤/搜索