Operating environment: JDK 5.0 Tomcat 5.5.4
JDK installation path: d: /java/jdk1.5.0_01tomcat installation path: D: / Tomcat 5.5
Set an environment variable (Control Panel -> System -> Advanced): Java_Home = D: /JAVA/JDK1.5.0_01path=%java_Home%/binclasspath = .; D: /java/jdk1.5.0_01/lib/dt.jar; D: /java/jdk1.5.0_01/lib/tools.jar; D: / Tomcat 5.5 / Common / lib / servlet-api.jar; D: / Tomcat 5.5 / Common / lib / mysql-connector-java-3.1. 6-bin.jar;
Where D: / Tomcat 5.5 / Common / lib / servlet-api.jar is implemented for Tomcat's servlet API implementation, be sure to add, it is better to compile servletd: / tomcat 5.5 / common / lib / mysql-connector-java-3.1.6 -bin.jar; is a MySQL JDBC driver, connect / j 3.1.6, you can go to MySQL official website to download
Tomcat5.5 Virtual Directory Settings: D: / Tomcat 5.5 / Conf / Catalina / LocalHost New Test.xml content is as follows:
D: / WWW path will be the root of our test website, access to this virtual directory with http: // localhost: 8080 / test D: / www, copying a directory web-inf, there is a web.xml setting file (you can refer D: / Tomcat 5.5 / WebApps / root / web-inf / web.xml), classes directory and lib directory
// Java Bean connection database filename dbconn.javapackage NinGoo; import java.sql *;. Public class dbconn {public dbconn () {} // declare variable private Connection conn = null; ResultSet rs = null; private String server = "127.0.0.1"; private string port = "3306"; private string db = "test"; private string user = "root"; private string pass = "password"; private string drivername = "com.mysql.jdbc.driver "; Private string url =" jdbc: mysql: // " server ": " port " / " dB " user = " user " & password = " pass;
public Connection getConn () {// get database connection try {Class.forName (drivername) .newInstance (); conn = DriverManager.getConnection (URL);} catch (Exception e) {e.printStackTrace ();} return this. conn;} public ResultSet executeSQL (String str) {try {Statement stmt = conn.createStatement (); rs = stmt.executeQuery (str);} catch (Exception e) {e.printStackTrace ();} return this.rs; }
Compile Javac dbconn.java, put the compiled file dbconn.class to the directory D: / www / web-inf / classes / ningoo /
// Call the Java Bean's servlet welcome.javaimport java.io. *; Import javax.servlet. *; Import javax.servlet.http. *; Import java.sql. *;
Public class welcome extends httpservlet {public welcome () {}
Public void doget (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException {res. setcontenttype ("text / html");
Connection conn = null; statement stmt = null; resultset = NULL;
Try {ningoo.database.dbconn myconn = new ningoo.database.dbconn (); conn = myconn.getconn (); rs = myconn.executesql ("select * from test"); // Test is a TABLE PRINTWRITER in MySQL OUT = Res.Getwriter (); out.println ("