1. 程式人生 > >Spring MVC 下Session監聽器監聽設定小細節

Spring MVC 下Session監聽器監聽設定小細節

今天在SpringMVC專案中加入了一個Session監聽事件,當在web.xml中註冊後啟動專案一直報異常,之後查證後發現,原來session監聽類中不能進行依賴注入,而我同時又必須要用注入方式進行例項化,最終經過多次試驗,終於解決了問題,下面是具體程式碼:

//記得 到web.xml中註冊監聽
public class SessionListenerLog implements HttpSessionListener, ServletRequestListener{
	
	private HttpServletRequest request;

	//監聽事件中 不能新增依賴注入
	//@Resource(name="AuditLogServiceImpl")
	private AuditLogService auditLogService;
	
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		//當client端訪問server端jsp頁面時,session也就建立了
		//但並不意味著使用者就已經登入,因此登陸日誌不寫在這
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		//可將下面類中需要的類都進行依賴注入,非常方便
		ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
		auditLogService = (AuditLogService) ctx.getBean("AuditLogServiceImpl");
		
		//但退出日誌寫在這裡
		//只要使用者退出,理論上session需要被銷燬
		HttpSession session = event.getSession();
		String LoginName = (String) session.getAttribute("sessionUserName");
		StringBuilder sb = new StringBuilder();
		
		//details 資訊
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:dd:ss");
		sb.append("退出時間: ").append(sdf.format(new Date())).append("\n");
		sb.append("退出使用者: ").append(LoginName).append("\n");
		String detailsMsg = sb.toString();
		
		if(detailsMsg.length() != 0 ){
			String GUID = new RandomGUID().toString().replaceAll("-", "");
			GUID = GUID.substring(1, GUID.length()-1);
			//記錄日誌基本資訊
			ZfSysLogBasicBean logBasic = auditLogService.insertZfSysLogOutBasic(
					request, "AJ", "", "LOGOUT", "", "100335",
					SessionListenerLog.class, GUID,LoginName);
			auditLogService.insertZfSysLogDetails(detailsMsg, logBasic);
		}
	}
	
	@Override
	public void requestInitialized(ServletRequestEvent requestEvent) {
		request = (HttpServletRequest) requestEvent.getServletRequest();
	}
	@Override
	public void requestDestroyed(ServletRequestEvent requestEvent) {
		
	}
}