JSP+Java Bean访问MySQL数据库

类别:Java 点击:0 评论:0 推荐:

运行环境: JDK 5.0 + Tomcat 5.5.4+MySQL4.1.8

JDK安装路径: D:\Java\jdk1.5.0_01
Tomcat安装路径:D:\Tomcat 5.5

设置环境变量(控制面板->系统->高级):
java_home=D:\Java\jdk1.5.0_01
path=%JAVA_HOME%\bin
classpath=.;D:\Java\jdk1.5.0_01\lib\dt.jar;D:\Java\jdk1.5.0_01\lib\tools.jar;D:\Tomcat 5.5\common\lib\mysql-connector-java-3.1.6-bin.jar;

其中D:\Tomcat 5.5\common\lib\mysql-connector-java-3.1.6-bin.jar;是MySQL的JDBC驱动,connect/J 3.1.6,可到MySQL官方网站下载

Tomcat5.5虚拟目录设定:
D:\Tomcat 5.5\conf\Catalina\localhost下新加一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.5\webapps\ROOT\WEB-INF\web.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 void setServer(String str) {//set server name
  server=str;
 }

 public void setPort(String str) {//set server port
  port = str;
 }

 public void setDB(String str) {//set db name
  db = str;
 }

 public void setUser(String str) {//set user name
  user = str;
 }

 public void setPass(String str) {//set user name
  pass = str;
 }

 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:\www\WEB-INF\classes\NinGoo\下

//调用Java Bean的JSP文件test.jsp
<%@ page contentType="text/html;charset=gb2312" import="java.sql.*"%>
<jsp:useBean id="NinGoo" scope="page" class="NinGoo.dbconn" />
<%
ResultSet rs = null;
Connection conn = null;
NinGoo.setServer("127.0.0.1");  //设置MySQL的服务器名或者IP
NinGoo.setPort("3306");            //设置MySQL的监听端口
NinGoo.setDB("test");                //设置MySQL的数据库名
NinGoo.setUser("root");             //设置连接MySQL的用户名
NinGoo.setPass("password");      //设置连接MySQL的密码
conn = NinGoo.getConn() ;
rs = NinGoo.executeSQL("select * from test");
while(rs.next()) {
%>
    Row:<%=rs.getString(1)%>
<%}%>
<%out.print("Successful!\n");%>  
<%
rs.close();
conn.close();
%>

然后在浏览器中访问http://localhost:8080/test/test.jsp,恭喜成功!

本文地址:http://com.8s8s.com/it/it11620.htm