[英]how to deploy java web application with mysql database on tomcat server
I have created java web application in eclipse with database mysql.But now i have to deploy that web application in tomcat server.I know how to deploy web application without databas but need assistance with database. 我已经在eclipse中使用数据库mysql创建了java web应用程序。但是现在我必须在tomcat服务器中部署该Web应用程序。我知道如何在没有数据库的情况下部署Web应用程序但需要数据库帮助。 Thank you in advance.
先感谢您。
There are two main ways to obtain JDBC connections within a Java Web Application. 在Java Web应用程序中获取JDBC连接有两种主要方法。
JNDI JNDI
Using JNDI requires a connection pool to be created within tomcat. 使用JNDI需要在tomcat中创建连接池。 This can be done within the context.xml file in tomcat's
config
directory. 这可以在tomcat的
config
目录中的context.xml文件中完成。
Example Context.xml Entry 示例Context.xml条目
<Resource name="jdbc/EmployeeDB"
auth="Container"
type="javax.sql.DataSource"
username="dbusername"
password="dbpassword"
driverClassName="org.hsql.jdbcDriver"
url="jdbc:HypersonicSQL:database"
maxActive="8"
maxIdle="4"/>
This connection would then be retrieved in your code as follows: 然后将在您的代码中检索此连接,如下所示:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
Manual Creation 手动创建
Manually creating the connection within your code is simpler, however JNDI is recommended for its portability. 在代码中手动创建连接更简单,但建议使用JNDI以实现其可移植性。
Manual Example 手动示例
public class MysqlConnect{
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When deploying for either of these scenarios it is important that you have the appropriate JDBC driver in your classpath. 在部署这些方案之一时,在类路径中拥有相应的JDBC驱动程序非常重要。
There are 2 scenarios here: 这里有两种情况:
Class.forName()
- in that case you just need to make sure the jar containing the driver is in the classpath and it should work. Class.forName()
直接在代码中定义连接 - 在这种情况下,您只需要确保包含驱动程序的jar在类路径中并且它应该可以工作。 This is the preferred method - Define a Datasource on the server and call it in the code by using the JNDI API: 这是首选方法 - 在服务器上定义数据源并使用JNDI API在代码中调用它:
InitialContext ic = new InitialContext(); DataSource ds = (DataSource)ic.lookup("jdbc/testDS"); conn = ds.getConnection();
在contex.xml中使用 - tag我们可以连接到任何db
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.