[jsp]代码库
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%@ page import="java.sql.*" %>
<%!
String str="";
private void tree(Connection conn,int id,int level){
Statement stmt = null;
ResultSet rs = null;
String preStr="";
//前导缩进level表示缩进的层次
for(int i=0;i<level;i++){
preStr+="----";
}
try{
stmt = conn.createStatement();
String url = "select * from articles where pid="+id;
rs = stmt.executeQuery(url);
while(rs.next()){
str += "<tr><td>"+rs.getInt("id")+"</td><td>"+ preStr +
"<a href='detail.jsp?id="+rs.getInt("id")+"'>"+
rs.getString("title") +"</a>"+ "</td></tr>";
if(rs.getInt("isleaf")!=0){//不是叶子节点
tree(conn,rs.getInt("id"),level+1);//如果不是叶子节点,则缩进+1
}
}
}catch(SQLException sql){
sql.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
%>
<%
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/bbs?user=root&password=root";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from articles where pid=0");
while(rs.next()){
str += "<tr><td>"+rs.getInt("id")+"</td><td>"+rs.getString("cont")+"</td></tr>";
if(rs.getInt("isleaf")!=0){
tree(conn,rs.getInt("id"),1);
}
}
rs.close();
stmt.close();
conn.close();
%>