[Java] [session] Using XMLHTTP and Java session Monitoring to improve the on-site message system

Source: Internet
Author: User
Tags object serialization
Improve the on-site message system with XMLHTTP and Java session listening

This topic contains many concepts that need to be explained. It is easy to describe "intra-site messages", which is a function available in many forums and can be used to send messages to other online users through the Web, many users have used it. The first advantage of intra-site messages is that you do not need to install the client. You do not need to know the other party's MSN or QQ to contact him, praise his point of view or give him a scolding. The second advantage is the ease of customer management. Session is used to maintain the online list, and various scripts have encapsulated session operations to make it easy to use, like other stateless instant messaging tools (such as UDP tools), you don't need to spend some brain cells to solve the online list problem. The disadvantage is that the real-time performance is poor. Generally, messages can be detected and the online list can be updated only when users jump to or refresh the page.

Session listening. Java provides a flexible event mechanism to listen to sessions and can listen to the creation and destruction of sessions, monitors the creation, change, and destruction of the data carried by a session, and can listen on the sharpening and passivation of the session (the brother who understands Object serialization should know this ), I don't know what other platforms are like. If you can monitor sessions of all customers, you do not need to operate the troublesome and dangerous application.

XMLHTTP is a technology pushed by Ms. It has complex functions and can do many things. For example, a client can open an HTTP connection in simple HTML and actively request data from the server and obtain the returned data, it is a very important application of DOM technology. It is so easy to use it to write refreshing dynamic pages. The web developers should understand how significant it is.

I. Session listening

The servlet provides many interfaces for session listening, which are flexible and most commonly used for listening to sessions and attributes. Here we need to clarify the concept. Session listening in servlet has different meanings from attribute listening. Session listening does not mean that we generally understand to place a session or destroy a session, this is the attribute listening function, because the session syntax in the servlet is session. setattribute ("session name", object to be put ). Session listening listens on HTTP connections. If a user connects to the server, a blank JSP page will trigger session events, therefore, the session here actually refers to connection, which is most suitable for counting the number of online users. I don't know. The following describes the two listening methods.
1. Session listening

First, write a session listener class to implement the httpsessionlistener interface. It is used to calculate the number of online users currently:

Package org. bromon. test;

Import javax. servlet .*;
Import javax. servlet. http .*;

Public class sessioncount implements httpsessionlistener
{
Private Static int COUNT = 0;

Public void sessioncreated (httpsessionevent SE)
{
Count ++;
System. Out. println ("session creation:" + new java. util. Date ());
}

Public void sessiondestroyed (httpsessionevent SE)
{
Count --;
System. Out. println ("session destruction:" + new java. util. Date ());
}

Public static int getcount ()
{
Return (count );
}
}

How about it? Count is defined as static because only one count is required for the entire system. If you are not at ease, you can write it into a singleton class.

Then declare the listener in Web. xml:

<Listener>
<Listener-class>
Org. bromon. Test. sessioncount
</Listener-class>
</Listener>

Compile a test. jsp test page to obtain count:

<%
Int COUNT = org. bromon. Test. sessioncount. getcount ();
Out. println (count );
%>

Note that no session operations are involved here. Restart the app server and try to connect to test. jsp. You can see that the listener has started to work.
2. Attribute listening

As an in-site message system, it is possible to send messages to each other only by obtaining the IDs of all login users. This involves attribute listening. Assume that we have written a user login module. After the user passes authentication, a session is generated to save its related information, for example:

// Check. jsp
<%
String name = request. getparameter ("name ");
Name = new string (name. getbytes ("ISO8859-1 "));
Session. setattribute ("user", name );
%>

JSP brothers should not be familiar with this Code. Next we will write a listener to listen to user login and save all user IDs to a list. This listener is implemented as the httpsessionattributelistener interface:

Package org. bromon. test;

Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. util .*;

Public class onlinelist implements httpsessionattributelistener
{
Private Static list = new arraylist ();

Public void attributeadded (httpsessionbindingevent SE)

{
If ("user". Equals (SE. getname ()))
{
List. Add (SE. getvalue ());
}
}

Public void attributeremoved (httpsessionbindingevent SE)
{
If ("user". Equals (SE. getname ()))
{
List. Remove (SE. getvalue ());
}
}

Public void attributereplaced (httpsessionbindingevent SE ){}

Public static list getlist ()
{
Return (list );
}
}

Write a simple JSP to get the user list:

& Ly; %
Java. util. List list = org. bromon. Test. onlinelist. getlist ();
Out. println ("Total" + list. Size () + "user logged on :");
For (INT I = 0; I <Lise. Size (); I ++)
{
Out. println (list. Get (I ));
}
%>

Maybe you said, what is the Magic? Listen to the session, don't worry, look at XMLHTTP.
Ii. XMLHTTP

XMLHTTP is of a lot of use. Here we only need to talk about communication with the server without refreshing it. Let's look at this Code:

<Script language = "JavaScript">
Xml = new activexobject ("Microsoft. XMLHTTP ");
VaR post = ""; // construct the data to carry
XML. open ("Post", "http: // localhost: 7001/testwl/index. JSP ", false); // use the POST method to open a connection to the server and communicate asynchronously.
XML. setRequestHeader ("Content-Length", post. Length );
XML. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
XML. Send (post); // send data
VaR res = xml. responsetext; // receives data from the server
Document. Write (RES );
</SCRIPT>

Suddenly, this code is used to open an HTTP connection and pass data in standard HTTP format. If you like it, you can use XML format to transfer data. You can change the XML Object Construction Method to be compatible with Mozilla and Netscape. Next, we will write a round robin to refresh the user list every time. Of course, we do not need to refresh the page:

<HTML>
<Head> <title> detector </title>
<Script language = "JavaScript">
Function detect ()
{
Xml = new activexobject ("Microsoft. XMLHTTP ");
VaR post = ""; // construct the data to carry
XML. open ("Post", "http: // localhost: 7001/testwl/index. JSP ", false); // use the POST method to open a connection to the server and communicate asynchronously.
XML. setRequestHeader ("Content-Length", post. Length );
XML. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
XML. Send (post); // send data
VaR res = xml. responsetext; // receives data from the server
List. innertext = res;
SetTimeout ("detect ()", 5000); // Round Robin every 5 seconds
}
</SCRIPT>
<Body onload = "detect ()">
<A id = "list"> </a>
</Body>
</Html>

This communication method has a small amount of data, so you don't have to re-transmit the entire page. It takes five seconds to go round, so that normal PCs can withstand a large number of online messages. Constructing a detector to listen to online lists and messages has a very good effect. Even if your customers sit in front of the computer and do not touch the mouse, they can ensure real-time data transmission, page does not jump or refresh.

Session listening and XMLHTTP communication make it easy to develop a well-developed intra-site messaging system.

 

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.