我正在尝试使用GlobalNamingResources创建一个将由2个不同的webapps(当然是在同一个tomcat上)使用的全局bean。Tomcat JNDI返回null而不是bean
我的问题是,当我尝试将新数据设置为从JNDI获得的类时,我得到一个NullPointerException。
我也跟着下面的链接,我仍然不知道我做错了什么: http://tomcat.apache.org/tomcat-7.0-doc/config/globalresources.html
这是崩溃我的servlet行:
single.setText("TEXT");
这是我测试的servlet:
@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"/>
任何人都可以请我提供一些关于我做了什么的见解错了吗?
感谢很多:)
决定你的想法。根据你的问题,它是一个'NullPointerException'还是一个'ClassCastException'按照你对现在被删除的答案的评论? – EJP