大家好.下面是我用用JSP调用BEAN来显示数据的实践.但是编译不能执行.现将代码贴出来.请大家指教.
我的想法是这样的.用servlet把结果集传值给bean,然后用JSP调用bean显示相关值.
我使用的工具是Jbuilder 2006.具体代码如下.请大家指教错在哪里?如何修正.谢谢大家.
首先是DB相关:
package DB;
import java.sql.*;
public class db {
private Connection conn;
private Statement stmt;
private ResultSet rs;
private void preparedDriver() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
public Connection getConn() {
this.preparedDriver();
try {
conn = DriverManager.getConnection(
"jdbc:odbc:test","","");
}
catch (SQLException ex) {
ex.printStackTrace();
}
return conn;
}
public void closeAll() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public db() {
}
}
接着是用bean的内容:
package run;
public class test {
private String name=null;
private int age=0;
public test() {
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
然后是servlert调用数据库并查询相关值:
package DB;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import run.test;
import DB.db.*;
public class SeachSevlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
db sql=new db();
try {
conn = sql.getConn();
stmt = conn.createStatement();
rs=stmt.executeQuery("select * from table");
while(rs.next()){
test bean=new test();
bean.setName(rs.getString(1));
bean.setAge(rs.getInt(2));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
sql.closeAll();
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
最后是jsp调用bean的内容显示相关数据:
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>
GetMsg
</title>
</head>
<body bgcolor="#ffffff">
<table width="782" border="1" align="center" bgcolor="#0099FF">
<tr>
<td><div align="center">姓 名</div>
<td><div align="center">年龄</div>
</tr>
<c:forEach var="list" items="${requestScope.test}">
<tr>
<td width="224"><div align="center"> ${list.name}</div></td>
<td width="139"><div align="center">${list.age}</div></td>
</tr></c:forEach>
</table>
<br>
<br>
</body>
</html>