The first step: Write JavaBean
Copy Code code as follows:
Package withouttears.jdbc.db;
Import Java.util.HashMap;
Import java.sql.*;
Jndi has two core interface context and DirContext,
The context contains basic name operations, while DirContext extends these operations to the directory service.
Import Javax.naming.Context;
Import Javax.naming.InitialContext;
The connection factory for database resources is the Javax.sql.DataSource object,
It can create Java.sql.Connection database connection objects.
Import Javax.sql.DataSource;
You can now connect from Java Developers (HTTP://JAVA.SUN.COM/PRODUCTS/JDBC/DOWNLOAD.HTML#ROWSETCOBUNDLE1_0)
Download the implementation of the CachedRowSet. After downloading and extracting the installation files, place the "Rowset.jar" file in your class directory.
The CachedRowSet is in the Sun.jdbc.rowset package.
Import Sun.jdbc.rowset.CachedRowSet;
/**
* Author: Withouttears
* Time: 2006-12-13
* */
public class Database {
/**************************************************************/
/* Function: localhost
* Function: Establish connection pool
* */
private static DataSource localhost () {
DataSource Ds=null;
In HashMap, get value by getting (), insert value by put (),
ContainsKey () is used to verify that the object already exists
Hashmap<object,object> cachedds=new hashmap<object,object> ();
if (Cachedds.containskey ("DS"))//Remove the idle state of the database connection
{
/* A number of database connections have been established beforehand in DataSource,
* These database connections are stored in the connection pool.
* Java program Access to the database, only need to remove the Free State of the database connection from the connection pool;
* When the program accesses the database, then put the database connection back into the connection pool.
* */
ds = (DataSource) cachedds.get ("DS");
}
Else
Try
{
/* Provides a context interface in the Javax.naming package,
* This interface provides a way to bind objects and names, and to retrieve objects by name.
* */
Context Initctx = new InitialContext ();
Lookup (String name): Returns the object bound to the specified name, obtaining a database connection factory
ds = (DataSource) initctx.lookup ("Java:comp/env/jdbc/testdb");
Cachedds.put ("DS", DS);
}
catch (Exception e)
{
E.printstacktrace ();
}
return DS;
}
/**************************************************************/
/* Function: getconnection
* Function: The connection of the library
* */
private static Connection getconnection () {
Connection conn = null;
Try
{
DataSource ds = localhost ();
conn = Ds.getconnection ();
}
catch (Exception e)
{
E.printstacktrace ();
}
Return conn;
}
/**************************************************************/
/* Function: Close
* Function: Close the connection
* */
private static void Close (Connection conn)
{
Try
{
IF (conn!= null)
Conn.close ();
}
catch (SQLException e)
{
E.printstacktrace ();
}
}
/**************************************************************/
/* Function: ExecuteQuery
* Function: Data query
* */
public static CachedRowSet executequery (String sql)
{
Connection Conn=null;
CachedRowSet Rs=null;
try{
Rs=new CachedRowSet ();
Conn=getconnection ();
Statement stmt=conn.createstatement ();
ResultSet rs1=stmt.executequery (SQL);
Rs.populate (RS1);
}
catch (Exception e)
{
System.out.println (E.tostring ());
}
finally{
Try
{
Conn.close ();
}
catch (Exception ex)
{}
} return RS;
}
/**************************************************************/
/* Function: executeupdate
* Function: Data update (Add/change/delete)
* */
public static Boolean executeupdate (String sql)
{
Boolean bl;
BL = false;
Connection conn = getconnection ();
Try
{
Statement stmt = Conn.createstatement ();
if (stmt.executeupdate (SQL) > 0)
Stmt.close ();
BL = true;
}
catch (SQLException e)
{
}
Finally
{
Close (conn);
}
return BL;
}
/**************************************************************/
}
Compile to get withouttears/db/database.class and put it under e:/myworkspace/test/web-inf/classes, i.e. e:/myworkspace/test/web-inf/classes /withouttears/db/database.class, be careful not to get it wrong.
Step Two: Configure Tomcat (I'm using tomcat 5.5.7)
1. Under C:/Program files/tomcat 5.5.7/conf/catalina/localhost, create a new test.xml, which reads as follows: <context docbase= "E:/MyWorkSpace/ Test "path="/test "></Context>
Note: Docbase is the location of your Web file, and I am using E:/myworkspace/test. Path can not write, but must be written on Linux, Windows does not write my test can be used, it is best to write. The test.xml specified here are not C:/Program Files/tomcat 5.5.7/webapps/test as we normally use, but the same purpose is to use http://localhost:8080/test/to access , which is equivalent to the virtual directory under IIS, can be arbitrary.
2. Establish context.xml under C:/Program files/tomcat 5.5.7/conf/and create a new e:/myworkspace/test under Web-inf/web.xml.
Context.xml
Copy Code code as follows:
<!--the contents of this file is loaded for each Web application-->
<Context>
<!--Default set of monitored resources-->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>META-INF/context.xml</WatchedResource>
<!--uncomment this to disable session persistence across Tomcat restarts-->
<!--
<manager pathname= ""/>
-->
<resource name= "Jdbc/testdb"
Auth= "Container"
Type= "Javax.sql.DataSource"
Driverclassname= "Com.mysql.jdbc.Driver"
Url= "Jdbc:mysql://localhost/mytestdb"
Username= "Root"
Password= "157744375"
Maxactive= "100"
Maxidle= "30"
Maxwait= "10000"
/>
</Context>
Note: The link pool configuration file allows us to read the Jdbc/testdb name in this content.xml using the localhost () function in the JavaBean class database, which is written in the first step
Xml
Copy Code code as follows:
<?xml version= "1.0" encoding= "GBK"?>
<web-app id= "webapp_id" version= "2.4" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" xmlns:xsi= /xmlschema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/j2ee Http://java.sun.com/xml/ns/j2ee/web-app _2_4.xsd ">
<display-name>
Test</display-name>
<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>
<!--jspc servlet mappings Start-->
<!--jspc servlet mappings End-->
</web-app>
Note: Web.xml places the Web's default home page (such as: test.jsp or index.jsp) and the mapping of the servlet in the program, regardless of whether it's not available here.
Step Three: Write test.jsp
Copy Code code as follows:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
<% @page import= "java.sql.*"%>
<% @page import= "withouttears.jdbc.db.*"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<meta http-equiv= "Content-type" content= "text/html; CHARSET=GBK ">
<title>insert title</title>
<body>
<%
String Sql=null;
Sql= "SELECT * from Table_test";
ResultSet rs=database.executequery (SQL);
try{
while (Rs.next ()) {
%>
Name: <%=rs.getstring ("name")%><br>
Tel: <%=rs.getstring ("mobile")%><br>
<%}}catch (Exception e) {}%>
</body>
Step Fourth: Testing