最近有点忙,人物比较多,累。。
=======================================
项目需求要支持查看用户操作记录和登录的记录
操作记录已经有了 现在只需要添加登录的记录
线面只说实现登录记录的方法 和 一些问题
项目用的springMvc hibernate
记录登录登出用的是实现HttpSessionBindingListener接口(这里有详细介绍HttpSessionBindingListener和HttpSessionAttributeListener区别)
public class SessionListener implements HttpSessionBindingListener {
private LogUser logUser;
private String ipAddress;
private LogUserService logUserService;//实现注入LogUserService对象
public LogUser getLogUser() {
return logUser;
}
public void setLogUser(LogUser logUser) {
this.logUser = logUser;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public LogUserService getLogUserService() {
return logUserService;
}
public void setLogUserService(LogUserService logUserService) {
this.logUserService = logUserService;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
this.logUserService.addUserLoginHistory(this.logUser, ipAddress, "login");
System.out.println(logUser.getUserName() + "在" + this.ipAddress + "上线");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
this.logUserService.addUserLoginHistory(this.logUser, ipAddress, "logout");
System.out.println(logUser.getUserName() + "在" + this.ipAddress + "下线");
}}
添加监听
SessionListener sessionListener = new SessionListener();
sessionListener.setLogUser(user);
sessionListener.setIpAddress(ipLogin);
sessionListener.setLogUserService(this);//LogUserService
request.getSession().setAttribute("user2", sessionListener);
由于用的是SpringMvc 所以用bean的话就直接注入到监听类中可以直接调用
本来想用加载上下文得到类的但是SpringMvc老师过不去,在配置文件中添加<bean></bean>还有别的问题,由于时间问题就没在研究了,如有大侠知道请告诉一下
ServletContext sc = event.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
LogUserService logUserService = (LogUserService) ctx.getBean("logUserService");
下面是实现效果
登录时:
test1在10.10.110.56上线
超时注销和:
test1在10.10.110.56下线