0

我正在使用 Jboss AS 5.1.x 服务器。当我在我的 java 程序中使用带有 jndi 名称的 DataSource 对象时,我在连接到服务器管理器连接池时遇到错误。请验证下面提到的详细信息,并给我建议为什么它会给出错误。

要将数据源放置到 Jndi,我们必须放置 *-ds.xml 文件,因此我已将 mysql-ds.xml 文件放置在带有以下标签的 default/deploy 文件夹中。

 <?xml version="1.0" encoding="UTF-8"?>
  <datasources>
  <local-tx-datasource>
 <jndi-name>MySqlDS</jndi-name>
 <connection-url>jdbc:mysql://localhost:3306/mysql</connection-url>
 <driver-class>org.gjt.mm.mysql.Driver</driver-class>
 <user-name>root</user-name>
 <password>root</password>
<exception-sorter-class-name>org.jboss.resource.adapter.
  jdbc.vendor.MySQLExceptionSorter
  </exception-sorter-class-  name>
    <new-connection-sql>SELECT 1</new-connection-sql>
    <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
 <metadata>
    <type-mapping>mySQL</type-mapping>
  </metadata>
  </local-tx-datasource>
 </datasources>

将此 xml 文件放入部署文件夹后,当我浏览 Jndiview 时,我在 jnditree 中找到了一个带有 java 中 MySqlDs 的标签:|MySqlDs

为了使用上面绑定的 jndi 名称,我使用了以下 java 程序(独立)。

// JndiDsConTest.java
import javax.naming.*; //(jndi api)
import javax.sql.*;
import java.sql.*;
import java.util.*;

public class JndiDsConTest
 {
public static void main(String args[])throws Exception
{


    //Jbosss
     Hashtable ht=new Hashtable();
         ht.put(Context.INITIAL_CONTEXT_FACTORY,
               "org.jnp.interfaces.NamingContextFactory");
    ht.put(Context.PROVIDER_URL,"jnp://localhost:1099");

    // create InitialContext obj
    InitialContext ic=new InitialContext(ht);
                                // represents conectivity with registry s/w

    // get DataSoruce obj ref from registry
    DataSource ds=(DataSource)ic.lookup("java:/MySqlDS");
     //DataSource ds=(DataSource)ic.lookup("java:comp/env/jdbc/MySqlDS");

     // get con obj from Jdbc Con pool
     Connection con=ds.getConnection();

     // write jdbc persistance logic
     Statement st=con.createStatement();
     ResultSet rs=st.executeQuery("select count(*) from  employee");

      if(rs.next())
      {
          System.out.println("count of records :"+rs.getInt(1));
      }

      // close jdbc objs
      rs.close();
      st.close();
      // release con obj back to con pool
      con.close();
      }//main
     }//class

当我在类文件上运行时,我得到以下错误堆栈跟踪。

    D:\JAVA DRIVER\JAVA\JNDI>java JndiDsConTest
   Exception in thread "main" javax.naming.CommunicationException: Could not obtain
   connection to any of these urls: MySqlDS and discovery failed with error: javax
   .naming.CommunicationException: Receive timed out [Root exception is java.net.So
   cketTimeoutException: Receive timed out] [Root exception is javax.naming.Communi
  cationException: Failed to connect to server MySqlDS:1099 [Root exception is jav   
  ax.naming.ServiceUnavailableException: Failed to connect to server MySqlDS:1099
  [Root exception is java.net.UnknownHostException: MySqlDS]]]
    at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1763)
    at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:693)
    at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
    at javax.naming.InitialContext.lookup(Unknown Source)
    at JndiDsConTest.main(JndiDsConTest.java:25)
  Caused by: javax.naming.CommunicationException: Failed to connect to server MySq
  lDS:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to
   connect to server MySqlDS:1099 [Root exception is java.net.UnknownHostException:
  MySqlDS]]
    at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:335)
    at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1734)
    ... 4 more
   Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server
   MySqlDS:1099 [Root exception is java.net.UnknownHostException: MySqlDS]
    at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:305)
    ... 5 more  
   Caused by: java.net.UnknownHostException: MySqlDS
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory
    .java:81)
    at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:301)
    ... 5 more

请找到错误堆栈跟踪的原因并解决它。

提前谢谢你。

4

2 回答 2

0

查看堆栈跟踪消息java.net.UnknownHostException: MySqlDS,我会说 JDBC 驱动程序正在寻找一个名为“MySqlDS”的主机,所以我认为它不会从您的 mysql-ds.xml 文件中获取信息,至少不是您的方式在这里进行了描述。

这是我在 JBoss 5.1.0 中工作的一些代码。(我显示的是您的数据源名称,而不是我原来的名称。)

javax.naming.Context ic = new javax.naming.InitialContext();
javax.naming.Context ctx = (javax.naming.Context) ic.lookup("java:");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("jdbc/mysqlds");
conn = ds.getConnection();

在我的脑海中,我不知道 JNDI 查找是否区分大小写。我自己一直使用小写字母。

我希望这会有所帮助。

于 2013-05-30T18:21:06.920 回答
0

@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter out = resp.getWriter();
    resp.setContentType("application/json");

    try {
        DataSourceFactory dataSourceFactory = new DataSourceFactory();
        IDAOFactory dAOFactory = new DAOFactoryImpl(dataSourceFactory);
        IServiceFactory serviceFactory = new ServiceFactoryImpl(dAOFactory);

        IItemService itemService = serviceFactory.getItemService();
        ArrayList<Item> allItems = itemService.getAll();
        Gson gson = new GsonBuilder().create();

        String list = gson.toJson(allItems);

        out.write(list);
    } catch (Throwable ex) {
        ServletException servletException = new ServletException(ex);
        throw servletException;
    } finally {
        if (out != null) {
            out.close();
        }
    }

}

函数加载订单(){

var ajaxConfig = {
    type: "GET",
    url: "getAllOrders",
    async: true,
    contentType: "",
    data: "",
    dataType: "json"
};

$.ajax(ajaxConfig)
        .done(function (response) {
            for (var i = 0; i < response.length; i++) {
                var html = "<tr> \
                            <td>" + response[i].orderId + "</td> \
                            <td>" + response[i].date + "</td>\
                            <td>" + response[i].customerId + "</td> \
                        </tr>";
                $("#tbleOrders tbody").append(html);
            }
        })
        .fail(function (xhr, status, errorMessage) {
            alert("Faild to load data !!");
        });

}

于 2017-08-21T18:31:43.100 回答