title: Tomcat ServletContext cannot load class
body: <p>I have the need to communicate between two web applications. Both are tomcat projects. I want to avoid using http requests to communicate. After doing some research I discovered there is a ServletContext object which is meant to handle this.</p>
  
  <p>I was following the guide on <a href="http://blog.imaginea.com/cross-context-communication-between-web-applications/" rel="nofollow">http://blog.imaginea.com/cross-context-communication-between-web-applications/</a> and decided to try this in my own quickstarts.</p>
  
  <p>I made sure my tomcat server had its crossContext set to true.</p>
  
  <pre><code>&lt;Context crossContext="true"&gt;
  </code></pre>
  
  <p>I created two wicket quickstarts one named bar and one named foo. The idea was that I could call a function in foo from bar.</p>
  
  <p>Here is the code in bar</p>
  
  <pre><code>String methodName = getRequest().getParameter("PARAM_METHOD");
      ServletContext srcServletContext = ((WebApplication)WebApplication.get()).getServletContext();
      ServletContext targetServletContext = srcServletContext.getContext("/foo");
  
      ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
  
      try
      {
          Object object = targetServletContext.getAttribute("org.apache.wicket.protocol.http.WicketServlet.CONTEXT.foo");
  
          ClassLoader targetServiceClassLoader = targetServletContext.getClass().getClassLoader();
  
          Thread.currentThread().setContextClassLoader(targetServiceClassLoader);
  
          // Causes a ClassNotFoundException
          Class&lt;?&gt; classBarService = (Class&lt;?&gt;)targetServiceClassLoader.loadClass("com.foo.SomeUtil");
  
          Method getTextMethod = object.getClass().getMethod("getText", String.class);
  
          Object someUtil = getTextMethod.invoke(object, "someUtil");
  
          Method targetMethod = classBarService.getMethod(methodName, (Class[])null);
  
          Object responseFromTextMethod = targetMethod.invoke(someUtil, (Object[])null);
  
      }
      catch (Exception e)
      {
          text += e.toString();
      }
      finally
      {
          Thread.currentThread().setContextClassLoader(currentClassLoader);
      }
  </code></pre>
  
  <p>foo has a class named SomeUtil in the package com.foo.
  But when I try to load the class after changing the class loader I am getting a "ClassNotFoundException: com.foo.SomeUtil". I can't really tell what I am doing wrong.</p>
  
  <p>Any help is appreciated in advance.</p>