程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> [javaEE] tomcat內部連接池,javaeetomcat

[javaEE] tomcat內部連接池,javaeetomcat

編輯:JAVA綜合教程

[javaEE] tomcat內部連接池,javaeetomcat


在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>
package com.tsh.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;




/**
 */
public class DataSourceTest extends HttpServlet {
       
    /**
     */
    public DataSourceTest() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     */
    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>

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved