首頁 > php教程 > PHP开发 > 使用Servlet和JSP實作一個簡單的Web聊天室系統

使用Servlet和JSP實作一個簡單的Web聊天室系統

高洛峰
發布: 2016-11-18 10:47:07
原創
3060 人瀏覽過

1 問題描述

利用Java EE相關技術實作一個簡單的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和其它資源之間的執行順序。

 

2 解決方案

 

2.1 預期效果

使用Servlet和JSP實作一個簡單的Web聊天室系統

圖一:網路聊天系統示意圖

圖二:系統結構示意圖

welcome. jsp具體頁:

使用Servlet和JSP實作一個簡單的Web聊天室系統

圖三:welcome.jsp實際運行圖

 

2.3 具體編碼

使用Servlet和JSP實作一個簡單的Web聊天室系統(1)Main.java(Servlet類)透過請求分配來處理用戶提交的登錄頁面.資訊(並使用Cookie實現記住使用者登入使用者名稱和密碼功能),成功則跳到welcome.jsp,失敗則跳到login.jsp。具體實作如下:

網路聊天系統登陸首頁login.jsp頁面代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

String username = "";

String password = "";

//String[] checkBox = request.getParameterValues("save_password");

//获取当前站点的所有Cookie

 Cookie[] cookies = request.getCookies();

 

 for (int i = 0; i < cookies.length; i++) {

          //对cookies中的数据进行遍历,找到用户名、密码的数据

         if ("username".equals(cookies[i].getName())) {

          //读取时URLDecoder.decode进行解码(PS:Cookie存取时用URLEncoder.encode进行编码)

             username = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");

         } else if ("password".equals(cookies[i].getName())) {

             password =  java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");

         }

  }

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    <title>网上聊天室登陆页面</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

    <style type="text/css">

        *

        {

            margin: 0;

            padding: 0;

        }

        body

        {

             

            font-size: 0px;

            padding: 200px;

            

             

        }

         

    </style>

  </head>

 <body>

 <form action="Main" method="post">

 <div style="background:#49AFFF;font-size: 80px;text-align:center;">网上聊天室</div>

<div style="background:#75FFE7;font-size: 35px;text-align:center;">

<span>用户名:</span><input type="text" name="username" value="<%=username%>" style="border:1px solid #ccc; width:400px; height:40px;" ></div>

<div style="background:#75FFE7;font-size: 35px;text-align:center;">

<span>密    码 :</span><input type="password" name="password" value="<%=password%>" style="border:1px solid #ccc; width:400px; height:40px;" ></div>

<div style="background:#75FFE7;font-size: 25px;text-align:center;">

<input type="checkbox" value="save" name="save_password">记住密码

<input type="submit" value="登陆" name="login" style="width: 100px; height: 40px;font-size: 30px;">

<input type="reset" value="重置" name="reset" style="width: 100px; height: 40px;font-size: 30px;"></div>

</form>

</body>

</html>

登入後複製

Main.java類別程式碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

package com.liuzhen.chart;

 

import java.io.IOException;

import java.net.URLEncoder;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

 

@SuppressWarnings("serial")

public class Main extends HttpServlet {

 

    /**

     * Constructor of the object.

     */

    public Main() {

        super();

    }

 

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

 

   

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

         doPost(request,response);

    }

 

    

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

         

        //response.setContentType("text/html;charset=utf-8");

        //此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码

        //request.setCharacterEncoding("utf-8");

        String userName = request.getParameter("username");

        String passWord = request.getParameter("password");

        String checkBox = request.getParameter("save_password");

 

        System.out.println("userName:"+userName+"\n"+"passWord:"+passWord);

        request.getSession().setAttribute("nameSession", userName);   //将用户名存入session中

        String[] name_one = {"柳真","刘仁杰","吴超","张浩东","陈初相"};

        String[] pwd_one = {"201421092073","201421092068","201421092077","201421092082","201421092119"};

        String name_two = "";

        String pwd_two = "";

        boolean login_test = false;

        for(int i=0;i<5;i++){

            name_two = name_one[i];

            pwd_two = pwd_one[i];

            if(userName.equals(name_two) && passWord.equals(pwd_two))

                login_test = true;                          

        }

         

        if(login_test) {

            if ("save".equals(checkBox)) {

                //Cookie存取时用URLEncoder.encode进行编码(PS:读取时URLDecoder.decode进行解码)

                String name = URLEncoder.encode(userName,"UTF-8");

                //创建两个Cookie对象

                Cookie nameCookie = new Cookie("username", name);

                //设置Cookie的有效期为3天

                nameCookie.setMaxAge(60 * 60 * 24 * 3);

                String pwd = URLEncoder.encode(passWord,"UTF-8");

                Cookie pwdCookie = new Cookie("password", pwd);

                pwdCookie.setMaxAge(60 * 60 * 24 * 3);

                response.addCookie(nameCookie);

                response.addCookie(pwdCookie);

             }

             request.getRequestDispatcher("welcome.jsp").forward(request, response);          

        }  

        else{

             response.sendRedirect("loginFail.jsp");     

              // request.getRequestDispatcher("loginFail.jsp").forward(request, response);            

        }

             

        

    }

 

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init() throws ServletException {

        // Put your code here

    }

 

}

登入後複製

登陸失敗頁loginFail.jspomej

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

     

    <title>My JSP &#39;loginFail.jsp&#39; starting page</title>

     

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="content-type" content="text/html; charset=gb2312">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

  </head>

   

  <body>

    <br>

      <br>

           <h1>用户名和密码不匹配,请重新登陆!</h1>

           <a href="login.jsp">重新登陆</a>

  </body>

</html>

登入後複製

登陸頁碼這裡使用frameset標籤,分為頭部、左部和中間主頁三部分,分別物件header.jsp、left.jsp和main.jsp頁面):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

     

    <title>网上聊天室</title>

     

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="content-type" content="text/html; charset=gb2312">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

  </head>

   <frameset rows="100,*" cols="*" frameborder="no" border="0" framespacing="0">

         <frame src="header.jsp" name="topFrame" scrolling="auto" noresize="noresize" id="topFrame"/>

      <frameset cols="213,*" frameborder="no" border="0" framespacing="0">

        <frame src="left.jsp" name="leftFrame" scrolling="No" noresize="noresize" id="leftFrame"/>

        <frame src="main.jsp" name="mainFrame" scrolling="auto" id="mainFrame"/>

      </frameset>

   </frameset>

  <body>

     

  </body>

</html>

登入後複製

聊天頭部header.jsp頁面代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312" pageEncoding="gb2312"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

     

    <title></title>

     

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

  </head>

   

  <body topmargin="0" leftmargin="0" rightmargin="0">

     <form action="">

             <table  width="100%" height="79" border="0" cellpadding="0"

                     cellspacing="0" align=center>

             <tr>

                <td bgcolor="F9A859" valign="top">

                <table width="100%" height="50" border="0" align="center"

                       cellpadding="0" cellspacing="0" bgcolor="FBEAD0">

                 <tr>

                   <td align="center" style="font-size:40px;">

                     网上聊天室

                   </td>

                 </tr>

                 

                </table>

                 

                </td>

             </tr>

               <tr>

                 <td bgcolor="F9A859" valign="top">

                 <table width="100%" border="0" align="center" cellpadding="0"

                         cellspacing="0">

                  <tr>

                     <td align="center" style="font-size:20px" valign="middle">

                     欢迎<%=(String)request.getSession().getAttribute("nameSession") %>访问!

                     当前在线人数为<%=application.getAttribute("peopleOnline")%>人

                     </td>

                  </tr>      

                  

                 </table>

                  

                 </td>

              </tr>             

              

             </table>

           </form>

  </body>

</html>

登入後複製

聊天左部left.jsp頁面程式碼(這裡為了顯示美觀,使用了jquery-1.4.2套件):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

     

    <title>My JSP &#39;test.jsp&#39; starting page</title>

     

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="content-type" content="text/html; charset=gb2312">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 <style type="text/css">

        *

        {

            margin: 0;

            padding: 0;

        }

        body

        {

            font-size: 15px;

            padding: 00px;

        }

        .menu

        {

            width: 500px;

            border-bottom: solid 1px gray;

        }

        .menu h3

        {

            border: solid 1px gray;

            height: 30px;

            line-height: 30px;

            padding-left: 10px;

            padding:0 5px;

            border-bottom: none;

            cursor: pointer;

            

        }

        .menu p

        {

            border-left: solid 1px gray;

            border-right: solid 1px gray;

            padding: 20px 0;

            padding-left: 5px;

        }

        .changecolor{background-color:red;}

    </style>

    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">

          $(function () {

            $(".menu p:not(:first)").hide();

            $(".menu h3").css("background", "#ccc");      

            $(".menu h3").hover(function () { $(this).css("background-color", "gray").siblings("h3").css

("background-color", "#ccc");});

            $(".menu h3").mouseleave(function () {

               $(".menu h3").css("background", "#ccc");}); //离开时将其变为原来颜色

            var index = $(".menu h3").index(this);

            $(".menu h3").click(function () { $(this).next("p").slideToggle().siblings("p").slideUp(); });

        });

    </script>

  </head>

   

  <body>

    <div class="menu">

        <h3>

            我的好友</h3>

        <p>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/><br/>

   <a href="index.jsp">周杰伦</a><br/>

            </p>

        <h3>

            我的朋友</h3>

        <p>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/><br/>

   <a href="index.jsp">李连杰</a><br/>

         </p>

        <h3>

            陌生人</h3>

        <p>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/><br/>

   <a href="index.jsp">比尔盖茨</a><br/>

          </p>

    </div>

  </body>

</html>

登入後複製

聊天主頁main.jsp頁面程式碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

     

    <title>My JSP &#39;main.jsp&#39; starting page</title>

     

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

  </head>

   

  <body>

  <form action="InputInformation" method=post>

  <textarea  cols="105" rows="25" name="show_textarea"><%=request.getAttribute("input_textarea")%></textarea>

  <br>

  <textarea  cols="105" rows="5"  name="input_textarea"></textarea><br>

  <input type="submit" value="发送" name="button_one"

   style="width: 100px; height: 40px;font-size: 25px;"><br>

  </form>

  </body>

</html>

登入後複製

(2)InputInformation.java(Servlet類別)透過請求指派取得main.jsp聊天輸入框中輸入訊息,跳到main.jsp頁面,並在聊天記錄顯示框中顯示聊天訊息。具體實作如下:

 InputInformation.java類別程式碼如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

package com.liuzhen.chart;

 

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

@SuppressWarnings("serial")

public class InputInformation extends HttpServlet {

    public String chat_record = ""//定义聊天记录变量,此处为全局变量

 

    /**

     * Constructor of the object.

     */

    public InputInformation() {

        super();

    }

 

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

 

   

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        doPost(request,response);

    }

 

    

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        //response.setContentType("text/html;charset=utf-8");

        //此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码

        //request.setCharacterEncoding("utf-8");

        String input_textarea = request.getParameter("input_textarea");

        Date now = new Date();    //创建日期对象,及系统当前时间

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        String time = dateFormat.format( now ); //按照给定的日期格式获取系统当前时间

        String t = (String)request.getSession().getAttribute("nameSession");  //获取登陆页面用户名

        chat_record += t+"  "+input_textarea+"  "+time+"\n";   //聊天记录存储

        request.setAttribute("input_textarea",chat_record); //将当前聊天输入内容存储

        request.getRequestDispatcher("main.jsp").forward(request,response);  //跳转到当前聊天输入界面,即界面布局不变

    }

 

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init() throws ServletException {

        // Put your code here

    }

 

}

登入後複製

(3)CodeFilter.java(过滤器类)截取系统所有Servlet类,实现对请求和响应对象的编码格式的设置,均设置为UTF-8。具体实现如下:

CodeFilter.java类代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

package com.liuzhen.chart;

 

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

//采用注解方式配置URL,此处就不必再在web.xml文件中配置。如果两者均配置的话,系统将以web.xml文件中配置信息为准

@WebFilter(filterName="CodeFilter",urlPatterns={"/*"})     

 

public class CodeFilter implements Filter{

         

     

         @Override

         public void destroy() {

             System.out.println("destroy---CodeFilter");                         

         }

      

         @Override

         public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)

                 throws IOException, ServletException {

             System.out.println("start----doFilter--CodeFilter");

      

             HttpServletRequest request =(HttpServletRequest) arg0;

             HttpServletResponse response =(HttpServletResponse) arg1;

             //以上是强制内型转换,使用request对象和response对象

              

             request.setCharacterEncoding("utf-8");          //设置过滤页面提取数据的编码

             response.setContentType("text/html;charset=utf-8");  //设置过滤页面显示数据的编码

              

             arg2.doFilter(arg0, arg1);//在页面跳转之前执行此语句前面的代码,执行完页面的代码之后,在执行后面的语句

             System.out.println("第一个字符过滤器");

             System.out.println("end------doFilter--CodeFilter");   

             }

      

         @Override

         public void init(FilterConfig filterConfig) throws ServletException {

             System.out.println("init----CodeFilter");

         }

 

}

登入後複製

(4)OnlineListener.java(监听器类)主动监听系统Web容器,返回当前聊天系统在线人数,具体实现如下:

OnlineListener.java类代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

package com.liuzhen.chart;

 

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

 

public class OnlineListener implements HttpSessionListener{

     

    public void sessionCreated(HttpSessionEvent arg0) {

           ServletContext context = arg0.getSession().getServletContext();

      

           Integer count = (Integer) context.getAttribute("peopleOnline");

           if (count == null) {

               count = 1;

           } else {

               count++;

           }

           context.setAttribute("peopleOnline", count);

        }

      

        public void sessionDestroyed(HttpSessionEvent arg0) {

           ServletContext context = arg0.getSession().getServletContext();

           Integer count = (Integer) context.getAttribute("peopleOnline");

      

           count--;

           context.setAttribute("peopleOnline", count);

        }

 

}

登入後複製

此处还要给OnlineListener监听器类在web.xml文件中配置路径,web.xml配置代码具体如下(红色标记代码):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name></display-name>

   

  <listener>

    <listener-class>com.liuzhen.chart.OnlineListener</listener-class>

  </listener>

    

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>Main</servlet-name>

    <servlet-class>com.liuzhen.chart.Main</servlet-class>

  </servlet>

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>InputInformation</servlet-name>

    <servlet-class>com.liuzhen.chart.InputInformation</servlet-class>

  </servlet>

   

 

 

  <servlet-mapping>

    <servlet-name>Main</servlet-name>

    <url-pattern>/Main</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>InputInformation</servlet-name>

    <url-pattern>/InputInformation</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>login.jsp</welcome-file>

  </welcome-file-list>

</web-app>

登入後複製

在调用监听器类实现监听系统当前在线人数时,本机上同一个浏览器同时登陆多个用户,只能算作一次,本机上不同浏览器登陆则分别算作一次。以下分别是在IE、谷歌和360浏览器登陆在线人数显示:

使用Servlet和JSP實作一個簡單的Web聊天室系統

图四:IE浏览器登陆,显示在线人数1人

使用Servlet和JSP實作一個簡單的Web聊天室系統

图五:谷歌浏览器登陆,显示在线人数2人

使用Servlet和JSP實作一個簡單的Web聊天室系統

图六:360浏览器登陆,显示在线人数3人

 附:本文系统代码Coding链接:https://coding.net/u/LiuZhen1995/p/MyDemo/git/tree/origin_seven

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板