"Listener" uses the listener Listener to complete the output of the online user list with the idea of MVC JSP+SERVLET+JDBC

Source: Internet
Author: User
Tags get ip stub mysql command line



Servlet, Listener Listener and "Filter" Interceptor Filter (click Open link) is the three core components of JSP, in fact, the listener listener equivalent to the trigger in the database, once the user triggered a certain behavior, The corresponding program can be executed through the relevant Java files. Users in the process of browsing the web, the main browser to open the action, the corresponding behavior is the creation of the session, but the user to close the browser action, not corresponding to the disappearance of the session, so for the disappearance of the session we have little meaning; access to any page of the action, The corresponding behavior is the creation of requests, and the disappearance of the request does not make any sense to our program ape; The server itself starts and shuts down. The corresponding behavior is the creation and disappearance of application.



Using the listener listener with the database, you can complete the online user list statistics.






I. BASIC OBJECTIVES



Output a list of online users, set the user to visit our site 127.0.0.1:8080/listener that its online, in fact, is localhost:8080/listener, but Localhost:8080,ip address has become 0::0 : 11 IP6 address is very ugly, so still use 127.0.0.1:8080, because can not listen to whether the user closes the browser, so set if the user does not have access to any of our web site in 5 seconds, it is considered to be offline, just to see the experimental results, should be set longer.



For example, open two browser, each browser corresponding to a session, think is two users visit our website. In fact, you use the listener, you can also do a complex point, by checking whether this user name is logged in the way to determine whether it landed. As I did before in "PHP" based on Xajax's online chat room, live room (click to open link).









II. Basic Preparation



First create an online user table in the database, such as:






This table does not have a primary key, because it needs to be repeatedly erased by the insert and delete, I do not intend to use the primary key to count the number of history online, lest the primary key is too ugly, so do not set the primary key.



Because you do not set a primary key, you cannot create a table graphically, if you are building a table through Mysqlquerybrowser, rather than MySQL Command line client, you should:






In the query statement input box, enter:





create table onlineTable(
  sessionId varchar(45),
  ip varchar(45),
  timeonline LONG
)

After building the table, create a new network engineering listenertest in Eclipse and put the servlet and JDBC packages from the last "servlet" Design user login, user registration, and Change Password system (click to open link) to Lib, based on the MVC idea. The two Lib online a search, at the same time put the Dbdao.java into the Listenertest src folder, and add a new insert, modify the exact same deletion delete method, Finally the whole Dbdao.java as follows, almost exactly the same, nothing changed, this is the advantage of MVC, because we use the same database test, the pain once write the database and delete changes to the class, after multiple reuse on the happiness.







import java.sql. *;

public class dbDAO {
private Connection con;

// Constructor, connect to the database
public dbDAO () throws Exception {
String dburl = "jdbc: mysql: // localhost: 3306 / test? UseUnicode = true & characterEncoding = utf8 & useOldAliasMetadataBehavior = true";
String dbusername = "root";
String dbpassword = "root";
Class.forName ("com.mysql.jdbc.Driver");
this.con = DriverManager.getConnection (dburl, dbusername, dbpassword);
}

// execute the query
public ResultSet query (String sql, Object ... args) throws Exception {
PreparedStatement ps = con.prepareStatement (sql);
for (int i = 0; i <args.length; i ++) {
ps.setObject (i + 1, args [i]);
}
return ps.executeQuery ();
}

// perform insert
public boolean insert (String sql, Object ... args) throws Exception {
PreparedStatement ps = con.prepareStatement (sql);
for (int i = 0; i <args.length; i ++) {
ps.setObject (i + 1, args [i]);
}
if (ps.executeUpdate ()! = 1) {
return false;
}
return true;
}

// perform modification
public boolean modify (String sql, Object ... args) throws Exception {
PreparedStatement ps = con.prepareStatement (sql);
for (int i = 0; i <args.length; i ++) {
ps.setObject (i + 1, args [i]);
}
if (ps.executeUpdate ()! = 1) {
return false;
}
return true;
}
Ranch
// execute delete
public boolean delete (String sql, Object ... args) throws Exception {
PreparedStatement ps = con.prepareStatement (sql);
for (int i = 0; i <args.length; i ++) {
ps.setObject (i + 1, args [i]);
}
if (ps.executeUpdate ()! = 1) {
return false;
}
return true;
}

// Destructor, interrupt the database connection
protected void finalize () throws Exception {
if (! con.isClosed () || con! = null) {
con.close ();
}
}
}





After the configuration of Web. XML, such fragments are generally the same as the filter to the top, indicating that the entire site behavior by the root of the Onlinelistener.java listening, write such a listener code, after the user triggers a certain behavior, if the Onlinelistener.java has the corresponding code, Then the code is executed:





<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<listener>
		<listener-class>onlineListener</listener-class>
	</listener>
</web-app>

Finally, the overall network structure is as follows:











Third, the production process



1, in fact, is to write a good listener.java on OK. As in the Filter interceptor filter (click to open link), once we want to listen to an action, we have to rewrite the action of the destruction and creation of the implementation method, because the interface is used here, you do not write really not. Also do not be afraid that a method is too long to remember, Eclipse for Java EE will help you automatically generated. can be monitored by means of servletrequestlistener means that the user accesses any URL, each visit to a Web page is monitored/triggered once, is actually listening to the request object; Servletcontextlistener start and end of the server monitoring/ Trigger once, is actually listens to the application object, through to the Application object listens can achieve "the Servlet" uses the Load-on-startup to create a thread with the server to survive (click Open link) effect And Httpsessionlistener, when the user opens the browser to listen/trigger once, actually listens to the session object creation and destroys, here is not used.





import java.util. *;
import java.sql. *;

import javax.servlet. *;
import javax.servlet.http. *;

public class onlineListener implements ServletRequestListener,
ServletContextListener {

// The destruction of the request object doesn't mean much to us
@Override
public void requestDestroyed (ServletRequestEvent servletRequestEvent) {

}

// The creation of the request object is equivalent to the user visiting any number of web pages
@Override
public void requestInitialized (ServletRequestEvent servletRequestEvent) {
// The parameters of this method can be converted into a request object
HttpServletRequest request = (HttpServletRequest) servletRequestEvent
.getServletRequest ();
// method of taking session in request object
HttpSession session = request.getSession ();
String sessionId = session.getId ();
// method to get ip in request object
String ip = request.getRemoteAddr ();
// Database query results
ResultSet rs = null;
try {
// If this sessionID is already in the online user list
// user is online
// then update its online time
dbDAO db = new dbDAO ();
rs = db.query ("select * from onlinetable where sessionId =?",
sessionId);
if (rs.next ()) {
db.modify (
"update onlinetable set timeonline =? where sessionId =?",
System.currentTimeMillis (), sessionId);
}
// otherwise insert online user list
else {
db.insert ("insert into onlinetable values (?,?,?)", sessionId,
ip, System.currentTimeMillis ());
}
// Put the current online user list in the application
rs = db.query ("select * from onlinetable");
} catch (Exception e) {
e.printStackTrace ();
}
// session.getServletContext () is equivalent to application, which stores the online user list with application
session.getServletContext (). setAttribute ("onlineTable", rs);

}

// The disappearance of the application doesn't mean much to us
// equivalent to server shutdown, everything is gone
@Override
public void contextDestroyed (ServletContextEvent arg0) {
// TODO Auto-generated method stub

}

// The start of the application is equivalent to the start of the server
@Override
public void contextInitialized (ServletContextEvent arg0) {
// TODO Auto-generated method stub
// Once the server is started, perform the following tasks every 5 seconds
Timer timer = new Timer ();
timer.schedule (new MyTask (), 0, 5000);

}
}

class MyTask extends TimerTask {
public void run () {
try {
// check online user list
dbDAO db = new dbDAO ();
ResultSet rs = db.query ("select * from onlinetable");
while (rs.next ()) {
// If the current time is more than 5 seconds from the user's last online time
// Then delete this result from the online user list.
if (System.currentTimeMillis ()-rs.getLong ("timeonline")> 5 * 1000) {
db.delete ("delete from onlinetable where sessionId =?",
rs.getString ("sessionId"));
}
}
} catch (Exception e) {
e.printStackTrace ();
}
}
}

Here, "Java" is used to think about System.currenttimemillis () (click Open link), remove the January 1, 1970 to present the concept of the number of milliseconds to generate a timestamp, and "Java" Perform tasks every 5 seconds using the concept of timer and TimerTask timed tasks (click to open link).








2, then write a online.jsp to display the current database of the online user list, because the listener in each listening requests request process, has put the online user list in the application container, and constantly update the message inside. The application container is a large container on the server that can be seen by all users. This is different from the session container, which is the only small container that the browser can see after each user opens the browser. ONLINE.JSP read the results of the online user list query in this application container. Note that the object to be taken out, to be forced type conversion, not converted by error.


<% @ page language = "java" contentType = "text / html; charset = utf-8"
pageEncoding = "utf-8"%>
<% @ page import = "java.sql. *"%>
<! DOCTYPE html PUBLIC "-// W3C // DTD HTML 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text / html; charset = utf-8">
<title> List of online users </ title>
</ head>
<body>
List of online users
<% ResultSet rs = (ResultSet) application.getAttribute ("onlineTable");%>
<table border = "1">
<tr>
<td> ip </ td>
<td> sessionId </ td>
</ tr>
<%
while (rs.next ()) {
%>
<tr>
<td> <% = rs.getString (2)%> </ td>
<td> <% = rs.getString (1)%> </ td>
</ tr>
<%}%>
</ table>
</ body>
</ html>




Fourth, summary and outlook
In fact, the MVC layering of the entire network project is as follows. MODEL is the same MODEL as previously written in "[Servlet] Designing User Login, User Registration, and Password Modification Based on MVC Ideas" (click to open the link). Since it is the same database, it is completely possible Where to pay attention. Online.jsp is used as the view. It does not directly query the database. It reads the C-level listener and puts the query results.


Although using [Java] using the new array traversal method after JDK1.5 to traverse HashMap, HashMap should not store multivariate groups (click to open the link), the same can store online user information, but the reason why it is used The database stores online user information because you can avoid setting an ArrayList of storage classes into the Application container. Putting an ArrayList of storage classes into the Application container is not simpler than putting it into a database, mainly because the program is not clear enough.

[Listener] Use Listener to complete the output of online user list through JSP + Servlet + JDBC based on MVC

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.