[javaEE] tomcat内部连接池详解编程语言
2023-06-13 09:20:37 时间
在META-INF的目录下,新建context.xml
在程序中获取数据源,通过jndi,这个jndi必须在Servlet中才能获取,并且需要配置web.xml使servlet一启动就拿到数据源
context.xml
?xml version="1.0" encoding="utf-8"? Context Resource name="mySource" type="javax.sql.DataSource" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql:///java" maxActive="8" maxIdle="4" /Context
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /** protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 创建后就会启动 @Override public void init() throws ServletException { try { //注意导包javax.naming.Context; Context context= new InitialContext(); Context jndi=(Context) context.lookup("java:comp/env"); DataSource source =(DataSource) jndi.lookup("mySource"); //注意导包 java.sql.Connection; Connection conn=source.getConnection(); //获取传输器对象 Statement statement=conn.createStatement(); //获取结果集对象 ResultSet resultSet=statement.executeQuery("select * from user"); //遍历 while(resultSet.next()){ String username=resultSet.getString("username"); System.out.println(username); //关闭资源 resultSet.close(); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); }
web.xml
servlet servlet-name DataSourceTest /servlet-name servlet-class com.tsh.web.DataSourceTest /servlet-class load-on-startup 1 /load-on-startup /servlet servlet-mapping servlet-name DataSourceTest /servlet-name url-pattern /Servlet/DataSourceTest /url-pattern /servlet-mapping
12686.html
cjavamysqlxml相关文章
- 查看Tomcat内存使用情况的JSP代码详解编程语言
- Tomcat的JVM和连接数设置详解编程语言
- [javaEE] Tomcat的安装与配置详解编程语言
- Servlet容器Tomcat中web.xml中url-pattern的配置详解[附带源码分析]编程语言
- Linux 安装配置 Tomcat详解编程语言
- tomcat创建一个windows服务详解编程语言
- springboot 项目部署到外部tomcat详解编程语言
- tomcat启动时出现There are no resources that can be added or removed from the server详解编程语言
- SpringBoot 打包成war包,部署到tomcat详解编程语言
- 服务安装安装Linux Tomcat服务,轻松管理Web应用程序(linux的tomcat)
- tomcat指定JDK版本详解编程语言
- java,spring,tomcat,跨域设置详解编程语言
- SSH远程重启Tomcat时无法找到JAVA_HOME也连接不上SAP详解编程语言
- Linux查看Tomcat进程:掌握必备指令(linux查看tomcat进程)
- Linux下如何快速启动Tomcat(linux如何启动tomcat)
- 以Linux运行Tomcat,实现轻松部署Web应用(linux tomcat)
- 使用Tomcat和Redis构建更加稳健的Web应用(tomcat和redis)
- Tomcat 与 Redis 的桥梁惠泽互联(tomcat与redis)