[javaEE] tomcat内部连接池

前端之家收集整理的这篇文章主要介绍了[javaEE] tomcat内部连接池前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Meta-INF的目录下,新建context.xml

在程序中获取数据源,通过jndi,这个jndi必须在Servlet中才能获取,并且需要配置web.xml使servlet一启动就拿到数据源

context.xml

@H_502_32@
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Context>
  3. Resource
  4. name="mySource"
  5. type="javax.sql.DataSource"
  6. username="root"
  7. password
  8. driverClassName="com.MysqL.jdbc.Driver"
  9. url="jdbc:MysqL:///java"
  10. maxActive="8"
  11. maxIdle="4"
  12. />
  13. </>
@H_502_32@
  1. package com.tsh.web;
  2. import java.io.IOException;
  3. java.sql.Connection;
  4. java.sql.ResultSet;
  5. java.sql.Statement;
  6. javax.naming.Context;
  7. javax.naming.InitialContext;
  8. javax.servlet.ServletException;
  9. javax.servlet.http.HttpServlet;
  10. javax.servlet.http.HttpServletRequest;
  11. javax.servlet.http.HttpServletResponse;
  12. javax.sql.DataSource;
  13. /**
  14. */
  15. public class DataSourceTest extends HttpServlet {
  16. /**
  17. */
  18. public DataSourceTest() {
  19. super();
  20. // TODO Auto-generated constructor stub
  21. }
  22. protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
  23. TODO Auto-generated method stub
  24. void doPost(HttpServletRequest request,IOException {
  25. }
  26. /**
  27. * 创建后就会启动
  28. */
  29. @Override
  30. void init() ServletException {
  31. try {
  32. 注意导包javax.naming.Context;
  33. Context context= new InitialContext();
  34. Context jndi=(Context) context.lookup("java:comp/env");
  35. DataSource source =(DataSource) jndi.lookup("mySource");
  36. 注意导包 java.sql.Connection;
  37. Connection conn=source.getConnection();
  38. 获取传输器对象
  39. Statement statement=conn.createStatement();
  40. 获取结果集对象
  41. ResultSet resultSet=statement.executeQuery("select * from user"遍历
  42. while(resultSet.next()){
  43. String username=resultSet.getString("username");
  44. System.out.println(username);
  45. }
  46. 关闭资源
  47. resultSet.close();
  48. statement.close();
  49. conn.close();
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }

web.xml

@H_502_32@
  1. servlet>
  2. servlet-name>DataSourceTestservlet-class>com.tsh.web.DataSourceTestload-on-startup>1servlet-mappingurl-pattern>/Servlet/DataSourceTest>
  3.  
  4. >

 

猜你在找的Java SE相关文章