简体   繁体   English

JAVA:如何从web.xml加载数据库URL?

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

I'm using persistence API and want to load jdbc URL from web.xml. 我正在使用持久性API,并希望从web.xml加载jdbc URL。 URL should be a context parameter of servlet. URL应该是servlet的上下文参数。 I can't find how to construct EntityManagerFactory not using persistence.xml. 我找不到如何使用persistence.xml构造EntityManagerFactory。 May be I should create PersistenceUnit in servlet and set some parameters? 可能是我应该在servlet中创建PersistenceUnit并设置一些参数? Can you give me some short example? 你能举个简短的例子吗?

Thank you 谢谢

you can use method createEntityManagerFactory(String persistenceUnitName, Map properties) of class javax.persistence.Persistence . 您可以使用类javax.persistence.Persistence方法createEntityManagerFactory(String persistenceUnitName, Map properties) 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. 我个人觉得这是在servlet容器中使用JNDI定义数据源的最简洁方法,并从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. 这也解决了从test-uat-p​​rod迁移时的一个配置问题,因为我可以在机器上使用相同的数据源名称。

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. 是的,我知道JNDI不受欢迎,但这很好用,它避免了操纵hte web.xml,这也包含在战争中。

Whether you use a datasource or not, the JPA configuration goes in the persistence.xml , not in the web.xml . 无论您是否使用数据源,JPA配置都在persistence.xml ,而不在web.xml If you want to use JPA, provide a persistence.xml . 如果要使用JPA,请提供persistence.xml

You can retrieve any value from the web.xml by using env-entry 您可以使用env-entry从web.xml中检索任何值

<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 而在java中

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

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

}

Define an init-param in your web.xml that points to your database url. 在web.xml中定义一个指向数据库URL的init-param。 For example, for MySQL, it would be something like this: 例如,对于MySQL,它将是这样的:

<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: 然后使用以下内容在Web应用程序(在Servlet中)中获取此值:

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

In JSP files you can get the value in this way: 在JSP文件中,您可以通过以下方式获取值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM