Web中的監聽器【Listener】與過濾器【Filter】 例項

qingyezhu發表於2015-01-19

監聽器例項:

package com.gwssi.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		SessionBean sessionBean = SessionFactory.getInstance().getSessionBean();
		System.out.println("sessionCreated session: " + (session.getId()));
		System.out.println("sessionCreated accessCount: "
				+ (sessionBean.getAccessCount()));
		// 訪問次數
		sessionBean.setAccessCount(sessionBean.getAccessCount() + 1);
		// 線上人數統計
		sessionBean.getOnline().put(session.getId(), null);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		SessionFactory factory = SessionFactory.getInstance();
		SessionBean sessionBean = factory.getSessionBean();

		System.out.println("sessionDestroyed session: " + (session.getId()));
		System.out.println("sessionDestroyed accessCount: "
				+ (sessionBean.getAccessCount()));

		factory.removeLogin(session);
	}

}

 

package com.gwssi.listener;

import javax.servlet.http.HttpSession;

public class SessionFactory {
	private SessionBean sessionBean = new SessionBean();
	private static SessionFactory factory;

	private SessionFactory() {

	}

	static {
		factory = new SessionFactory();
	}

	public synchronized static SessionFactory getInstance() {
		if (factory == null) {
			factory = new SessionFactory();
		}
		return factory;
	}

	public void addLogin(HttpSession session, String user) {
		this.getSessionBean().getOnline().put(session.getId(), user);
		this.getSessionBean().getLogin().add(user);
	}

	public void removeLogin(HttpSession session) {
		this.getSessionBean().getLogin()
				.remove(this.getSessionBean().getOnline().get(session.getId()));
		this.getSessionBean().getOnline().remove(session.getId());
	}

	public boolean isOnline(String user) {
		return this.getSessionBean().getLogin().contains(user);
	}

	public SessionBean getSessionBean() {
		return sessionBean;
	}

	public void setSessionBean(SessionBean sessionBean) {
		this.sessionBean = sessionBean;
	}

}

 

package com.gwssi.listener;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SessionBean {

	private Map<String, String> online = new HashMap<String, String>();

	private int accessCount = 0;

	private Set<String> login = new HashSet<String>();

	/**
	 * 
	 * 返回當前系統線上人數
	 * 
	 * @return int
	 */
	public int getOnlineCount() {
		return this.online.size();
	}

	/**
	 * 返回當前系統登入人數
	 * 
	 * @return int
	 */
	public int getLoginCount() {
		return this.getLogin().size();
	}

	public Map<String, String> getOnline() {
		return online;
	}

	public void setOnline(Map<String, String> online) {
		this.online = online;
	}

	public int getAccessCount() {
		return accessCount;
	}

	public void setAccessCount(int accessCount) {
		this.accessCount = accessCount;
	}

	public Set<String> getLogin() {
		return login;
	}

	public void setLogin(Set<String> login) {
		this.login = login;
	}

}

 在web.xml中增加

 <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
    
    <listener>
    	<listener-class>com.gwssi.listener.SessionListener</listener-class>
    </listener>

 

在登入時

	//新增進入SessionFactory,以供記錄是否線上
				SessionFactory.getInstance().addLogin(session, userInfo.getUserId());

 頁面呼叫:
import="com.oddel.listener.SessionFactory;
SessionFactory.getInstance().isOnline(userid)
返回true表示使用者當前是線上的。
返回false表示使用者當前是不線上的。

 

參考部落格:

http://www.cnblogs.com/sherryueda/p/4273169.html

過濾器:

package com.gwssi.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.gwssi.csdb.fbk.util.StringUtil;

public class SessionCheckFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String userid = request.getParameter("userid");
//		System.out.println(request.getServletPath() + "===SessionCheckFilter====" + userid);
		if (StringUtil.isEmpty(userid) || "null".equals(userid)) {
			// 當請求中沒有userid引數時,由後臺進行判斷
			chain.doFilter(req, res);
		} else {
			HttpSession session = request.getSession();
			UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
			HttpServletResponse response = (HttpServletResponse) res;
			if (userInfo == null) {
				// session過期
				redirect(request, response);
			} else {

				System.out.println(userInfo.getUserId() + "========" + userid);
				if (userid.equals(userInfo.getUserId())) {
					chain.doFilter(req, res);
				} else {
					// 登入名不一致
					redirect(request, response);
				}
			}
		}
	}

	private void redirect(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String requestType = request.getHeader("X-Requested-With");
		if (requestType != null && requestType.equals("XMLHttpRequest")) {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		} else {
			String href = request.getContextPath()
					+ "/pages/sessionTimeOut.jsp";
			response.sendRedirect(href);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

}

 在web.xml中

<filter>
    	<filter-name>sessionCheckFilter</filter-name>
    	<filter-class>com.gwssi.csdb.fbk.authority.SessionCheckFilter</filter-class>
    </filter>
    <filter-mapping>
    	<filter-name>sessionCheckFilter</filter-name>
    	<url-pattern>*.do</url-pattern>
    </filter-mapping>
    

 

參考部落格:

http://www.cnblogs.com/sherryueda/p/4275805.html

 

相關文章