入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Spring MVC 下Session监听器监听设置小细节

创建时间:2017-01-10 投稿人: 浏览次数:124

今天在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("
");
		sb.append("退出用户: ").append(LoginName).append("
");
		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) {
		
	}
}



声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像