<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!--
数据库结构:
库名:test
表名:tree
CREATE TABLE [dbo].[tree] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[parentid] [int] NOT NULL ,
[message] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
)
为了达到比较好的效果,这里准备了五张小图片
加号:plus.gif
减号:minus.gif
打开的文件夹:openfold.gif
关闭的文件夹:closedfold.gif
白板:white.gif
-->
<%!//方便起见这里就不写成javabean了
class cn {//连接数据库,这里以MS-SQL为例
String jdbcDriver="com.microsoft.jdbc.sqlserver.SQLServerDriver";//jdbc驱动
String connectionString="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";//数据库连接字符串
String user="sa";//数据库用户名
String pass="";//数据库密码
Connection conn=null;
ResultSet rs=null;
public cn() {
try {
Class.forName(jdbcDriver);
} catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
public ResultSet executeQuery(String sql) {
rs=null;
try {
conn=DriverManager.getConnection(connectionString,user,pass);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(sql);
}
catch(SQLException e) {
System.err.println(e.toString());
}
return rs;
}
public void executeUpdate(String sql) {
try {
conn=DriverManager.getConnection(connectionString,user,pass);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(sql);
}
catch(SQLException e) {
System.err.println(e.toString());
}
}
}
class tree {
cn conn=new cn();
public void init(javax.servlet.jsp.JspWriter out,javax.servlet.http.HttpServletRequest request) throws Exception {
out.println("<title>用jsp种树</title>");
dowith(request);
buildTree(out,0,0);//初始调用
}
private void dowith(javax.servlet.http.HttpServletRequest request) {
if(request.getParameter("parentid")==null||request.getParameter("parentid").equals(""))return;
String action=request.getParameter("action");
if(action.equals("add"))
conn.executeUpdate("insert into tree(parentid,message) values('"+request.getParameter("parentid")+"','"+request.getParameter("message")+"')");
else if(action.equals("delete"))
conn.executeUpdate("delete from tree where id="+request.getParameter("parentid")+" or parentid="+request.getParameter("parentid"));
}
public void buildTree(javax.servlet.jsp.JspWriter out,int parentid,int level) throws Exception {
level++;
ResultSet rs=conn.executeQuery("select * from tree where parentid="+parentid+" order by id");
while(rs.next()) {
out.println("<div>");
for(int i=0;i<level-1;i++)
out.print("<img src="/Files/Pic/Img/JavaDB/0682513240788712.gif"\"> ");
if(has_child(rs.getInt("id"))) {
out.print("<img alt=\"展开\" style=\"cursor:hand;\" onclick=\"myClick('"+rs.getInt("id")+"');\" id=\"img"+rs.getInt("id")+"\" src="/Files/Pic/Img/JavaDB/0682513240755500.gif"\"> <img id=\"im"+rs.getInt("id")+"\" src="/Files/Pic/Img/JavaDB/0682513240721011.gif"\"> ");






