title: Sharing session attributes of a web service and a servlet within same Tomcat container
body: <p>I have a servlet where I store a object into attribute storage of ServletContext:</p>
  
  <pre><code>@WebServlet(name = "MainTestServlet", urlPatterns = {"/MainTestServlet"})
  public class MainTestServlet extends HttpServlet {
  
      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {        
          IFStoreCredentials creds = new StoreCreds();
          this.getServletContext().setAttribute("creds2", creds);   
      }
  
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          processRequest(request, response);
      }
  }
  </code></pre>
  
  <p>This object (IFStoreCredentials) should be accessable in a other Web Service Application which is running within same Tomcat container instance:</p>
  
  <pre><code>@WebService(serviceName = "TestWebService")
  public class TestWebService {
      @Resource
      private WebServiceContext context;
      @WebMethod(operationName = "hello")
      public String hello(@WebParam(name = "name") String txt) {       
          ServletContext servletContext =
                  (ServletContext) context.getMessageContext().get(
                          MessageContext.SERVLET_CONTEXT);        
          IFStoreCredentials creds = (IFStoreCredentials) servletContext.getContext("/TestServlet").getAttribute("creds2");       
          return "Hello " + creds.getUserName() + " !";
      }
  }
  </code></pre>
  
  <p>Because the two web applications did not know about shared class name I created an external library which should act as an interface:</p>
  
  <pre><code>package com.data.credentials.manager;
  
  public interface IFStoreCredentials {    
      public String getUserName();    
      public String getPassword();
  }
  </code></pre>
  
  <p>I included this library in each application and implement the interface in a concrete class.</p>
  
  <p>The problem is know that not the interface which is known by each application is used but still the concrete class name. If a execute the Web Service method I got a ClassCastException:</p>
  
  <pre><code> test.main.StoreCreds cannot be cast to com.data.credentials.manager.IFStoreCredentials
  java.lang.ClassCastException: test.main.StoreCreds cannot be cast to com.data.credentials.manager.IFStoreCredentials
      at com.test.webservice.TestWebService.hello(TestWebService.java:30)
  </code></pre>
  
  <p><strong>Question:</strong>
  Why is this class cast exception is thrown? I have created an interface which should be used but it seems that object is still from type "test.main.StoreCreds". How to solve this problem?</p>