Using XMLHTTP and Java session monitoring to improve the message system in the station

Source: Internet
Author: User
Tags date format object count interface object serialization string what magic
Session|xml

Using XMLHTTP and Java session monitoring to improve the message system in the station

Bromon Original quote:http://www.javaresearch.org/article/showarticle.jsp?column=106 &thread=25340

This topic contains a lot of concepts to explain, the easiest to say is "in-station message", which is the function of many forums, can send messages to other online users through the Web, many users have used. The first advantage of information in the station is that we do not need to install the client, you do not have to know the other's MSN or QQ, you can contact him, praise his views or give him a scolding. The second advantage is customer management convenience, using session to maintain online lists, the various scripts have already encapsulated the session operation is very easy to use, without the same as other stateless instant messaging tools (such as using UDP communication tools), it costs some brain cells to solve the problem of online lists. The disadvantage is that the real-time is not good, generally in the user jump or refresh the page to detect messages, update the online list.

Session listening, there is nothing to explain, Java provides a very flexible event mechanism to listen to the session, you can listen to the creation and destruction of sessions, monitoring the session of the data carried by the creation, change and destruction, You can monitor the sharpening and passivation of the session (the brother who understands object serialization should know this), the other platform is a case I'm not sure, I guess. If you can monitor all of your clients ' sessions, you won't have to go through the hassle-free application.

XMLHTTP is a technology of MS Push, the function is very complex, can do a lot of things, such as the client can open the HTTP connection in the simple HTML, the initiative to request data from the server and get the return data, is a very important application of DOM technology, Using it to write a dynamic page without refreshing is simply easy, and a brother who has done web development should understand how important it is.

First, session monitoring

There are many interfaces in the servlet for session listening, the function is very flexible, the most commonly used is the listening session and attribute. Here to clarify the concept, the servlet in the session monitoring and attribute monitoring meaning there is a difference, session monitoring refers to not what we generally understand to place a session or destroy a session, which is the function of monitoring, Because the syntax for placing sessions in the servlet is Session.setattribute ("Session name", the object to put in). and session listening, listening to the HTTP connection, as long as there is a user connected to the server, even if the connection is a blank JSP page, will also trigger the sessions event, so here is the connection actually refers to the The most appropriate time to count the current number of users online. I don't know if I have made myself clear. The following are the two ways to monitor each.

1, Session Monitoring

First, write a session listener class, which is implemented as the Httpsessionlistener interface, and its function is to calculate how many online users are currently:

  1. /**
  2. * @Author Bromon
  3. *2004-6-12
  4. */
  5. package org.bromon.test;
  6. import javax.servlet.*;
  7. import javax.servlet.http.*;
  8. Public class Sessioncount implements httpsessionlistener
  9. {
  10. Private Static int count=0;
  11. Public void sessioncreated (httpsessionevent se)
  12. {
  13. count++;
  14. System. OUT.PRINTLN ("Session creation:" +new java.util. ) Date());
  15. }
  16. Public void sessiondestroyed (httpsessionevent se)
  17. {
  18. count--;
  19. System. OUT.PRINTLN ("Session Destroy:" +new java.util. ) Date());
  20. }
  21. Public Static int GetCount ()
  22. {
  23. return (count);
  24. }
  25. }

How, is not at a glance? Count is defined as static because it is guaranteed to have only one count for the entire system. If you're not comfortable with it, you can write it as a single case class.

Then declare the listener in Web.xml:
<listener>
<listener-class>
Org.bromon.test.SessionCount
</listener-class>
</listener>

Write a test page test.jsp to get count:
<%
int Count=org.bromon.test.sessioncount.getcount ();
Out.println (count);
%>

It should be noted that no session action is involved here at all. Restart the app server, try connecting to test.jsp, and you can see that the listener has started working.

2, attribute monitoring
As an in-station message system, it is certain to obtain the ID of all the landers to be able to send messages to each other. This involves attribute monitoring. Suppose we write a user login module, the user will be authenticated after a session, save its relevant information, such as:
    1. //check.jsp
    2. <%
    3. String name=request.getparameter ("name");
    4. Name=new String(name.getbytes ("iso8859-1"));
    5. Session.setattribute ("user", name);
    6. %>


The brother who has done JSP should be familiar with this code, the following write a listener to monitor the user login, the ID of all users to a list, the listener implemented as Httpsessionattributelistener interface:

  1. /**
  2. * @Author Bromon
  3. *2004-6-12
  4. */
  5. package org.bromon.test;
  6. import javax.servlet.*;
  7. import javax.servlet.http.*;
  8. import java.util.*;
  9. Public class Onlinelist implements httpsessionattributelistener
  10. {
  11. Private Static List list=new ArrayList();
  12. Public void attributeadded (httpsessionbindingevent se)
  13. {
  14. if ("User". Equals (Se.getname ()))
  15. {
  16. List.add (Se.getvalue ());
  17. }
  18. }
  19. Public void attributeremoved (httpsessionbindingevent se)
  20. {
  21. if ("User". Equals (Se.getname ()))
  22. {
  23. List.remove (Se.getvalue ());
  24. }
  25. }
  26. Public void attributereplaced (httpsessionbindingevent se) {}
  27. Public Static List getlist ()
  28. {
  29. return (list);
  30. }
  31. }


write a simple JSP to the user list:
<%
Java.util.List list=org.bromon.test.onlinelist.getlist ();
Out.println ("A Total" +list.size () + "The user has Landed:");
for (int i=0;i<lise.size (); i++)
{
Out.println (List.get (i));
}
%>

Perhaps you say, this is what magic, listen to session just, not anxious, look xmlhttp.

Second, XMLHTTP

XMLHTTP a lot of useful, here just say what we need, is no refresh with the server communication, look at this code:

  1. <script language="JavaScript">
  2. XML = new ActiveXObject ("Microsoft.XMLHTTP");
  3. var post=""; //construct the data to carry
  4. Xml.open ("POST","http://localhost:7001/TestWL/index.jsp",false); //Use the Post method to open a connection to the server and communicate asynchronously
  5. Xml.setrequestheader ("Content-length", post. Length);
  6. Xml.setrequestheader ("Content-type","application/x-www-form-urlencoded");
  7. Xml.send (POST); //Send data
  8. var res = Xml.responsetext; //data returned by the receiving server
  9. document.write (RES);
  10. </script>



Suddenly, the code is to open an HTTP connection, pass the data in the standard HTTP format, and if you like, you can pass it in XML format. Changing the way XML objects are constructed can be compatible with Mozilla and Netscape. Write a poll below, refresh the list of users every once in a while, and of course, do not need to refresh the page:

  1. <script language="JavaScript">
  2. function Detect ()
  3. {
  4. XML = new ActiveXObject ("Microsoft.XMLHTTP");
  5. var post=""; //construct the data to carry
  6. Xml.open ("POST","http://localhost:7001/TestWL/index.jsp",false); //Use the Post method to open a connection to the server and communicate asynchronously
  7. Xml.setrequestheader ("Content-length", post. Length);
  8. Xml.setrequestheader ("Content-type","application/x-www-form-urlencoded");
  9. Xml.send (POST); //Send data
  10. var res = Xml.responsetext; //data returned by the receiving server
  11. List.innertext=res;
  12. SetTimeout ("Detect ()", 5000); //Poll once every 5 seconds
  13. }
  14. </script>
  15. <body onload= "Detect ()" >
  16. <a id= "List" ></a>
  17. </body>


Such a way of communication data is very small, do not have to transfer the entire page, 5 seconds, the average PC can withstand a larger number of online. Building a probe to monitor online listings and messages is good, even if your client sits in front of the computer and does not touch it, it can ensure that the data is delivered instantly and the page does not jump and refresh.

Session monitoring plus XMLHTTP communication, the development of a more complete station message system is a breeze.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.