JAVA: how to load database url from web.xml?
I'm using persistence API and want to load jdbc URL from web.xml. URL should be a context parameter of servlet. I can't find how to construct EntityManagerFactory not using persistence.xml. May be I should create Pe开发者_高级运维rsistenceUnit in servlet and set some parameters? Can you give me some short example?
Thank you
you can use method createEntityManagerFactory(String persistenceUnitName, Map properties)
of class javax.persistence.Persistence
. and insert all your parameters in the map
I personally find it the cleanest way to define a datasource in the servlet container usng JNDI and refer to that from the persistence.xml.
This also solves one configuration issue when migrating from test-uat-prod as I can use the same datasource name on the machines.
Yeah, I know JNDI is not popular, but this works nice and it avoids having to manipulate hte web.xml which is also wrapped in the war.
Whether you use a datasource or not, the JPA configuration goes in the persistence.xml
, not in the web.xml
. If you want to use JPA, provide a persistence.xml
.
Define an init-param in your web.xml that points to your database url. For example, for MySQL, it would be something like this:
<init-param>
<param-name>DB_URL</param-name>
<param-value>jdbc:mysql:///MY_DB</param-value>
</init-param>
Then get this value inside your Web app (in a Servlet) using something like this:
String myDbUrl = getServletConfig().getInitParameter("DB_URL");
In JSP files you can get the value in this way:
String myDbUrl = config.getInitParameter("DB_URL");
You can retrieve any value from the web.xml by using 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>
And in java
try {
Context ctx = new InitialContext();
String dbUrl= (String) ctx.lookup("java:comp/env/dbUrl");
//... create your connection
} catch (Exception e ) {
}
精彩评论