环境: JDK 5.0 + Tomcat 5.5.4
JDK安装路径: D:Javajdk1.5.0_01
Tomcat安装路径:D:Tomcat 5.5
设置环境变量(控制面板-系统-高级):
java_home=D:Javajdk1.5.0_01
path=%JAVA_HOME%bin
classpath=.;D:Javajdk1.5.0_01libdt.jar;D:Javajdk1.5.0_01libtools.jar;D:Tomcat 5.5commonlibservlet-api.jar;D:Tomcat 5.5commonlibmysql-connector-java-3.1.6-bin.jar;
其中D:Tomcat 5.5commonlibservlet-api.jar为Tomcat的servlet API实现,一定要加上,不如无法编译servlet
D:Tomcat 5.5commonlibmysql-connector-java-3.1.6-bin.jar;是MySQL的JDBC驱动,connect/J 3.1.6,可到MySQL官方网站下载
Tomcat5.5虚拟目录设定:
D:Tomcat 5.5confCatalinalocalhost下新加一test.xml
内容如下:
Context path="/test" docBase="d:/www" reloadable="true" crossContext="true" debug="0"
/Context
d:www路径将是我们测试网站的根目录,通过http://localhost:8080/test访问该虚拟目录
d:www下建有目录WEB-INF,下有web.xml设置文件(可参考D:Tomcat 5.5webappsROOTWEB-INFweb.xml),classes目录和lib目录
//连接数据库的Java Bean文件名dbconn.java
package 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;
}
}
编译javac welcome.java,将编译后的文件welcome.class放到目录D:wwwWEB-INFclassesNinGoo下
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)
//调用Java Bean的servlet welcome.java
import 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 rs = null;
try{
NinGoo.database.dbconn myconn =new NinGoo.database.dbconn();
conn = myconn.getConn() ;
rs = myconn.executeSQL("select * from test"); //test是MySQL中的一个table
PrintWriter out=Res.getWriter();
out.println("htmlheadtitletest/title/head");
out.println("body");
while(rs.next()) {
out.println(rs.getString(1));
}
out.println("successfule!/body/html");
}
catch(Exception e){
}
}
}
编译javac welcome.java,将编译后的文件welcome.class放到目录D:wwwWEB-INFclasses下
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)然后修改D:wwwWEB-INFweb.xml,加入如下设置
servlet
servlet-namewelcome/servlet-name
servlet-classwelcome/servlet-class
/servlet
servlet-mapping
servlet-namewelcome/servlet-name
url-pattern/welcome/url-pattern
/servlet-mapping
保存后重启Tomcat,然后在浏览器中敲入http://localhost:8080/test/welcome