zoukankan      html  css  js  c++  java
  • 马士兵讲jsp项目--BBS项目分析笔记

    1 导言

    作为一个新手JAVA程序员,我相信很多人和我一样急切的想要寻找项目来做,这里我把马士兵老师讲的JAVA WEB的第一个小项目拿过来给大家分享一下。

    首先,对一个项目而言我们先要认识清楚我们要做什么。这里我们要做的是一个模拟的小型BBS,内容分为以下几块:

    1、树形展示回帖内容

    2.、详细展示帖子内容

    3、回复帖子功能

    4、管理员登陆功能

    5、删除功能

    对这个项目而言,我们使用纯JSP最为联系语言,以后使用JSP+JAVABEAN这种主流的方法。纯JSP将事物与展示放在一起做,业务逻辑混乱,但是做一次来培养我们的业务逻辑思考,在这个过程中我们会体会到这种不足,之后自然而然的会投入到JAVABEAN+JSP的怀抱中。

    2 数据库分析

    作为一个BBS网站,我们主要做的是将数据库中的内容在网页上展示出来,所以我们需要一个良好的数据库作为我们的测试数据。

    数据库如下:

    create database bbs;
    
    use bbs;
    
    create table article 
    (
    id int primary key auto_increment,
    pid int,
    rootid int,
    title varchar(255),
    cont text,
    pdate datetime,
    isleaf int 
    );
    
    insert into article values (null, 0, 1, '蚂蚁大战大象', '蚂蚁大战大象', now(), 1);
    insert into article values (null, 1, 1, '大象被打趴下了', '大象被打趴下了',now(), 1);
    insert into article values (null, 2, 1, '蚂蚁也不好过','蚂蚁也不好过', now(), 0);
    insert into article values (null, 2, 1, '瞎说', '瞎说', now(), 1);
    insert into article values (null, 4, 1, '没有瞎说', '没有瞎说', now(), 0);
    insert into article values (null, 1, 1, '怎么可能', '怎么可能', now(), 1);
    insert into article values (null, 6, 1, '怎么没有可能', '怎么没有可能', now(), 0);
    insert into article values (null, 6, 1, '可能性是很大的', '可能性是很大的', now(), 0);
    insert into article values (null, 2, 1, '大象进医院了', '大象进医院了', now(), 1);
    insert into article values (null, 9, 1, '护士是蚂蚁', '护士是蚂蚁', now(), 0);

    对于BBS中每个帖子的内容,首先我们要有帖子id,他回复的是哪个楼pid,以及主题rootid,回复内容的“主题title+正文cont”,回复日期pdate,是否为叶子节点即是否没有人回复他。对于一个小型测试用数据库已经足够,业务逻辑正确就行,我们不考虑界面美观,毕竟这是我们的练手项目。

    三 JSP代码

    1 树形展示帖子主题

    每个bbs都有一个入口界面,BBS入口界面基本上都是以树形展示为主,比如百度贴吧与天涯论坛。代码如下:

    <%@ page language="java" contentType="text/html; charset=gbk"
        pageEncoding="gbk"%>
    <%@ page import="java.sql.*" %>
    
    <%//检查管理员session是否登陆,若登陆显示删除按钮
    String admin = (String)session.getAttribute("admin");
    if(admin != null && admin.equals("true")) {
        login = true;
    }
    %>
    
    <%!
    String str = "";//全局声明,保存需要打印的字符串,即显示内容
    boolean login = false;//默认设为管理员未登录
    private void tree(Connection conn, int id, int level) {
        Statement stmt = null;
        ResultSet rs = null;
        String preStr = "";
        for(int i=0; i<level; i++) {//层次化结构显示,level为传入参数
            preStr += "----";
        }
        try {
            stmt = conn.createStatement();
            String sql = "select * from article where pid = " + id;
            rs = stmt.executeQuery(sql);
            String strLogin = "";
            
            while(rs.next()) {//递归查询该节点下是否还有子节点,先打印自己节点,再打印子节点
                if(login) {
                    strLogin = "<td><a href='Delete.jsp?id=" + rs.getInt("id") + "&pid=" + rs.getInt("pid") + "'>删除</a>";
                }//字符串用于控制是否显示删除按钮
                str += "<tr><td>" + rs.getInt("id") + "</td><td>" +
                       preStr + "<a href='ShowArticleDetail.jsp?id=" + rs.getInt("id") + "'>" + 
                       rs.getString("title") + "</a></td>" +
                       strLogin +
                       "</td></tr>";
                if(rs.getInt("isleaf") != 0) {//如果不是叶子节点,证明还存在子节点,递归打印
                    tree(conn, rs.getInt("id"), level+1);
                }
            }
        } catch (SQLException e) {
            e.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=123456";
    Connection conn = DriverManager.getConnection(url);
    
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from article where pid = 0");
    String strLogin = "";
    while(rs.next()) {
        if(login) {
            strLogin = "<td><a href='Delete.jsp?id=" + rs.getInt("id") + "&pid=" + rs.getInt("pid") + "'>删除</a>";
        }
        str += "<tr><td>" + rs.getInt("id") + "</td><td>" +
               "<a href='ShowArticleDetail.jsp?id=" + rs.getInt("id") + "'>" + 
               rs.getString("title") + "</a></td>" +
               strLogin +
               "</td></tr>";
           if(rs.getInt("isleaf") != 0) {
               tree(conn, rs.getInt("id"), 1);
           }
    }
    rs.close();
    stmt.close();
    conn.close();
    %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
    <a href="Post.jsp">发表新帖</a>
    <table border="1">
    <%= str %>
    <% 
    str = ""; //清空str,否则每刷新一次打印一次
    login = false;//清空登录位
    %>
    </table>
    </body>
    
    </html>

    2 详情页面

    在上面的页面中我们加入了查看详情的链接,这里我们写详情链接

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="java.sql.*" %>
    <%
    String strid = request.getParameter("id");//查看上个页面,我们需要查询的内容传来了id,这里第一步就是接受id
    int id = Integer.parseInt(strid);//传来的参数默认为字符串,我们转换为int类型,便于sql查询
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/bbs?user=root&password=123456";
    Connection conn = DriverManager.getConnection(url);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from article where id = "+ id);
        
     %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    if(rs.next()){//查询只能拿到一条记录,这里用if就行,用table展示出来
    %>
        <table border="1">
            <tr>
                <td>ID</td>
                <td><%= rs.getInt("id") %></td>
            </tr>
            <tr>
                <td>Title</td>
                <td><%= rs.getString("title") %></td>
            </tr>
                    <tr>
                <td>Content</td>
                <td><%= rs.getString("cont") %></td>
            </tr>
        </table>
    
    <%--加入回复链接,指向回复页面,需要传入参数为,回复楼的id,以及帖子id,这里rootid不是必要参数,加上可以简化流程 --%>
     <a href="Reply.jsp?id=<%= rs.getInt("id")%>&rootid=<%= rs.getString("rootid")%>">回复</a>
     <%    
    }//记得打开的东西要逆序关闭
    rs.close();
    stmt.close();
    conn.close();
     %>
    </body>
    </html>

    3 回复页面

    <%@ page language="java" contentType="text/html; charset=gbk"
        pageEncoding="gbk"%>
    
    
    <%//任何情况下都是先接受传递过来的参数
    int id = Integer.parseInt(request.getParameter("id"));
    int rootId = Integer.parseInt(request.getParameter("rootid"));
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    
    <script language="javascript">
    <!--    
        //javascript去空格函数 
        function LTrim(str){ //去掉字符串 的头空格
            var i;
            for(i=0;i<str.length; i++) {
                if(str.charAt(i)!=" ") break;
            }
            str = str.substring(i,str.length);
            return str;
        }
        
        function RTrim(str){
            var i;
            for(i=str.length-1;i>=0;i--){
                if(str.charAt(i)!=" "&&str.charAt(i)!=" ") break;
            }
            str = str.substring(0,i+1);
            return str;
        }
        function Trim(str){
        
            return LTrim(RTrim(str));
        
        }
        
        function check() {
            if(Trim(document.reply.title.value) == "") {
                alert("please intput the title!");
                document.reply.title.focus();
                return false;
            }
            
            if(Trim(document.reply.cont.value) == "") {
                alert("plsease input the content!");
                document.reply.cont.focus();
                return false;
            }
            
            return true;
            
        }
    -->
    </script>
    
    </head>
    <body>
    <form name=reply action="ReplyOK.jsp" method="post" onsubmit="return check()">
        <input type="hidden" name="id" value="<%=id %>">
        <input type="hidden" name="rootid" value="<%= rootId %>">
        <table border="1">
            <tr>
                <td>
                    <input type="text" name="title" size="80">
                </td>
            </tr>
            <tr>
                <td>
                    <textarea cols="80" rows="12" name="cont"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="提交">
                </td>
            </tr>
        </table>
    </form>
    </body>
    </html>

    4 回复成功,调转显示

    任何帖子回复成功后都要进行跳转,否则用户需要手动点击,太不人性化

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="java.sql.*" %>
    <%
    request.setCharacterEncoding("gbk");//request采用默认编码,我们给他转换成中文编码
    int id = Integer.parseInt(request.getParameter("id"));//第一步,接受传递过来的参数
    int rootid = Integer.parseInt(request.getParameter("rootid"));
    String title = request.getParameter("title");
    String cont = request.getParameter("cont");
    
    if(title == null) {//虽然前台检查过了,后台仍然要检查
        out.println("error! please use my bbs in the right way!");
        return;
    }
    
    title = title.trim();
    
    if(title.equals("")) {
        out.println("title could not be empty!");
        return;
    }
    
    cont = cont.trim();
    
    if(cont.equals("")) {
        out.println("content could not be empty!");
        return;
    }
    
    cont = cont.replaceAll("
    ", "<br>");//将用户输入域得到的字符串中的回车用html中的换行符替换
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/bbs?user=root&password=123456";
    Connection conn = DriverManager.getConnection(url);
    conn.setAutoCommit(false);//我们回复过的楼层必然不再是叶子节点,因此这里要用事物处理,关闭自动提交
    String sql = "insert into article values(null,?,?,?,?,now(),0)";
    PreparedStatement pstmt = conn.prepareStatement(sql);//sql语句过于负责,我们用PreparedStatement进行简便操作
    Statement stmt = conn.createStatement();
    
    pstmt.setInt(1,id);
    pstmt.setInt(2,rootid);
    pstmt.setString(3, title);
    pstmt.setString(4, cont);
    pstmt.executeUpdate();
    
    stmt.executeUpdate("update article set isleaf = 1 where id = "+id);
    
    conn.commit();
    conn.setAutoCommit(true);//回复自动提交功能
    
    stmt.close();
    pstmt.close();
    conn.close();
     %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    response.sendRedirect("ShowArticleTree.jsp");//重定向到入口界面
     %>
    </body>
    </html>

    5 发表新帖

    <%@ page language="java" contentType="text/html; charset=gbk"
        pageEncoding="gbk"%>
    <%@ page import="java.sql.*" %>
    
    <%
    
    request.setCharacterEncoding("gbk");
    String action = request.getParameter("action");//接受传递给自己的参数
    if(action != null && action.equals("post")) {
    	String title = request.getParameter("title");
    	String cont = request.getParameter("cont");
    	
    	cont = cont.replaceAll("
    " , "<br>");//将回车符换为html重的换行符
    	
    	Class.forName("com.mysql.jdbc.Driver");
    	String url = "jdbc:mysql://localhost/bbs?user=root&password=123456";
    	Connection conn = DriverManager.getConnection(url);
    	
    	conn.setAutoCommit(false);
    	
    	String sql = "insert into article values (null, 0, ?, ?, ?, now(), 0)";
    	PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    	Statement stmt = conn.createStatement();
    	
    	pstmt.setInt(1, -1);
    	pstmt.setString(2, title);
    	pstmt.setString(3, cont);
    	pstmt.executeUpdate();
    	
    	ResultSet rsKey = pstmt.getGeneratedKeys();
    	rsKey.next();
    	int key = rsKey.getInt(1);
    	rsKey.close();
    	stmt.executeUpdate("update article set rootid = " + key + " where id = " + key);
    	
    	conn.commit();
    	conn.setAutoCommit(true);
    	
    	stmt.close();
    	pstmt.close();
    	conn.close();
    	
    	response.sendRedirect("ShowArticleFlat.jsp");//重定向到平面显示
    }
    %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="Post.jsp" method="post">
    	<input type="hidden" name="action" value="post">
    	<table border="1">
    		<tr>
    			<td>
    				<input type="text" name="title" size="80">
    			</td>
    		</tr>
    		<tr>
    			<td>
    				<textarea cols="80" rows="12" name="cont"></textarea>
    			</td>
    		</tr>
    		<tr>
    			<td>
    				<input type="submit" value="提交">
    			</td>
    		</tr>
    	</table>
    </form>
    </body>
    </html>


    6 删除功能

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ page import="java.sql.*" %>
    <%!//递归判断该id下面是否有子结点,有的话递归,最后删除自己
    private void del(Connection conn,int id){
    	Statement stmt = null;
    	ResultSet rs = null;
    	try{
    		stmt = conn.createStatement();
    		String sql = "select * from article where pid = "+ id;//查询该id下的所有内容,因此该id应作为pid查询
    		rs = stmt.executeQuery(sql);
    		while(rs.next()){//查询到的结果集进行一条一条循环迭代
    			del(conn,rs.getInt("id"));
    		}
    		stmt.executeUpdate("delete from article where id = " + id);
    	} catch(SQLException e){
    		e.printStackTrace();
    	} finally{
    		try{
    			if(rs != null){//注意异常的捕获,这样处理更加严谨
    				rs.close();
    				rs = null;
    			}
    			if(stmt != null){
    				stmt.close();
    				stmt = null;
    			}
    		
    		} catch(SQLException e){
    			e.printStackTrace();
    		}
    	}
    }
     %>
     <%
    String admin = (String)session.getAttribute("admin");
    if(admin == null || !admin.equals("true")) {
    	out.println("孙贼,别想找BUG来删除!");
    	return;
    }
      %>
    <%
    int id = Integer.parseInt(request.getParameter("id"));//第一步,接受传递过来的参数
    int pid = Integer.parseInt(request.getParameter("pid"));//第一步,接受传递过来的参数
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/bbs?user=root&password=123456";
    Connection conn = DriverManager.getConnection(url);
    conn.setAutoCommit(false);//我们回复过的楼层必然不再是叶子节点,因此这里要用事物处理,关闭自动提交
    del(conn,id);
    
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select count(*) from article where pid = " + pid);
    rs.next();
    int count = rs.getInt(1);
    rs.close();
    stmt.close();
    if (count <= 0){
    	Statement stmtUpdate = conn.createStatement();
    	stmtUpdate.executeUpdate("update article set isleaf = 0 where id = " + pid);
    	stmtUpdate.close();
    }
    conn.commit();
    conn.setAutoCommit(true);//回复自动提交功能
    conn.close();
     %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    response.sendRedirect("ShowArticleTree.jsp");//重定向到入口界面
     %>
    </body>
    </html>


    7 登陆页面

    登陆页面主要有美工来做,这里的代码主要看业务逻辑

    <%@ page contentType="text/html; charset=gbk" pageEncoding="gbk" %>
    
    <%
    String action = request.getParameter("action");
    if(action != null && action.equals("login")) {
    	String username = request.getParameter("uname");
    	String password = request.getParameter("pwd");
    	if(username == null || !username.equals("admin")) {
    		%>
    		<font color="white" size=5>username not correct!</font>
    		<%
    		//return;
    	}else if(password == null || !password.equals("admin")) {
    		out.println("password not correct!");
    		//return;
    	}else {
    		session.setAttribute("admin", "true");
    		response.sendRedirect("ShowArticleTree.jsp");
    	}
    }
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <!-- saved from url=(0054)http://www.simworld.com/client_access/client_login.asp -->
    <HTML><HEAD><TITLE>SIM - Client Access - Login</TITLE>
    <META http-equiv=Content-Type content="text/html; charset=gbk" pageEncoding="gbk"><LINK 
    href="images/sim_stylesheet.css" type=text/css 
    rel=styleSheet>
    <SCRIPT language=JavaScript src="" type=text/javascript></SCRIPT>
    
    <SCRIPT language=JavaScript src="" type=text/javascript></SCRIPT>
    
    <SCRIPT language=JavaScript src="" type=text/javascript></SCRIPT>
    
    <META content="MSHTML 6.00.2900.2963" name=GENERATOR>
    <style type="text/css">
    <!--
    .STYLE1 {color: #CCCCCC}
    -->
    </style>
    
    </HEAD>
    <BODY bgColor=#20355a leftMargin=0 topMargin=0 onload=init() marginheight="0" 
    marginwidth="0"><!--Begin all TOP NAVIGATIOND ROPDOWN LAYERS ------------><!--Begin About Sim Dropdown 1 -->
    <DIV id=about_sim_drop1>
    <TABLE cellSpacing=0 cellPadding=0 width=140 border=0>
      <TBODY>
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width=140 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width=130><A class=topnav 
                onmouseover="stopTime(); showLayer('about_sim_corporate_drop2'); hideLayer('about_sim_portfolio_drop2');" 
                onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/index.asp">Corporate 
                Info</A></TD>
              <TD vAlign=top width=10><IMG height=10 alt=arrow 
                src="images/nav_arrows.gif" 
            width=10></TD></TR></TBODY></TABLE></TD></TR><!-- 
    	<tr> 
           <td bgcolor="#CACFDA"> 
             <table width="140" border="0" cellspacing="2" cellpadding="2">
               <tr> 
                 <td width="130" valign="top" align="left"><a href="/about_sim/services/index.asp" onMouseOver="stopTime(); hideLayer('about_sim_corporate_drop2');" onMouseOut="startTime();" class="topnav">Services</a></td>
                 <td width="10" valign="top"><img src="/pics/spacer.gif" alt="" width="10" height="10"></td>
               </tr>
             </table>
           </td>
         </tr>
    -->
      <TR>
        <TD bgColor=#cacfda>
          <TABLE cellSpacing=2 cellPadding=2 width=140 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width=130><A class=topnav 
                onmouseover="stopTime(); hideLayer('about_sim_corporate_drop2');" 
                onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/products/index.asp">Products</A></TD>
              <TD vAlign=top width=10><IMG height=10 alt="" 
                src="images/spacer.gif" 
            width=10></TD></TR></TBODY></TABLE></TD></TR><!--<tr> 
           <td bgcolor="#CACFDA"> 
             <table width="140" border="0" cellspacing="2" cellpadding="2">
               <tr> 
                 <td width="130" valign="top" align="left"><a href="/about_sim/portfolio/index1.asp" onMouseOver="stopTime(); showLayer('about_sim_portfolio_drop2'); hideLayer('about_sim_corporate_drop2');" onMouseOut="startTime();" class="topnav">Portfolio</a></td>
                 <td width="10" valign="top"><img src="/pics/nav_arrows.gif" alt="arrow" width="10" height="10"></td>
               </tr>
             </table>
           </td>
         </tr>-->
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width=140 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width=130><A class=topnav 
                onmouseover=stopTime(); 
                onmouseout="startTime(); hideLayer('about_sim_corporate_drop2');" 
                href="http://www.simworld.com/about_sim/portfolio/index_temp.asp">Portfolio</A></TD>
              <TD vAlign=top width=10><IMG height=10 alt=arrow 
                src="images/spacer.gif" 
            width=10></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></DIV><!-- End About Sim Dropdown 1 --><!--Begin About Sim Corporate Dropdown 2 -->
    <DIV id=about_sim_corporate_drop2>
    <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
      <TBODY>
      <TR>
        <TD bgColor=#cacfda>
          <TABLE cellSpacing=2 cellPadding=2 width="100%" border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width="100%"><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/mission.asp">Mission</A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width="100%" border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width="100%"><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/philosophy.asp">Philosophy</A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#cacfda>
          <TABLE cellSpacing=2 cellPadding=2 width="100%" border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width="100%"><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/team.asp">Team</A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width="100%" border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width="100%"><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/specialty.asp">Specialty 
                Markets </A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#cacfda>
          <TABLE cellSpacing=2 cellPadding=2 width="100%" border=0>
            <TBODY>
            <TR>
              <TD vAlign=top align=left width="100%"><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/about_sim/corporate/news.asp">News 
                & Awards</A></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></DIV><!--Begin About Sim Corporate Dropdown 2 --><!--Begin About Sim Portfolio Dropdown 2 -->
    <DIV id=about_sim_portfolio_drop2><!--<table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr> 
        <td bgcolor="#CACFDA"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/about_sim/portfolio/websites.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav">Websites</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#FFFFFF"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/about_sim/portfolio/multimedia.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav">Multimedia Presentations</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#CACFDA"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/about_sim/portfolio/print_graphic_design.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav" target="_blank">Print / Graphic Design</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#FFFFFF"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/about_sim/client_list.pdf" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav" target=_"blank">Client List (PDF)</a></td>
            </tr>
          </table>
        </td>
      </tr>
    </table>--></DIV><!--Begin About Sim Portfolio Dropdown 2 --><!--Begin Client Access Dropdown 1 -->
    <DIV id=client_access_drop1><!--<table width="140" border="0" cellspacing="0" cellpadding="0">
         <tr> 
           <td bgcolor="#FFFFFF"> 
             <table width="140" border="0" cellspacing="2" cellpadding="2">
               <tr> 
                 <td width="130" valign="top" align="left"><a href="/client_access/client_login.asp" onMouseOver="stopTime(); hideLayer('client_access_customer_drop2');" onMouseOut="startTime();" class="topnav">Client Login</a></td>
                 <td width="10" valign="top"><img src="/pics/spacer.gif" alt="" width="10" height="10"></td>
               </tr>
             </table>
           </td>
         </tr>
         <tr> 
           <td bgcolor="#CACFDA"> 
             <table width="140" border="0" cellspacing="2" cellpadding="2">
               <tr> 
                 <td width="130" valign="top" align="left"><a href="/client_access/customerservice/index1.asp" onMouseOver="stopTime(); showLayer('client_access_customer_drop2');" onMouseOut="startTime();" class="topnav">Customer Service</a></td>
                 <td width="10" valign="top"><img src="/pics/nav_arrows.gif" alt="arrow" width="10" height="10"></td>
               </tr>
             </table>
           </td>
         </tr>
         <tr> 
           <td bgcolor="#FFFFFF"> 
             <table width="140" border="0" cellspacing="2" cellpadding="2">
               <tr> 
                 <td width="130" valign="top" align="left"><a href="/under_construction.asp" onMouseOver="stopTime(); hideLayer('client_access_customer_drop2');" onMouseOut="startTime();" class="topnav">Beyond Today</a></td>
                 <td width="10" valign="top"><img src="/pics/spacer.gif" alt="" width="10" height="10"></td>
               </tr>
             </table>
           </td>
         </tr>
       </table>--></DIV><!-- End Client Access Dropdown 1 --><!--Begin Client Access Customer Service Dropdown 2 -->
    <DIV id=client_access_customer_drop2><!--<table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr> 
        <td bgcolor="#CACFDA"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/client_access/customerservice/policy1.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav">Our Policy</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#FFFFFF"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/client_access/customerservice/help1.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav">Help</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#CACFDA"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/client_access/customerservice/downloads1.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav">Downloads</a></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr> 
        <td bgcolor="#FFFFFF"> 
          <table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr> 
                <td width="100%" valign="top" align="left"><a href="/client_access/customerservice/tech_standards1.asp" onMouseOver="stopTime();" onMouseOut="startTime();" class="topnav" target=_"blank">Technical Standards</a></td>
            </tr>
          </table>
        </td>
      </tr>
    </table>--></DIV><!-- End Client Access Customer Service Dropdown 2 --><!--Begin Join our Team Dropdown 1 -->
    <DIV id=join_our_team_drop1>
    <TABLE cellSpacing=0 cellPadding=0 width=150 border=0>
      <TBODY>
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width=150 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top width=10><IMG height=10 alt="" 
                src="images/client_access.htm" 
              width=10></TD>
              <TD vAlign=top align=right width=140><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/join_our_team/job_openings.asp">Job 
                Openings</A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#cacfda>
          <TABLE cellSpacing=2 cellPadding=2 width=150 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top width=10><IMG height=10 alt="" 
                src="images/spacer.gif" width=10></TD>
              <TD vAlign=top align=right width=140><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/join_our_team/apply_online.asp">Employee 
                Benefits</A></TD></TR></TBODY></TABLE></TD></TR>
      <TR>
        <TD bgColor=#ffffff>
          <TABLE cellSpacing=2 cellPadding=2 width=150 border=0>
            <TBODY>
            <TR>
              <TD vAlign=top width=10><IMG height=10 alt="" 
                src="images/spacer.gif" width=10></TD>
              <TD vAlign=top align=right width=140><A class=topnav 
                onmouseover=stopTime(); onmouseout=startTime(); 
                href="http://www.simworld.com/join_our_team/corp_culture.asp">Corporate 
                Culture</A></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></DIV><!-- End Join Our Team  Dropdown 1 --><!--End all TOP NAVIGATIOND ROPDOWN LAYERS ------------><!--Begin Browser Spanning Table, this allows Main Web Site Table to be centered in the middle of the browser -->
    <TABLE height="100%" cellSpacing=0 cellPadding=0 width="100%" align=center 
    border=0>
      <TBODY>
      <TR>
        <TD><!--Begin Main Web Site Table All Website Design elements below-->
          <TABLE borderColor=#ffffff cellSpacing=0 cellPadding=0 width=760 
          align=center border=1>
            <TBODY>
            <TR>
              <TD>
                <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
                  <TBODY>
                  <TR>
                    <TD><!-- Begin Top Logo, Navigation and Message bar Table -->
                      <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0><!--Beign Global Nav Buttons --->
                        <TBODY>
                        <TR>
                          <TD rowSpan=2><IMG height=53 
                            alt="Screened Images Multimedia" 
                            src="images/sim_logo_top.gif" 
                            width=136 useMap=#top_logo_map border=0><MAP 
                            name=top_logo_map><AREA shape=RECT 
                              alt="Screened Images Multimedia [Back to Home]" 
                              coords=11,4,120,54 
                              href="http://www.simworld.com/index.asp"></MAP></TD>
                          <TD><span class="STYLE1">欢迎来到
                            著名的BBS后台</span></TD>
                        </TR>
                        <TR><!--End Global Nav Buttons --->
                          <TD><span class="STYLE1">不输入用户名密码不许进 用户名: admin 密码: admin </span></TD>
                        </TR></TBODY></TABLE><!-- End Top Logo, Navigation and Message bar Table --></TD></TR>
                  <TR>
                    <TD><!-- Begin Inner Content Table:  This portion will be customizable throughout the website -->
                      <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
                        <TBODY>
                        <TR>
                          <TD><IMG height=324 alt="" 
                            src="images/client_login_left_arc.gif" 
                            width=137 useMap=#bot_logo_map border=0><MAP 
                            name=bot_logo_map><AREA shape=RECT 
                              alt="Screened Images Multimedia [Back to Home]" 
                              coords=11,0,120,24 
                              href="http://www.simworld.com/index.asp"></MAP></TD>
                          <TD>
                            <TABLE cellSpacing=0 cellPadding=0 width="100%" 
    border=0>
                              <TBODY>
                              <TR>
                                <TD><IMG height=91 alt="CLIENT LOG-IN" 
                                  src="images/client_login_title.gif" 
                                  width=282></TD></TR>
                              <TR>
                                <TD>
                                  <FORM action=Login.jsp method=post>
                                  <input type=hidden name=action value=login>
                                  <TABLE cellSpacing=0 cellPadding=0 width="100%" 
                                  background="images/client_login_text_bg.gif" 
                                  border=0>
                                    <TBODY>
                                    <TR>
                                    <TD rowSpan=4><IMG height=158 alt="" 
                                    src="images/spacer.gif" 
                                    width=22 border=0></TD>
                                    <TD colSpan=2>
                                    <P class=bodydarkblue>Please enter your username 
                                    and password here to preview your designs, check 
                                    project status and/or submit new job 
                                    requests.</P></TD></TR>
                                    <TR>
                                    <TD>
                                    <P class=bodyldarkblue><LABEL 
                                    for=uname>用户名:</LABEL></P></TD>
                                    <TD><INPUT id=uname name=uname></TD></TR>
                                    <TR>
                                    <TD>
                                    <P class=bodyldarkblue><LABEL 
                                    for=pwd>密码:</LABEL></P></TD>
                                    <TD><INPUT id=pwd type=password 
                                    name=pwd></TD></TR>
                                    <TR>
                                    <TD vAlign=top colSpan=2><A class=bodydarkblue 
                                    href="http://www.simworld.com/client_access/client_login.asp"><STRONG><!--Forget your password?--></STRONG></A><IMG 
                                    height=1 alt="" 
                                    src="images/spacer.gif" 
                                    width=132 
                                    border=0>     <INPUT 
                                    type=image alt=Submit 
                                    src="images/client_login_submit.gif" 
                                    align=absMiddle value=Submit 
                                    name=Submit></TD></TR></TBODY></TABLE></TD></TR>
                              <TR>
                                <TD><IMG height=75 alt="" 
                                  src="images/client_login_bot_arc.gif" 
                                  width=282></TD></TR></TBODY></TABLE></TD>
                          <TD><IMG height=324 alt="Log-in Image" 
                            src="images/client_login_main_pic.jpg" 
                            width=341></TD></TR></TBODY></TABLE><!-- End Inner Content Table --------></TD></TR>
                  <TR>
                    <TD><!-- Begin Bottom Navigation: Contact Us, Request A- Quote -->
                      <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
                        <TBODY>
                        <TR>
                          <TD><A 
                            onmouseover="Rollover('nav_homepage_a','nav_homepage');" 
                            onmouseout="Rollover('nav_homepage','nav_homepage');" 
                            href="http://www.simworld.com/index.asp"></A><IMG height=26 
                            alt="" 
                            src="images/interior_bot_nav_bar.gif" 
                            width=100%></TD>
                        </TR>
                        <TR>
                          <TD><IMG height=12 
                            alt="Copyright 2003 Screened Images, Inc." 
                            src="images/bot_footer_bar.gif" 
                            width=760></TD></TR></TBODY></TABLE><!-- End Bottom Navigation: Contact Us, Request A- Quote --></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE><!--End Main Web Site Table --></TD></TR></TBODY></TABLE><!--End Browser Spanning Table --></BODY></HTML>
    


    8 平面展示

    <%@ page language="java" contentType="text/html; charset=gbk"
    	pageEncoding="gbk"%>
    <%@ page import="java.sql.*"%>
    
    
    <%
    	int pageSize = 3;//定义一页显示多少条数据
    
    	String strPageNo = request.getParameter("pageNo");//接受当前页数
    	int pageNo;
    	if (strPageNo == null || strPageNo.equals("")) {
    		pageNo = 1;//若没有则默认第一页
    	} else {
    		try {
    			pageNo = Integer.parseInt(strPageNo.trim());
    		} catch (NumberFormatException e) {
    			pageNo = 1;
    		}
    		if (pageNo <= 0)//不合法页默认第一页
    			pageNo = 1;
    	}
    
    	Class.forName("com.mysql.jdbc.Driver");
    	String url = "jdbc:mysql://localhost/bbs?user=root&password=123456";
    	Connection conn = DriverManager.getConnection(url);
    
    	Statement stmtCount = conn.createStatement();
    	ResultSet rsCount = stmtCount
    			.executeQuery("select count(*) from article where pid = 0");//拿出父亲节点为0的,即主题帖
    	rsCount.next();
    	int totalRecords = rsCount.getInt(1);
    
    	int totalPages = totalRecords % pageSize == 0 ? totalRecords
    			/ pageSize : totalRecords / pageSize + 1;//若可以整除则显示多少页,否则+1页
    	if (pageNo > totalPages)
    		pageNo = totalPages;//指定最多页数不可溢出
    
    	int startPos = (pageNo - 1) * pageSize;//确定mysql中要取出来的数据位置
    
    	Statement stmt = conn.createStatement();
    	ResultSet rs = stmt
    			.executeQuery("select * from article where pid = 0 order by pdate desc limit "
    			+ startPos + "," + pageSize);//利用mysql中的分页来显示
    %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
    <a href="Post.jsp">发表新帖</a>
    
    <table border="1">
    
    	<%
    	while (rs.next()) {
    	%>
    	<tr>
    		<td><%=rs.getString("title")%></td>
    	</tr>
    	<%
    	}
    	rs.close();
    	stmt.close();
    	conn.close();
    	%>
    </table>
    
    共<%=totalPages%>页 第<%=pageNo%>页
    <a href="ShowArticleFlat.jsp?pageNo=<%=pageNo-1%>"> < </a>   <%--传递给本页要显示的页数 --%>
        
    <a href="ShowArticleFlat.jsp?pageNo=<%=pageNo+1%>"> > </a>
    
    <form name="form1" action="ShowArticleFlat.jsp"><%--动态提交数据--%>
    	<select name="pageNo" onchange="document.form1.submit()">
    		<%
    		for(int i=1; i<=totalPages; i++) {
    		%>
    		<option value=<%=i%> <%=(pageNo == i) ? "selected" : ""%>> 第<%=i%>页
    		<%
    		}
    		%>
    	</select>
    </form>
    
    <form name="fom2" action="ShowArticleFlat.jsp">
    	<input type=text size=4 name="pageNo" value=<%=pageNo%> />
    	<input type="submit" value="go" />
    </form>
    
    </body>
    
    </html>
    


    3 总结

    到此为止,一个纯JSP的BBS完成,大家应该感觉到了头绪有点乱的感觉,正是由于这种感觉,我们之后会采取jsp+javabean的方法来开发,那样代码逻辑性看上去会强很多。

    给大家一个建议:这些代码都是先写出来功能模块,能够独立运行以后才慢慢加入其他控制模块以及健壮性模块,所以按照这个顺序写还是没那么困难的,希望大家都能够学好JAVA WEB!

  • 相关阅读:
    时间线 | timeline | 简易GitHub部署
    名词解释 | Lead SNPs | credible SNPs | Polygenicity | Discoverability
    Phenome-wide association studies | PheWAS
    孟德尔随机化 | Mendelian randomization
    探索性因子分析法 | exploratory factor analysis | EFA | Genomic Structural Equation Modelling | SEM
    漫画 | 到底是什么让IT人如此苦逼???
    国产Java代码补全神器,aiXcoder 2.0实测
    Dubbo学习(一) Dubbo原理浅析【转】
    Dubbo架构与底层实现【转】
    HAproxy 默认短连接,特殊域名开启长连接的配置方法【转】
  • 原文地址:https://www.cnblogs.com/kingszelda/p/7142700.html
Copyright © 2011-2022 走看看