注:これはクロスポストではありません(ただし、同じ tomcat の webapps 間の私の他の質問共有オブジェクトに関連しています)
c1、c2 (両方ともルートの直後) の 2 つのコンテキストで実行されている 2 つの webapps があります。変数を共有するために c1 に startupListener を配置し、変数を取得するために c2 にもう 1 つ配置しました。問題は、組み込みデータ型 (HashMap、Integer など) のオブジェクトを共有する場合は問題ありませんが、カスタム データ型をキャストできないことです。たとえば、User という名前のカスタム クラスがあり、その型のオブジェクトを渡すと、ClassCastError が発生しました。
c1 の私の startuplistener は次のとおりです。
public void contextInitialized(ServletContextEvent sce) {
User user = new user("name");
Integer exampleInt = 1;
ServletContext context = sce.getServletContext().getContext("/c1");
if (context!=null)
{
context.setAttribute("user", user);
context.setAttribute("id", exampleInt);
}
}
c2 アプリでは、次のようになります。
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext().getContext("/c1");
Integer integer = (Integer) context.getAttribute("id");//this line is OK
Object object = context.getAttribute("user");
User userObject = (User) object; //this line triggered error
User user = (User) context.getAttribute("user");// also trigger error
}
なんでそうなの?(クラスは自分自身へのキャストについて不平を言いますか?)。回避策: 同じ jvm のコンテキスト間でオブジェクトを共有したい。わかりました。