-1

Is there a proper way to set in tomcat database ip, user and password to open a connection toward DB?

My situation is: I have some Servlets running on tomcat, and almost all of them open a connection to mySQL DB and execute queries. Database ip, username and password of the connection are always the same, so what I want is a single point to store those info that let me change those info easly, for example editing a simple txt file or xml one.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
z10h22
  • 51
  • 1
  • 9
  • You could bind it to JNDI. – Kayaman Mar 05 '17 at 09:01
  • https://tomcat.apache.org/tomcat-8.0-doc/jndi-datasource-examples-howto.html – JB Nizet Mar 05 '17 at 09:18
  • @z10h22 Write code with connecting to the database.Yes, You may config conect to the database in context.xml, for example, http://stackoverflow.com/questions/39724146/scada-lts-no-datasource-specified-error This is JNDI. – Grzesiek Mar 05 '17 at 13:10

1 Answers1

0

YES, JNDI is the solution. When asked for this problem, I have already read about jndi, but I had errors, so I thought the solution was not that. After a lot of search it comes out that the error is that when I specify 'url' for the resource it needs TWO BACKSLASHES after 'mysql:', NOT ONE, as a lot of online tutorials said. I report the correct procedure to solve the problem I asked for:
1)context.xml has to be like

<Context>
<Resource name="jdbc/DB_NAME"
auth="Container"
type="javax.sql.DataSource"
username="db_user_to_interact_with_db"
password="password_of_username"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://db_IP:3306/DB_NAME?useSSL=true"
maxActive="100"
maxIdle="3"/>
</Context>

2)you can obtain db connection as follow

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
DataSource ds = (DataSource)envCtx.lookup("jdbc/DB_NAME");
// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
z10h22
  • 51
  • 1
  • 9