码迷,mamicode.com
首页 > 其他好文 > 详细

用Servlet实现聊天室设计

时间:2015-10-12 20:59:30      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

实验一   Servlet编程

.实验目的1.熟悉Java EE编程环境JDKNetBeans的安装,配置和使用;2.掌握Servlet的编写及部署;3.掌握Servlet的工作原理和编程接口;4.掌握Servlet中客户端输入数据处理技术;5.掌握Servlet中的会话跟踪技术;

6.掌握Servlet中的请求指派技术;

7.掌握Servlet上下文属性的使用方法;

8.掌握ServletFilter基本编程技术;

9.掌握ServletListener基本编程技术;

 二.实验内容利用JavaEE相关技术实现一个简单的Web聊天室系统,具体要求如下。

1编写一个登录页面,登录信息中有用户名和密码,分别用两个按钮来提交和重置登录信息。

2编写一个Servlet程序Main.java通过请求指派来处理用户提交的登录信息,如果用户名为本小组成员的名字且密码为对应的学号时,跳转到LoginSuccess显示聊天界面(类似于QQ群聊天界面,可使用HTML中的frameset标签生成两个窗口,一个用来实现用户信息输入,另一个显示所有用户聊天记录的);否则跳转到LoginFail页面,提示用户重新登录(注:此页面要包含前面的登录界面)

3编写两个Servlet程序,分别用来显示“信息输入”窗口和“聊天记录显示”窗口的内容;用户在“信息输入”窗口中键入聊天内容,点击“发送”按钮后,在“聊天记录显示”窗口中显示发送消息的用户名称和聊天内容。提示:利用HTML中的textarea标签来实现。

4在登录界面上实现记住用户名和密码的功能,使得当用户选择了此功能并成功登录后,在其下次登录时可以不用再输入用户名和密码即可登录。提示:此功能可通过两个Cookie来实现。

以下功能选做:

5编写一个Listener程序来监听会话的创建和销毁事件,以此统计当前在线(登录)人数,并将其显示在聊天界面上。

6添加一个Filter对本系统所有的Servlet程序进行过滤,该Filter实现对请求和响应对象的编码格式的设置(实现此功能后,Servlet可以直接从请求对象中获取参数信息而无需实现对请求进行格式的编码)。在【GlassFish Server】视图中输出程序在Filter和其它资源之间的执行顺序。

 

本次例子重在思路,页面未做任何美化。关于包文件的引用一定要注意,Servlet需要引入相应的包文件才能运行,一般IDE都会自动创建引入,这里不做解释

1.首先,需要一个登陆页面。LoginServlet

 1 package com.jun.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.Cookie;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 /**
14  * Servlet implementation class LoginServlet
15  */
16 @WebServlet("/LoginServlet")
17 public class LoginServlet extends HttpServlet {
18     private static final long serialVersionUID = 1L;
19        
20     /**
21      * @see HttpServlet#HttpServlet()
22      */
23     public LoginServlet() {
24         super();
25         // TODO Auto-generated constructor stub
26     }
27 
28     /**
29      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
30      */
31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
32         Cookie[] cookies = request.getCookies();//获取cookie对象
33         String uname = "";
34         String upwd = "";
35         if (cookies != null) {
36             for (int i = 0; i < cookies.length; i++) {
37                 Cookie cookie = cookies[i];
38                 if (cookie.getName().equals("remname")) {
39                     uname = cookie.getValue();
40                 } else if (cookie.getName().equals("rempwd")) {
41                     upwd = cookie.getValue();
42                 }
43             }
44         }
45         //上面代码用来判断用户是否曾保存过登陆信息
46         
47         
48         response.setContentType("text/html;charset=utf-8");
49         request.setCharacterEncoding("utf-8");    
50         PrintWriter out = response.getWriter();
51         out.println("<html><head><title>登陆界面</title>");
52         out.println("<body>");
53         out.println("<div>");
54         out.println("<form action=‘Main‘ method=‘post‘");
55         out.println("<p>用户名:<input type=‘text‘ name=‘username‘ value=" +uname+ "></p>");
56         out.println("<p>密  码:<input type=‘password‘ name=‘password‘ value=" +upwd+ "></p>");
57         out.println("<p>记住密码:<input type=‘checkbox‘ name=‘remember‘ value=‘ture‘>");
58         out.println("<input type=‘submit‘ name=‘submit‘ value=‘登陆‘>");
59         out.println("<input type=‘reset‘ name=‘reset‘ value=‘重置‘></p>");
60         out.println("</div>");
61         out.println("</body></html>");
62     }
63 
64     /**
65      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
66      */
67     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
68         // TODO Auto-generated method stub
69     }
70 
71 }

2.新建一个用来处理登录信息的Servlet: Main.java 所有的处理都在DoPost()完成

 1 package com.jun.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.Cookie;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 
14 /**
15  * Servlet implementation class Main
16  */
17 @WebServlet(name = "Main", urlPatterns = { "/Main" })
18 public class Main extends HttpServlet {
19     private static final long serialVersionUID = 1L;
20 
21     /**
22      * @see HttpServlet#HttpServlet()
23      */
24     public Main() {
25         super();
26         // TODO Auto-generated constructor stub
27     }
28 
29     /**
30      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
31      *      response)
32      */
33     protected void doGet(HttpServletRequest request,
34             HttpServletResponse response) throws ServletException, IOException {
35     }
36 
37     /**
38      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
39      *      response)
40      */
41     protected void doPost(HttpServletRequest request,
42             HttpServletResponse response) throws ServletException, IOException {
43         response.setContentType("text/html;charset=utf-8");
44         String username, password, remember;
45         HttpSession session = request.getSession(true);//开启会话
46         
47         username = (String) request.getParameter("username");
48         password = (String) request.getParameter("password");
49         remember = (String) request.getParameter("remember");
50         //在控制台中输出,方便审查
51         System.out.println("remember:" + remember);
52         System.out.println(username);
53         System.out.println(password);
54         
55         if (username != null && username.equals("201321091103") && password.equals("123456")) {
56             if (remember != null && remember.equals("true")) {
57                 Cookie cookie1 = new Cookie("remname", username);
58                 Cookie cookie2 = new Cookie("rempwd", password);
59                 cookie1.setMaxAge(60 * 60 * 24 * 7);
60                 cookie2.setMaxAge(60 * 60 * 24 * 7);
61                 
62                 
63                 response.addCookie(cookie1);
64                 response.addCookie(cookie2);
65             }
66             session.setAttribute("UserName", username);
67             session.setAttribute("IsLogin", "true");
68             response.sendRedirect("LoginSuccessServlet");//用sendRedirect实现页面完全跳转
69         } else if (username != null && username.equals("201321091104") && password.equals("654321")) {
70             if (remember != null && remember.equals("true")) {//当用户勾选记住密码功能时,将密码返回给客户端保存,下次访问的时候先从客户端获取密码,这样就实现了记住密码功能
71                 Cookie cookie1 = new Cookie("remname", username);
72                 Cookie cookie2 = new Cookie("rempwd", password);
73                 cookie1.setMaxAge(60 * 60 * 24 * 7);
74                 cookie2.setMaxAge(60 * 60 * 24 * 7);
75                 response.addCookie(cookie1);
76                 response.addCookie(cookie2);
77             }
78             session.setAttribute("UserName", username);
79             session.setAttribute("IsLogin", "true");
80             response.sendRedirect("LoginSuccessServlet");
81         } else {
82             session.setAttribute("IsLogin", "false");
83             response.sendRedirect("LoginFail.html");//页面完全跳转,不会出现乱码
84         }
85     }
86
87 }

3.登陆成功,就实现页面跳转 LoginSuccessServlet

 1 package com.jun.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 //import javax.servlet.http.HttpSession;
12 import javax.servlet.http.HttpSession;
13 
14 /**
15  * Servlet implementation class LoginSuccessServlet
16  */
17 @WebServlet("/LoginSuccessServlet")
18 public class LoginSuccessServlet extends HttpServlet {
19     private static final long serialVersionUID = 1L;
20 
21     /**
22      * @see HttpServlet#HttpServlet()
23      */
24     public LoginSuccessServlet() {
25         super();
26         // TODO Auto-generated constructor stub
27     }
28 
29     /**
30      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
31      *      response)
32      */
33     protected void doGet(HttpServletRequest request,
34             HttpServletResponse response) throws ServletException, IOException {
35         response.setContentType("text/html;charset=utf-8");
36         request.setCharacterEncoding("utf-8");
37         HttpSession session = request.getSession();
38         String username = "";
39         if (session.getAttribute("UserName") != null) {
40             username = session.getAttribute("UserName").toString();
41         }
42         if (username != null && !username.equals("")) {
43             if (!session.getAttribute("IsLogin").equals("true")) {
44                 System.out.println(session.getAttribute("IsLogin").toString());
45                 response.sendRedirect("LoginServlet");
46             }
47         } else {
48             response.sendRedirect("LoginServlet");
49         }
50 
51         PrintWriter out = response.getWriter();
52         out.println("<html><head><title>聊天室</title>");
53         out.println("<style type=‘text/css‘>#iframe1{width:600px;height:200px;}iframe{width:600px;height:200px;margin-bottom:20px;}</style>");
54         out.println("</head>");
55         out.println("<center><h2><b>欢迎使用聊天系统</b></h2>");
56         out.println("<lable>当前用户:" + username
57                 + "</lable><a href=\"LoginOut\"> 退出登录</a><br>");
58         out.println("<iframe src=‘Messagebox‘ id=‘iframe1‘></iframe>");
59         out.println("<br>");
60         out.println("<iframe src=‘Talk‘></iframe><br>");
61         /*out.println("<frameset rows=\"50%,25%\">");
62         out.println("<frame name=\"message\" src=\"Messagebox\" />");
63         out.println("<frame name=\"uinput\" src=\"Talk\"/>");
64         out.println("</frameset>");
65         */
66         out.println("</body></html>");
67         
68     }
69 
70     /**
71      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
72      *      response)
73      */
74     protected void doPost(HttpServletRequest request,
75             HttpServletResponse response) throws ServletException, IOException {
76         // TODO Auto-generated method stub
77 
78     }
79 
80 }

4.登录失败,跳转到失败页面 

LoginFail.html
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6   <meta http-equiv="refresh" content ="3;url=LoginServlet">
 7 </head>
 8 <body>
 9 <b>呦呦呦,登陆失败了哟,3秒后跳转到登录页重新登陆哟! <a href="LoginServlet">点击此处直接跳转</a></b>
10 </body>
11 </html>

 5.登录成功的页面中用frame嵌入了两个页面,分别显示用户的信息输入(Talk)和显示(Messagebox)。

下面为Talk的页面

  1 package com.jun.servlet;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.text.SimpleDateFormat;
  6 import java.util.Date;
  7 
  8 import javax.servlet.ServletContext;
  9 import javax.servlet.ServletException;
 10 import javax.servlet.annotation.WebServlet;
 11 import javax.servlet.http.HttpServlet;
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 import javax.servlet.http.HttpSession;
 15 
 16 /**
 17  * Servlet implementation class Talk
 18  */
 19 @WebServlet("/Talk")
 20 public class Talk extends HttpServlet {
 21     private static final long serialVersionUID = 1L;
 22 
 23     /**
 24      * @see HttpServlet#HttpServlet()
 25      */
 26     public Talk() {
 27         super();
 28         // TODO Auto-generated constructor stub
 29     }
 30 
 31     /**
 32      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 33      *      response)
 34      */
 35     protected void doGet(HttpServletRequest request,
 36             HttpServletResponse response) throws ServletException, IOException {
 37         response.setContentType("text/html;charset=utf-8");
 38         request.setCharacterEncoding("utf-8");
 39         PrintWriter out = response.getWriter();
 40         HttpSession session = request.getSession();
 41         String username = (String) session.getAttribute("UserName");// 将获取的对象强制类型转换为字符串
 42 
 43         out.println("<html><body>");
 44         out.println("<lable>当前用户:" + username + "</lable><br>");
 45         out.println("<form action=\"Talk\" method=\"post\">");
 46         out.println("<div><textarea name=\"userMessages\" cols=\"50\" style=\"height:100px;\"></textarea></div>");
 47         out.println("<div><input type=\"submit\" id=\"submit\" value=\"发送\"/>");
 48         out.println("<input type=\"reset\" id=\"reset\" value=\"清空输入\"/></div>");
 49         out.println("</form>");
 50         out.println("</body></html>");
 51     }
 52 
 53     /**
 54      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 55      *      response)
 56      */
 57     protected void doPost(HttpServletRequest request,
 58             HttpServletResponse response) throws ServletException, IOException {
 59         response.setContentType("text/html;charset=utf-8");
 60         request.setCharacterEncoding("utf-8");
 61         HttpSession session = request.getSession();
 62         ServletContext application = this.getServletContext();// 获取上下文信息
 63 
 64         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日期格式
 65         Date currentTime = new Date();// 得到当前的系统时间
 66         String str_date1 = formatter.format(currentTime);// 将日期时间格式化 str_date1
 67         String username = (String) session.getAttribute("UserName");// 将获取的对象强制类型转换为字符串
 68 
 69         PrintWriter out = response.getWriter();
 70 
 71         String mywords = request.getParameter("userMessages");// 获取提交信息的内容
 72                                                                 // mywords
 73         application.log(mywords);// 在控制台中将提交的内容显示出来
 74         if (mywords == null) {
 75             mywords = "系统提示:可以聊天";
 76             application.setAttribute("words", mywords + "\n");
 77         } else if (mywords != null) {
 78             // int len_mywords = mywords.length();
 79             // application.log("字节长度:"+len_mywords);
 80             mywords = username + ":" + mywords + ":" + str_date1;// 给内容添上其他信息。
 81             application.log(mywords);//在控制台信息中查看内容
 82             Object obj = application.getAttribute("words");// 上下文获取 的都是一个对象
 83             if (obj == null) {
 84                 application.setAttribute("words", mywords + "\n");// 设置成全局变量
 85             } else {
 86                 application.setAttribute("words", obj.toString() + mywords
 87                         + "\n");// 当获取的上下文对象不为空时,需要将前面的信息也显示出来
 88             }
 89         }
 90 
 91         out.println("<html><body>");
 92         out.println("<lable>当前用户:" + username + "</lable><br>");
 93         out.println("<form action=\"Talk\" method=\"post\">");
 94         out.println("<div><textarea name=\"userMessages\" cols=\"50\" style=\"height:100px;\"></textarea></div>");
 95         out.println("<div><input type=\"submit\" id=\"submit\" value=\"发送\"/>");
 96         out.println("<input type=\"reset\" id=\"reset\" value=\"清空输入\"/></div>");
 97         out.println("</form>");
 98         out.println("</body></html>");
 99 
100     }
101 
102 }

6.Messagebox的页面

 1 package com.jun.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletContext;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 
14 /**
15  * Servlet implementation class Messagebox
16  */
17 @WebServlet("/Messagebox")
18 public class Messagebox extends HttpServlet {
19     private static final long serialVersionUID = 1L;
20 
21     protected void processRequest(HttpServletRequest request,
22             HttpServletResponse response) throws ServletException, IOException {
23         response.setContentType("text/html;charset=UTF-8");
24         request.setCharacterEncoding("UTF-8");
25         PrintWriter out = response.getWriter();
26         try {
27     
28             String temp = (String) getServletConfig().getServletContext()
29                     .getAttribute("online");
30             if (temp == null)
31                 temp = "0";
32             ServletContext application = this.getServletContext();// 获取上下文信息
33             String words = (String) application.getAttribute("words");
34             
35             out.println("<html>");
36             out.println("<head>");
37             out.println("<title>Servlet messagebox</title>");
38             out.println("<meta http-equiv=\"refresh\" content =\"2;url=Messagebox\">");
39             out.println("</head>");
40             out.println("<body>");
41             out.println("<p>当前在线:");
42             out.println(temp);
43             out.println("人</p>");
44             out.println("<textarea name=\"messagebox\" cols=\"100\" words=\"400\" style=\"height:400px;\">");
45             out.println(words);
46             out.println("</textarea>");
47             out.println("</body>");
48             out.println("</html>");
49         } finally {
50             out.close();
51         }
52     }
53 
54     @Override
55     protected void doGet(HttpServletRequest request,
56             HttpServletResponse response) throws ServletException, IOException {
57         processRequest(request, response);
58     }
59 
60     
61     @Override
62     protected void doPost(HttpServletRequest request,
63             HttpServletResponse response) throws ServletException, IOException {
64         processRequest(request, response);
65     }
66 
67 
68     @Override
69     public String getServletInfo() {
70         return "Short description";
71     }// </editor-fold>
72 
73 }

 

用Servlet实现聊天室设计

标签:

原文地址:http://www.cnblogs.com/xs-yqz/p/4872713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!