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();