How to use the JNDI resource in a JAX-RS (Jersey) application?

I am trying to configure a connection to my database through the Tomcat JNDI resource. Today I look at many articles, and I can not find the answer.

In my server.xml, I have:

<GlobalNamingResources> <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="tomcat" password="...." driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/> ..... </GlobalNamingResources> 

In my web service, I am trying to access a resource with:

  InitialContext ctx = new InitialContext(); DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB"); Connection conn = data.getConnection(); 

When I run the code, I get this exception:

 Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container javax.naming.NameNotFoundException: Name jdbc is not bound in this Context ... 

I have the latest mysql-connector-java-5.1.18-bin.jar both in my lib web application and in my tomcat lib.

Could you help me get this job?

+4
source share
1 answer

I use this code only with the resource name and it works:

 private Connection getConnection(){ final Context ctx = new InitialContext(); final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB"); if (ds != null) { return ds.getConnection(); } else { } } 
+1
source

Source: https://habr.com/ru/post/1379350/


All Articles