tomcat共享多个web应用会话的实现方法(tomcat多个service)怎么可以错过

随心笔谈2年前发布 admin
185 0 0

文章摘要

这篇文章描述了从容器(Container)中获取`ServletContext`的方法。该方法`public ServletContext getContext(String uri)`的主要功能如下: 1. 首先验证输入参数`uri`是否为`null`或不以`/`开头,如果是则返回`null`。 2. 尝试从容器中查找与`uri`匹配的子容器(`child`)。如果找到且处于可用状态,则返回该子容器。 3. 如果未找到子容器,则尝试处理`uri`中的版本信息(`##`)并使用映射器(Mapper)获取对应的上下文。 4. 如果仍然找不到,则返回`null`。 5. 最后根据`crossContext`的设置,返回父容器或当前容器的`ServletContext`,或直接返回`null`。 该方法结合了参数验证、查找子容器、版本信息处理以及异常处理,确保了`ServletContext`的正确获取。


public ServletContext getContext(String uri) {

// Validate the format of the specified argument
if (uri==null || !uri.startsWith(“/”)) {
return null;
}

Context child=null;
try {
// Look for an exact match
Container host=context.getParent();
child=(Context) host.findChild(uri);

// Non-running contexts should be ignored.
if (child !=null && !child.getState().isAvailable()) {
child=null;
}

// Remove any version information and use the mapper
if (child==null) {
int i=uri.indexOf(“##”);
if (i > -1) {
uri=uri.substring(0, i);
}
// Note: This could be more efficient with a dedicated Mapper
// method but such an implementation would require some
// refactoring of the Mapper to avoid copy/paste of
// existing code.
MessageBytes hostMB=MessageBytes.newInstance();
hostMB.setString(host.getName());

MessageBytes pathMB=MessageBytes.newInstance();
pathMB.setString(uri);

MappingData mappingData=new MappingData();
((Engine) host.getParent()).getService().findConnectors()[0].getMapper().map(
hostMB, pathMB, null, mappingData);
child=(Context) mappingData.context;
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
return null;
}

if (child==null) {
return null;
}

if (context.getCrossContext()) {
// If crossContext is enabled, can always return the context
return child.getServletContext();
} else if (child==context) {
// Can still return the current context
return context.getServletContext();
} else {
// Nothing to return
return null;
}
}

© 版权声明

相关文章