myjavaBean.java
package des;
import java.sql.*;
public class myjavaBean {
private String url;
private String user;
private String password;
private String sql;
public void setUrl(String url)
{
this.url=url;
}
public void setUser(String user)
{
this.user=user;
}
public void setPassword(String password)
{
this.password=password;
}
public void setSql(String sql)
{
this.sql=sql;
}
public String getSql()
{
return sql;
}
public Connection getConnection()
{
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
}
catch(ClassNotFoundException ce)
{
System.out.println(ce);
}
Connection con;
try
{
con=DriverManager.getConnection(url,user,password);
}
catch(Exception e)
{
con=null;
e.printStackTrace();
}
return con;
}
private ResultSet getRs()
{
ResultSet rs=null;
try
{
Statement st=getConnection().createStatement();
rs=st.executeQuery(sql);
}
catch(Exception e)
{
return null;
}
return rs;
}
public String showTable()
{
String tabstr="";
ResultSet rs=getRs();
if (rs==null)
return "Run Error";
tabstr+="<table border=1 >";
try
{
while(rs.next())
{
tabstr+="<tr>";
tabstr+="<td>" ;
tabstr+=rs.getString(1);
tabstr+="</td>";
tabstr+="<td>" ;
tabstr+=rs.getString(2);
tabstr+="</td>";
tabstr+="</tr>";
}
}
catch(SQLException e)
{
return "Read Field eroor";
}
tabstr+="</table>";
return tabstr;
}
}
------------------------------------------------------------------
MyJavaBean.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyJavabean.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
//id是自己命名,指的是本javaBean在JSP中的名字,class的值是本javaBean文件的名字,注意要放在一个包里面,scope值一般是page
<jsp:useBean id="mytab" class="des.myjavaBean" scope="page" >
//这里的property值对应javaBean文件中属性名
<jsp:setProperty name="mytab" property="url" value="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=jyx"/>
<jsp:setProperty name="mytab" property="user" value="sa"/>
<jsp:setProperty name="mytab" property="password" value="" />
<jsp:setProperty name="mytab" property="sql" value="select * from employee"/>
</jsp:useBean>
<% out.write(mytab.showTable());%>//用write调用javaBean文件的方法。
</body>
</html>