tomcat配置context的crossContext属性应用案例

在tomcat下,context元素有一个crossContext属性,如果配置为true,则可以实现在同一个tomcat下的多个web应用之间实现ServletContext对象访问。该属性主要用于跨应用访问数据

在实际项目中遇到一个奇葩需求:在同一个页面框架下嵌套了2套应用!!!
app1和app2部署在同一个tomcat,且session超时时间使用tomcat全局配置。
app2存在定时ajax刷新,导致app2不会存在session超时的问题;因此,如果用户长期停留在app2某个定时刷新的页面,就会出现如下情况;
app2不会出现session超时,但是app1在指定时间之后就会session超时,这时访问app2页面不会跳转到登录页面,而点击app1页面元素就会退出登录,重新跳转到登录页面。
给用于一种很不自然的体验!

为了解决这个问题,做如下调整:
1. 首先,必须明确一个现实:app1和app2是2个独立的应用,所以对于浏览器访问都会在服务器端各自生成独立的session。
2. tomcat支持配置context元素的crossContext属性为true,使得在app2中可以访问到app1应用的ServletContext对象。
利用这个特性,可以在app2中知道app1应用下对应的session是否已经超时。如果已经超时,则在访问app2时就退出登录,跳转到登录页面。


1. tomcat配置

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
    <Context path="/app1" debug="0" reloadable="true" crossContext="true" />
    <Context path="/app2" debug="0" reloadable="true" crossContext="true" />
</Host>

2. app1端

public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
    ...
    HttpSession session = req.getSession();
    req.getSession().getServletContext().setAttribute(session.getId(), session);
    resp.sendRedirect("app2?app1sid=" + session.getId()); // 将app1对应的sessonid传递给app2
    ...
}

3. app2端

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    ...
    if (pageType == 1) {// 从app1跳转到app2
        // 获取在app1应用中对应的session id并保存到app2会话中
        if(req.getSession().getAttribute(req.getSession().getId()) == null) {
            String app1SesionId = request.getParameter("app1sid");
            req.getSession().setAttribute(req.getSession().getId(), app1SesionId);
        }
    }else {
        // 获取app1应用上下文
        ServletContext app1Context = req.getSession().getServletContext().getContext("/app1");
String app1SessionId = req.getSession().getAttribute(req.getSession().getId()).toString(); HttpSession app1Session
= (HttpSession)app1Context.getAttribute(app1SessionId); try { app1Session.getAttribute("login_user"); } catch (IllegalStateException e) { e.printStackTrace(); // app1会话已经超时, 直接在访问app2时就退出登录 // 另外,还应该在app2定时刷新的地方检测app1会话是否已经超时,如果已经超时,则不再返回数据 req.getSession().invalidate(); resp.sendRedirect("/app1/login.do"); return; } } ... }


关于context配置crossContext属性详见:http://tomcat.apache.org/tomcat-7.0-doc/config/context.html
切记:该特性只适用于多个应用程序部署在同一个tomcat下的情形!

原文地址:https://www.cnblogs.com/nuccch/p/7156142.html