0

GlobalNamingResourcesを使用して、2つの異なるWebアプリケーション(もちろん同じTomcat上)で使用されるグローバルBeanを作成しようとしています。

私の問題は、JNDIから取得したクラスに新しいデータを設定しようとすると、NullPointerExceptionが発生することです。

次のリンクをたどりましたが、何を間違えたのかまだわかりません: http ://tomcat.apache.org/tomcat-7.0-doc/config/globalresources.html

これは私のサーブレットをクラッシュさせる行です:

single.setText("TEXT");

これは私のテストサーブレットです:

     @WebServlet("/JNDIServlet")
     public class JNDIServlet extends HttpServlet {

     /**
      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         try {

              Thread.sleep(4000);
              Context initCtx = new InitialContext();
              Context envCtx = (Context) initCtx.lookup("java:comp/env");
              SingletonClass single = (SingletonClass) envCtx.lookup("TestMe");
              single.setText("TEXT");
              initCtx.rebind("TestMe", single);
              response.getWriter().println(envCtx.lookup("TestMe").toString());
         } catch (NamingException e) {
              e.printStackTrace();
         } catch (InterruptedException e) {
        e.printStackTrace();
         }
     }

私の「SingletonClass」は単なるpojoです。

package com.jndi.test;

public class SingletonClass {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public SingletonClass() {
    }

}

これは私のweb.xmlファイルです:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>JNDIServletTest</display-name>

  <resource-ref>
<res-ref-name>TestMe</res-ref-name>
<res-type>com.jndi.test.SingletonClass</res-type>
<res-auth>Container</res-auth>
  </resource-ref>
</web-app>

そして最後に、Tomcatのserver.xmlファイルの関連部分:

<GlobalNamingResources>

    <Resource name="TestMe" auth="Container"
                    type="com.jndi.test.SingletonClass"
                    factory="org.apache.naming.factory.BeanFactory"/>

<!-- Editable user database that can also be used by
     UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>

また、Tomcatのcontext.xmlに必要なリソースリンクを追加しました。

<ResourceLink name="TestMe" global="TestMe" type="com.jndi.test.SingletonClass"/>

誰かが私が間違ったことについての洞察を私に提供できますか?

どうもありがとう :)

4

1 に答える 1