java web利用mvc結構實現簡單聊天室功能


 簡單聊天室采用各種內部對象不適用數據庫實現。

一個聊天室要實現的基本功能是:

        1.用戶登錄進入聊天室,

   2.用戶發言

   3.用戶可以看見別人發言

 

剛才算是簡單的需求分析了,現在就應該是進行mvc結構的設計:

  1.視圖,有登陸頁面login.jsp,聊天頁面chat.jsp,其中chat.jsp利用框架實現,包括兩部分,用戶發言sendMessage.jsp和聊天信息的查看content.jsp;

  2.模型,包括聊天信息的顯示(類Message)和聊天信息的管理(類MessageService);

  3.控制器,登錄功能的控制器LoginServlet,添加消息的控制器AddMessageServlet。

 

  整個程序實現的大致流程是這樣的:每當一個用戶登錄聊天室,根據用戶的userid把用戶添加進application對象的ArrayList中,在application中保存的是當前所有在聊天的用戶;用戶登陸成功之后,通過控制器LoginServlet把application對象遍歷,輸出所有的消息,消息存儲在application(消息格式:用戶名+消息);用戶發言,通過控制器AddMessageServlet,先在session中取出用戶名,把當前消息放在application中,保存更新后的消息,跳轉到聊天頁面。

精簡源代碼:

1.登陸界面login.jsp

 1 <body>
 2       <h1>歡迎進入聊天室</h1>
 3       <form action="login">
 4           用戶名:<input type="text" name="userid"><br>
 5           
 6           <input type="submit" value="進入"> <input type="reset" value="重寫">
 7           
 8       </form>
 9   
10   </body>
View Code

2.聊天界面整體框架chat.jsp

<frameset rows="*,20%">
    <frame name="content" src="content.jsp">
    <frame name="sendMessage" target="content" src="sendMessage.jsp">
    <noframes>
        <body>
            <p>此網頁使用了框架,但你的瀏覽器不支持框架</p>
        </body>
    </noframes>
</frameset>
View Code

3.用戶發言sendMessage.jsp

1 <body>
2     <form action="addmessage" target="content">
3         發言:<input type="text" name="info"> <input type="submit"
4             value="確定">
5     </form>
6 </body>
View Code

4.顯示聊天信息

 1 <body>
 2 <%  
 3    //頁面每隔1秒自動刷新一遍      
 4   response.setHeader("refresh","1");  
 5 %>
 6 
 7     <c:forEach items="${allMessage}" var="message">
 8         ${message.userid }
 9         在${message.time }說:<font color="green">${message.info }</font>
10         <br>
11     </c:forEach>
12 </body>
View Code

5.登錄控制器LoginServlet

 1 public class LoginServlet extends HttpServlet {
 2 
 3     public void doGet(HttpServletRequest request, HttpServletResponse response)
 4             throws ServletException, IOException {
 5         // 獲取用戶輸入
 6         String userid = request.getParameter("userid");
 7         userid = new String(userid.getBytes("utf-8"));
 8 
 9         // 獲取application對象
10         ServletContext application = this.getServletContext();
11         // 獲取application對象中user
12         ArrayList<String> users = (ArrayList<String>) application
13                 .getAttribute("users");
14 
15         // 判斷用戶名是否存在
16         if (users != null && users.contains(userid)) {
17             request.setAttribute("errorinfo", "用戶" + userid + "已經存在");
18             RequestDispatcher rd;
19             rd = request.getRequestDispatcher("login.jsp");
20             rd.forward(request, response);
21         } else {
22             if (users == null)// 如果當前application中沒有user,初始化user對象
23             {
24                 users = new ArrayList<String>();
25             }
26             users.add(userid);
27             application.setAttribute("users", users);
28 
29             // 為每一個用戶設置一個session
30             HttpSession session = request.getSession(true);
31             session.setAttribute("userid", userid);
32 
33             response.sendRedirect("chat.jsp");
34 
35         }
36 
37     }
38 
39     public void doPost(HttpServletRequest request, HttpServletResponse response)
40             throws ServletException, IOException {
41         doGet(request, response);
42     }
43 
44 }
View Code

6.添加消息的控制器AddMessageServlet

 1 public class AddMessageServlet extends HttpServlet {
 2 
 3     public void doGet(HttpServletRequest request, HttpServletResponse response)
 4             throws ServletException, IOException {
 5 
 6         // 從request中取出用戶的個人信息
 7 
 8         HttpSession session = request.getSession(true);
 9         String userid = (String) session.getAttribute("userid");
10 
11         // 從request對象中取出用戶新增的聊天信息
12 
13         String info = request.getParameter("info");
14         info = new String(info.getBytes("utf-8"));
15 
16         // 取出所有的聊天信息
17         ServletContext application = this.getServletContext();
18         ArrayList<Message> allMessage = (ArrayList<Message>) application
19                 .getAttribute("allMessage");
20 
21         // 創建消息對象
22         Message message = new Message(userid, info);
23 
24         // 創建業務對象
25         MessageService service = new MessageService(allMessage);
26 
27         // 調用業務邏輯
28         service.addMessages(message);
29 
30         // 保存更新后的消息
31         application.setAttribute("allMessage", service.getAllMessages());
32 
33         // 轉向聊天頁面
34         response.sendRedirect("content.jsp");
35 
36     }
37 
38     public void doPost(HttpServletRequest request, HttpServletResponse response)
39             throws ServletException, IOException {
40         doGet(request, response);
41     }
42 
43 }
View Code

7.聊天信息Message.java

 1 //聊天信息的表示
 2 public class Message {
 3  private String userid;
 4  
 5  private String info;
 6  
 7  public Message(String userid,String info)
 8  {
 9         this.userid = userid;
10         //this.sex=sex;
11         this.info=info;
12         this.time=(new SimpleDateFormat("hh:mm:ss")).format(new Date());//將時間格式化
13      
14  }
15  public String getUserid() {
16     return userid;
17 }
18 public void setUserid(String userid) {
19     this.userid = userid;
20 }
21 
22 public String getInfo() {
23     return info;
24 }
25 public void setInfo(String info) {
26     this.info = info;
27 }
28 public String getTime() {
29     return time;
30 }
31 public void setTime(String time) {
32     this.time = time;
33 }
34 private String time;
35  
36 }
View Code

8.聊天信息管理MessageService.java

 1 public class MessageService {
 2     private ArrayList<Message> allMessages;
 3     public MessageService(ArrayList<Message> allMessages)
 4     {
 5         this.allMessages=allMessages;
 6     }
 7     public ArrayList<Message> getAllMessages()
 8     {
 9         return allMessages;
10     }
11     
12     public void addMessages(Message message)
13     {
14         //先判斷聊天信息列表是否為空,為空則新建聊天列表
15         if(allMessages==null)
16         {
17             allMessages=new ArrayList<Message>();
18         }
19         else
20         {
21             allMessages.add(0,message);//將指定的元素插入此列表中的指定位置。向右移動當前位於該位置的元素(如果有)以及所有后續元素(將其索引加 1)。 
22         }
23     }
24 
25 }
View Code

 

      收獲:通過這么一個小小的web程序,加深了對mvc模式的理解。

      mvc的傳值方式(個人理解):視圖層通過表單提交的方式把信息放在request對象中,在控制器中通過request對象獲取視圖層的數據,獲取的數據經過模型層的業務邏輯處理,把相應的結果放在response對象中傳回瀏覽器顯示在視圖中。

  小知識點:

    application對象只有一個,每一個用戶都有自己的session,每個用戶的每個請求都對應着一個新的request對象(request只能在一次請求時共享信息)。

    標准標簽庫的使用:循環輸出<c:forEach var="變量名" items="集合對象">循環體</c:forEach>

   最后,部署自己的應用到服務器下就可以使用了。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM