我有一个 servlet,我将一个对象存储到 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);
}
}
此对象 (IFStoreCredentials) 应该可以在同一个 Tomcat 容器实例中运行的其他 Web 服务应用程序中访问:
@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() + " !";
}
}
因为这两个 Web 应用程序不知道共享类名,所以我创建了一个应充当接口的外部库:
package com.data.credentials.manager;
public interface IFStoreCredentials {
public String getUserName();
public String getPassword();
}
我在每个应用程序中都包含了这个库,并在一个具体的类中实现了接口。
问题是知道不是每个应用程序都知道的接口被使用,而是具体的类名。如果执行 Web 服务方法,我得到一个 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)
问题: 为什么会抛出这个类转换异常?我创建了一个应该使用的接口,但似乎该对象仍然来自“test.main.StoreCreds”类型。如何解决这个问题呢?