1. 程式人生 > >過濾器、監聽器、攔截器各自的應用場景

過濾器、監聽器、攔截器各自的應用場景

過濾器

監聽器

public interface HttpSessionListener extends EventListener {
    
    public void sessionCreated ( HttpSessionEvent se );
    
    public void sessionDestroyed ( HttpSessionEvent se )
    }

自定義監聽器,統計網站線上人數

public class MyHttpSessionListener implements HttpSessionListener{
	public static int peopleOnLine = 0;
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		System.out.println("myHttpSessionListener.sessionCreated():"+arg0);
		peopleOnLine++;
		arg0.getSession().setAttribute("peopleOnLine",peopleOnLine);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("myHttpSessionListener.sessionDestroyed():"+arg0);
		peopleOnLine--;
		arg0.getSession().setAttribute("peopleOnLine",peopleOnLine);
	}
}

web.xml中的配置

<listener> 
    <listener-class>com.sansux.listener.MyHttpSessionListener</listener-class>
</listener>

在前端頁面獲取線上人數

<%=session.getAttribute("peopleOnLine")%>

攔截器