在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 driverClassName="com.MysqL.jdbc.Driver" url="jdbc:MysqL:///java" maxActive="8" maxIdle="4" /> </>
package com.tsh.web; import java.io.IOException; java.sql.Connection; java.sql.ResultSet; java.sql.Statement; javax.naming.Context; javax.naming.InitialContext; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; 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 void doPost(HttpServletRequest request,IOException { } /** * 创建后就会启动 */ @Override void init() 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>DataSourceTestservlet-class>com.tsh.web.DataSourceTestload-on-startup>1servlet-mappingurl-pattern>/Servlet/DataSourceTest> >
原文链接:/javase/996836.html