标签:style http color io java ar sp cti 代码
二话不说直接上代码:
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
代码:
int activeSessions = 0;
if (request instanceof RequestFacade) {
Field requestField = request.getClass().getDeclaredField("request");
requestField.setAccessible(true);
Request req = (Request) requestField.get(request);
Context context = req.getContext();
Manager manager = context.getManager();
activeSessions = manager.getActiveSessions();
}
编译时引用了tomcat/lib下的catalina.jar,打成war包之后记得从war包中删除catalina.jar
这时候maven的好处就来了,scope写个provided(容器已提供)就OK了。
原理:
tomcat对request(javax.servlet.http.HttpServletRequest)的实现是org.apache.catalina.connector.RequestFacade
RequestFacade有一个protected的request (org.apache.catalina.connector.Request)属性
request 能拿到Context (org.apache.catalina.Context)
context能拿到Manager(org.apache.catalina.Manager,tomcat管理session的类)
然后通过Manager拿到所有存活的session数,就是在线人数了。
标签:style http color io java ar sp cti 代码
原文地址:http://blog.csdn.net/gaboolic/article/details/39232645