远程访问(跨JVM访问)JBoss5.1配置的数据源

1:在JBoss中配置一个名为“FirstDS”的数据源。

2:在JBoss中部署一个Web项目,在项目中通过JNDI查找FirstDS数据源,可以查找到数据源并

能成功访问数据库。

3:但是在Java Project中却无法查找FirstDS数据源。

代码如下:

public static void main(String[] args) {
	Context ctx = null;
	DataSource ds = null;
	Connection con = null;
	Statement stmt = null;
	ResultSet result = null;
	Properties props = new Properties();
	props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
	props.setProperty(Context.PROVIDER_URL, "127.0.0.1:1099");
	try {
		ctx = new InitialContext(props);
		ds = (DataSource) ctx.lookup("FirstDS");
		con = ds.getConnection();
		stmt = con.createStatement();
		result = stmt.executeQuery("select * from student");
		while (result.next()) {
			System.out.println(result.getInt(1) + "  "
					+ result.getString(2) + "  " + result.getString(3));
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		try {
			if (result != null)
				result.close();
			if (stmt != null)
				stmt.close();
			if (con != null)
				con.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

 异常信息如下:

Exception in thread "main" javax.naming.NameNotFoundException: FirstDS not bound    
    at org.jnp.server.NamingServer.getBinding(NamingServer.java:542)    
    at org.jnp.server.NamingServer.getBinding(NamingServer.java:550)    
    at org.jnp.server.NamingServer.getObject(NamingServer.java:556)    
    at org.jnp.server.NamingServer.lookup(NamingServer.java:296)    
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

 解决方法:

<use-java-context> - A boolean indicating if the jndi-name should be prefixed with java: which causes the DataSource to only be accessible from within the jboss server vm. The default is true.

Configuring a DataSource for remote usage
As of jboss-4.0.0 there is support for accessing a DataSource from a remote client. The one change that is necessary for the client to be able to lookup the DataSource from JNDI is to specify use-java-context=false as shown here:

<datasources>  <local-tx-datasource>    <jndi-name>GenericDS</jndi-name>    <use-java-context>false</use-java-context>    <connection-url>...</connection-url>...
This results in the DataSource being bound under the JNDI name "GenericDS" instead of the default of "java:/GenericDS" which restricts the lookup to the same VM as the jboss server.

 

它说的大概意思就是:(该参数在数据源的配置文件中)
当你指定<use-java-context>的值为false时,你就可以在jboss运行的VM外的VM上查找到这个DataSource.
这个属性默认.为true
即,默认情况下你是不可以在JBOSS的VM外来查找这个数据源. 

猜你喜欢

转载自guoying252166655.iteye.com/blog/2025592
今日推荐