用java listener统计在线人数,并获取session中对应的ip
在web.xml中添加。注意放到
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
spring监听器之后,否则会报错
<listener>
<listener-class>com.xxx.xxx.util.SessionListener</listener-class>
</listener>
import org.springframework.stereotype.Component;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.*;
import java.util.HashMap;
import java.util.Map;
/**
* SESSION 监听
*/
@Component
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener, ServletContextListener, ServletRequestListener {
//用Map来存储session,sessionid作为key session作为value
public IViewNumService viewNumService;
private static Map sessionMap = new HashMap<String, HttpSession>();
HttpServletRequest request;
public void sessionCreated(HttpSessionEvent se) {
//当session 创建的时候,例如我要监听统计在线人数 并且获取当前session的ip
HttpSession session = se.getSession();
String ip = request.getRemoteAddr();//获取客户端ip
session.setAttribute("ip", ip);
String sid = session.getId();//获取sessionId
sessionMap.put(sid, session);
DateTime dateTime = DateTime.of(session.getCreationTime());
String formattedTime = dateTime.toString("yyyy-MM-dd HH:mm:ss");
// System.out.println("---2session创建时间:" + formattedTime);
System.out.println("----SESSIONID:" + sid + "---2session创建时间:" + formattedTime + " " + ip);
ViewNum viewNum = new ViewNum();
viewNum.setRID(new GUID().toString());
viewNum.setNTIME(formattedTime);
viewNum.setNYEAR(String.valueOf(dateTime.year()));
viewNum.setNMONTH(String.valueOf(dateTime.month()));
viewNum.setNDAY(String.valueOf(dateTime.getDay()));
viewNum.setNIP(ip);
viewNumService.save(viewNum);
}
public static int getOline() {
return sessionMap.size();//获取在线人数,获取到session 就可以拿到ip了
}
public void requestDestroyed(ServletRequestEvent arg0) {
}
public void requestInitialized(ServletRequestEvent sre) {
request = (HttpServletRequest) sre.getServletRequest();//获取request
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// 销毁session或者session超时时
}
public void attributeAdded(HttpSessionBindingEvent arg0) {
//这里是监听当session调用setAtrribute()方法时,例如用户登录,将用户信息设置进session
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
//这里监听当session调用removeAttribute()方法时
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
}
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent arg0) {
}
}
标签:java,ip,void,viewNum,session,import,public
From: https://www.cnblogs.com/xx2017/p/18140894