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>

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

 

posted @ 2015-03-26 20:34  zhhx  阅读(3436)  评论(0编辑  收藏  举报