如果您使用Apache Tomcat 7,則可以在servlet中使用@Resource
來注入數據源。
添加在META-INF
目錄中的文件context.xml
,本地的項目:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/TestResource">
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password=""
url="jdbc:mysql://localhost:3306/test"
maxActive="100"
maxIdle="30"
maxWait="10000"/>
</Context>
在servlet:
@WebServlet(urlPatterns = { "/" }, loadOnStartup = 0)
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource(name = "jdbc/test")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
try (Connection conn = ds.getConnection();
PrintWriter out = resp.getWriter();) {
out.println(conn.getMetaData().getDatabaseProductName());
out.println(conn.getMetaData().getDatabaseProductVersion());
} catch (SQLException e) {
log(e.getMessage(), e);
}
}
}
的WAR結構如下:
C:.
+---META-INF
| context.xml
| MANIFEST.MF
|
\---WEB-INF
+---classes
| \---test
| TestServlet.class
|
\---lib
mysql.jar
這在瀏覽器http://localhost:8080/Test/
的輸出:
MySQL
5.5.32