配置项目上,取得数据源

来源:互联网 发布:淘宝客网站域名规则 编辑:程序博客网 时间:2024/06/05 18:06

这两天做东西想配个数据源,因为是在基本类中使用数据源,Struts配置的数据源无法使用,所以想找个简单点的数据源配置方式(只用到了一点数据库),找了很多这个算是最简单的了,总结了一下步骤,Easy,就是在项目的META-INF目录下建一个context.xml文件,对!就是和Tomcat/conf下的context.xml一样的文件,内容也是一样的,在里面配置数据源,省去了复制粘贴的麻烦,可以走到哪里带到哪里,老少皆宜,配置方式和内容如下:地球人都知道,自己备着用来复制粘贴=。=context.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<Context>  
    <Resource name="jdbc/sqlserver"      
              type="javax.sql.DataSource"    
              driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"      
              maxIdle="2"      
              maxWait="5000"    
              username="sa"    
              password="sql2005"    
              url="jdbc:microsoft:sqlserver://localhost:1433"/>    
    <Resource name="jdbc/mysql"      
              type="javax.sql.DataSource"    
              driverClassName="com.mysql.jdbc.Driver"      
              maxIdle="2"      
              maxWait="5000"    
              username="root"    
              password="qili"    
              url="jdbc:mysql://localhost:3306/goods"/>        
</Context>   

 

 

2、还需要配置web.xml

      <resource-ref>  
    <description>DBConnection</description>  
    <res-ref-name>jdbc/mysql</res-ref-name>  
    <res-type>javax.sql.DataSource</res-type>  
    <res-auth>Container</res-auth>  
</resource-ref> 
 
<resource-ref>  
    <description>DBConnection</description>  
    <res-ref-name>jdbc/sqlserver</res-ref-name>  
    <res-type>javax.sql.DataSource</res-type>  
    <res-auth>Container</res-auth>  
</resource-ref> 

 

3、在JAVA(JSP)中获得数据源

 

 

  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>

<%@page import="javax.naming.Context"%>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.sql.DataSource" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
  <%
   Connection conn=null;
  DataSource ds = null;
 try{
 Context ctx = new InitialContext(); 
   Context envctx =  (Context) ctx.lookup("java:comp/env");
    ds =  (DataSource) envctx.lookup("jdbc/mysql"); 
    conn=ds.getConnection();
    if(conn!=null){
      System.out.println(" MYSQL 88888888888888888888888888888 连接成功");
     }else{
      System.out.println("failfailfailfailfailfailfailfail");
     }
 }catch(Exception exs){
  System.out.println("获取 tomcat 数据源异常!");
  System.out.println(exs);
 }

  %>

 

 

   

原创粉丝点击