Javaweb實現簡易的留言板項目

首語

  • 歡迎大家來我的個人網站逛逛。有什麼建議可以留言!

網站地址:http://www.yanghujun.com

此項目使用Eclipse+mysql 5.0+Tomcat v7.0開發,實現的主要功能有增加留言,查詢留言。附加用戶的登錄和註冊。修改、刪除和回覆留言還未設計,望大家補充。
此留言板爲Javaweb基礎練習項目,供Javaweb入門者參考學習,共同進步。

GitHub下載地址:MessageBoard

一、JavaBean層的設計

數據表參數的獲取。

主要是生成數據表字段的get,set方法,對數據進行設置和獲取。

數據庫連接和操作

/**數據庫連接*/
public class DBConn {

 public static Connection conn;
  // Connection對象(鏈接)
  // 連接數據庫
  public static Connection getConn() {
     try {
       // 加載註冊SQLSever的JDBC驅動
       Class.forName("com.mysql.jdbc.Driver");
       // 編寫鏈接字符串,創建並且獲取鏈接
       conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/MessageBoard","root","root");
     } catch (Exception e) {
       e.printStackTrace();
     }
     return conn;
  }

  public static void CloseConn() {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
  }

  public static void main(String[] args) {
     Connection conn=DBConn.getConn();
     if(conn!=null) {
       System.out.println("數據庫連接正常");
     }else {
       System.out.println("數據庫連接失敗");
     }
  }
}



/**數據庫操作*/
public class LoginDao {

  Connection conn = DBConn.getConn();
  // 數據庫連接對象
  PreparedStatement pstmt;
  
  public Login checkLogin(String name, String password) {
     // 驗證用戶名密碼
     try {
       pstmt = conn.prepareStatement("select*from logins where name=?and password=?");
       pstmt.setString(1, name);
       // 設置SQL語句參數
       pstmt.setString(2, password);
       // 設置SQL語句參數
       ResultSet rs = pstmt.executeQuery();
       // 執行查詢,返回結果集
       if (rs.next()) {
         // 通過JavaBean保存值
         Login login = new Login();
         login.setId(rs.getInt(1));
         login.setName(rs.getString(2));
         login.setPassword(rs.getString(3));
         login.setRole(rs.getInt(4));
         return login;
         // 返回JavaBean對象
       }
       return null;
       // 驗證失敗返回null
     } catch (Exception e) {
       e.printStackTrace();
       return null;
     }
  }

  //留言查詢
  public ArrayList<MessBor> findMbInfo() {
     try {
       ArrayList<MessBor> al = new ArrayList<MessBor>();
       pstmt = conn.prepareStatement("select *from messages");
       ResultSet rs = pstmt.executeQuery();
       while (rs.next()) {
         MessBor mb = new MessBor();
         mb.setId(rs.getInt(1));
         mb.setName(rs.getString(2));
         mb.setTime(rs.getDate(3));
         mb.setTitle(rs.getString(4));
         mb.setMessage(rs.getString(5));
         al.add(mb);
       }
       return al;
     } catch (Exception e) {
       e.printStackTrace();
       return null;
     }
  }
  
  public String getName(int id) {
     String name = null;
     try {
       pstmt = conn.prepareStatement("select namefrom logins where id=?");
       pstmt.setInt(1, id);
       ResultSet rs = pstmt.executeQuery();
       while (rs.next()) {
         name = rs.getString(1);
       }
       return name;
     } catch (Exception e) {
       e.printStackTrace();
       return null;
     }
  }
 
 //添加留言
  public boolean addInfo(MessBor mb) {
     try {
       pstmt = conn.prepareStatement("insert intomessages values(?,?,?,?,?)");
       pstmt.setInt(1, mb.getId());
       pstmt.setString(2, mb.getName());
       pstmt.setDate(3, mb.getTime());
       pstmt.setString(4, mb.getTitle());
       pstmt.setString(5, mb.getMessage());
       pstmt.executeUpdate();
       return true;
     } catch (Exception e) {
       e.printStackTrace();
       return false;
     }
  }
  
  //用戶註冊
  public boolean insertUser(int id, String name, String password) {
     try {
       pstmt = conn.prepareStatement("insert into
logins(id,name,password,role) values(?,?,?,?)");
       pstmt.setInt(1, id);
       pstmt.setString(2, name);
       pstmt.setString(3, password);
       pstmt.setInt(4, 0);
       pstmt.executeUpdate();
       return true;
     } catch (Exception e) {
       e.printStackTrace();
       return false;
     }
  }
}


二、jsp頁面設計

jsp頁面主要包括登陸和註冊頁面,留言主頁面,留言界面。

<!-- 登陸界面 -->
<body>
  <div style="margin-left: 35%; margin-top: 100px; font-family: Microsoft YaHei">
     <h1>登錄界面</h1>
     <form action="LoginServlet" method="post">
       <table>
         <tr>
            <td>賬號:</td>
            <td><input name="name" type="text"></td>
         </tr>
         <tr>
            <td>密碼:</td>
            <td ><input name="password" type="password"></td>
         </tr>
       </table>
       <input type="submit"  value="登錄" style="font-size: 16px"> 
       &nbsp;&nbsp;<a href="register.jsp">註冊</a>
     </form>
  </div>
</body>




<!-- 註冊界面 -->
<body>
  <div>
     <h1>註冊界面</h1>
     <form action="RegisterServlet" method="post">
       <table>
         <tr>
            <td>ID:</td>
            <td><input name="id" type="text" size="20"></td>
         </tr>
         <tr>
            <td>登錄名:</td>
            <td><input name="name"type="text" size="20"></td>
         </tr>
         <tr>
            <td>密碼:</td>
            <td><input name="password"type="password" size="21"></td>
         </tr>
       </table>
       <input type="submit"value="註冊">
       <input type="reset" value="重置">
     </form>
     <br> <a href="login.jsp">登錄</a>
  </div>
</body>



<!-- 留言主界面 -->
<body>
  <div
     style="margin-left: 35%; margin-top: 100px; font-family: Microsoft YaHei">
     <h1 style="margin-left: 5%">這裏是留言板主界面</h1>
     <form action="leavemessage.jsp" method="post">
       <table border="1">
         <caption>所有留言信息</caption>
         <tr>
            <th>留言人姓名</th>
            <th>留言時間</th>
            <th>留言標題</th>
            <th>留言內容</th>
         </tr>
         <%
            ArrayList<MessBor> al = new ArrayList<MessBor>();
            al = (ArrayList) session.getAttribute("al");
            if (al != null) {
              Iterator iter = al.iterator();
              while (iter.hasNext()) {
                MessBor mb = (MessBor) iter.next();
         %>
         <tr>
            <td><%=new LoginDao().getName(mb.getId())%></td>
            <td><%=mb.getTime().toString()%></td>
            <td><%=mb.getTitle()%></td>
            <td><%=mb.getMessage()%></td>
         </tr>
         <%
             }
          }
         %>
       </table>
     </form>
     <a style="margin-left: 22%" href="leavemessage.jsp">留言</a>
  </div>
</body>



<!-- 留言界面 -->
<body>
  <div style="text-align: center; margin-top: 140px">
     <h1>請留言</h1>
     <form action="LeaveMessage" method="post">
       <table style="margin-left: 37%" border="1">
         <caption>填寫留言信息</caption>
         <tr>
            <td>留言標題</td>
            <td><input type="text"name="title" /></td>
         </tr>
         <tr>
            <td>留言內容</td>
            <td><textarea name="message" rows="5" cols="35"></textarea></td>
         </tr>
       </table>
       <input type="submit"value="提交" />
       <input type="reset"value="重置" />
     </form>
     <a href="main.jsp">返回留言板界面</a>
  </div>
</body>


三、servlet設計

servlet主要實現登錄,註冊,留言等功能。


/**登錄操作*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public LoginServlet() {
     super();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
     // 設置請求編碼
     request.setCharacterEncoding("utf-8");
     // 設置響應編碼
     response.setContentType("utf-8");
     LoginDao loginDao = new LoginDao();
     HttpSession session = request.getSession();
     // 先獲得user對象,如果是第一次訪問該Servlet,用戶對象肯定爲空,
     //但如果是第二次甚至是第三次,就不應該再判斷該用戶的信息
     Login l = (Login) session.getAttribute("login");
     if (l == null)
       l = loginDao.checkLogin(request.getParameter("name"), request.getParameter("password"));
     if (l != null) {
       // 如果登陸成功
       session.setAttribute("login", l);
       // 將獲取的對象保存在session中
       ArrayList al = loginDao.findMbInfo();
       // 獲取留言板的內容,返回一個數組
       session.setAttribute("al", al);
       // 把數組保存起來
       response.sendRedirect("main.jsp");
       // 驗證成功跳轉到 main.jsp
     } else {
       // 驗證失敗跳轉到 error.jsp
       response.sendRedirect("error.jsp");
     }
     if(session!=null) {
       response.sendRedirect("login.jsp");
     }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}
 


/**註冊操作*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public RegisterServlet() {
     super();
      }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
       //設置請求編碼
     request.setCharacterEncoding("utf-8");
     //獲取字段
     int id = Integer.valueOf(request.getParameter("id"));
     String name = request.getParameter("name");
     String password = request.getParameter("password");
     if (new LoginDao().insertUser(id, name, password)) {
       //註冊成功,跳轉到登錄界面
       response.sendRedirect("login.jsp");
     }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
     doGet(request, response);
  }
}



/**留言操作*/
@WebServlet("/LeaveMessage")
public class LeaveMessage extends HttpServlet {
  private static final long serialVersionUID = 1L;
  public LeaveMessage() {
     super();
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
     // 設置請求編碼        
     request.setCharacterEncoding("utf-8");         
     // 設置響應編碼        
     response.setContentType("utf-8");         
     // 獲取title內容         
     String title=request.getParameter("title");        
     // 獲取message內容         
     String message=request.getParameter("message");         
     // 從session中取出當前用戶對象         
     Login leaveMessageBoard=(Login) request.getSession().getAttribute("login");        
     // 建立留言表對應JavaBean對象,把數據封裝進去        
     MessBor mb=new MessBor();        
     mb.setId(leaveMessageBoard.getId());        
     // 參數爲獲取的當前時間         
     mb.setName(leaveMessageBoard.getName());         
     mb.setTime(new Date(System.currentTimeMillis()));          
     mb.setTitle(title);         
     mb.setMessage(message);       
     // 調DB類中的方法判斷是否插入成功         
     if(new LoginDao().addInfo(mb)){           
       response.sendRedirect("success.jsp") ;         
       }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
     doGet(request, response);
  }
}



四、數據庫設計

/*註冊表和留言表*/

CREATE TABLE `logins` (
  `id` int(11) NOT NULL,
  `name` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `role` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-------------------------------------------------------------------
CREATE TABLE `messages` (
  `id` int(11) NOT NULL,
  `name` varchar(20) NOT NULL,
  `time` varchar(20) NOT NULL,
  `title` varchar(20) NOT NULL,
  `message` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

小結:

本項目採用MVC設計模式(所謂MVC:模型(model)-視圖(view)-控制器(controller),它是用一種業務邏輯、數據與界面顯示分離的方法來組織代碼,將衆多的業務邏輯聚集到一個部件裏面,在需要改進和個性化定製界面及用戶交互的同時,不需要重新編寫業務邏輯,達到減少編碼的時間。是一種軟件設計典範。),主要學習數據庫與jsp和servlet的綜合使用,也是本項目的難點。本項目已上傳到GitHub,供大家下載使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章