I have a servlet where I store a object into attribute storage of ServletContext:
@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);
}
}
This object (IFStoreCredentials) should be accessable in a other Web Service Application which is running within same Tomcat container instance:
@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() + " !";
}
}
Because the two web applications did not know about shared class name I created an external library which should act as an interface:
package com.data.credentials.manager;
public interface IFStoreCredentials {
public String getUserName();
public String getPassword();
}
I included this library in each application and implement the interface in a concrete class.
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:
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)
Question: 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?