[英]How can I bind Datasource to an attribute in ServletContext in a Java web application runing on Tomcat?
如何在Java Web應用程序中將Datasource綁定到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();
}
}
}
這就是它,希望它有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.