JAVA: how to load database url from web.xml?

I am using the persistence API and want to load the jdbc url from web.xml. The URL must be a servlet context parameter. I cannot find how to build EntityManagerFactory without using persistence.xml. Maybe I should create a PersistenceUnit in the servlet and set some parameters? Can you give me a small example?

thank

+3
source share
5 answers

you can use the createEntityManagerFactory(String persistenceUnitName, Map properties)class method javax.persistence.Persistence. and paste all your parameters on the map

+3
source

usng JNDI persistence.xml.

test-uat-prod, .

, , JNDI , , hte web.xml, .

+1

, JPA persistence.xml, web.xml. JPA, persistence.xml.

+1

web.xml env-entry

<env-entry>
    <env-entry-name>dbUrl</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>jdbc:url:goes:here</env-entry-value>
</env-entry>

java

try {
    Context ctx = new InitialContext();
    String dbUrl= (String) ctx.lookup("java:comp/env/dbUrl");

    //... create your connection
} catch (Exception e ) {

}
0

init-param web.xml, URL- . , MySQL :

<init-param>
    <param-name>DB_URL</param-name>
    <param-value>jdbc:mysql:///MY_DB</param-value>
</init-param>

Then get this value in your web application (in the servlet) using something like this:

String myDbUrl = getServletConfig().getInitParameter("DB_URL");

In JSP files, you can get the value as follows:

String myDbUrl  = config.getInitParameter("DB_URL");
0
source

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


All Articles