java - 在 Tomcat 上运行的 Java Web 应用程序中,如何将数据源绑定(bind)到 ServletContext 中的属性?

标签 java mysql jakarta-ee tomcat datasource

如何在 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&amp;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/

相关文章:

java - 在 RESTful 中加密交换的数据

mysql - 从多个表中选择(大数据)

mysql - 类(class)计时器重载服务器

jsf - 使用 JSF 和 Java EE Batch 上传时是否可以处理文件流?

java - MySQL JDBC 语句问题

java - 使用属性文件获取错误数据库

java - Swing/JFrame 与 AWT/Frame 在 EDT 之外的渲染

sql - 如何将这两个表连接在一起(MySQL,分层查询)?

JSP 表达式语言不从 JavaBean 呈现属性

session - Tomcat:如何从 servlet 访问( session )管理器