如何在 Java Web 应用程序中将数据源绑定(bind)到 ServletContext 中的属性,以及如何使用它来查询数据库?
最佳答案
首先你需要在 root/META-INF 文件夹中有一个 context.xml,例如:
<Context>
<Resource name="jdbc/superblog" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="username" password="passwordhere"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/superblog?useEncoding=true&characterEncoding=UTF-8"
URIEncoding="UTF-8"/>
</Context>
然后在 web.xml 中:
<resource-ref>
<description>MySQL Datasource example</description>
<res-ref-name>jdbc/superblog</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
现在让我们把它放在 ServletContext 中:
package com.tugay.listeners;
import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
public class ServletContextListenerForDataSource
implements ServletContextListener {
@Resource(name = "jdbc/superblog")
DataSource dataSource;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().setAttribute("datasource", dataSource);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
太好了,现在让我们在 Servlet 中使用它:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Super Blog</title>
</head>
<body>
<div>
<form method="POST" action="${pageContext.servletContext.contextPath}/submit"
accept-charset="utf-8">
<label for="name">Name please:
<input type="text" id="name" name="name"/>
</label>
<input type="submit" id="submit" value="Send it!">
</form>
</div>
</body>
</html>
假设此表单被发布到以下 Servlet:
package com.tugay.listeners;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MyFormServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
final String name = httpServletRequest.getParameter("name");
final DataSource datasource
= (DataSource) getServletContext().getAttribute("datasource");
try {
final Connection connection = datasource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + "app_user" + "(username) VALUES(?)");
preparedStatement.setString(1, name);
preparedStatement.execute();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
就是这些了,希望对你有帮助!
关于java - 在 Tomcat 上运行的 Java Web 应用程序中,如何将数据源绑定(bind)到 ServletContext 中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23396105/