WebSocket Real-time refresh of front-end pages when database updates are implemented

Source: Internet
Author: User

WebSocket Real-time refresh of front-end pages when database updates are implemented javaweb

directory (?) [+]

    1. userjsp
    2. Managerservletjava

Title, to achieve the above functions, I know there are two major ideas:

    1. Polling: Polling is the principle of sending a request to the server over a period of time, which is not described here. Here is a discussion of the second way of thinking.
    2. WebSocket to the front-end communication: WebSocket is a new protocol for HTML5, based on TCP, after a handshake, the establishment of an HTTP connection, the client and the server to achieve full-duplex communication. Compared with polling mechanism, save resources, do not need frequent requests.

The following is the most streamlined example of a javaweb+mysql instance, only the key code is posted. (originally on GitHub, there are websocket-api.jar,.sql files and readme.doc that are needed in this example for easy understanding of this example).

USER.JSP:



<%@ page import="model. UserBean " %>
<%@ page import="java.util.List" %>
<%@ page import="fun. Client " %>

<%@ page contenttype="Text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>$Title $</title>
</head>
<body>
<tableid="table" Border="1">
<tr>
<th >Id</th>
<th >Name</th>
</tr>
<%
To the database information, placed in the list
Client client=New client ();
List<userbean> list= client.list ();
if (List! = null) {
for (UserBean user:list) {
%>
<tr >
<TD ><%=user.getid ()%></td>
<TD ><%=user.getname ()%></td>
</tr>
<%
}
}
%>
</table>
<div id="message"></div>

<script>
varWebSocket =NULL;
//Determine if the current browser supports WebSocket
if(' WebSocket ' inchwindow) {
//Establish a connection, where the/websocket is the value in the opening annotation in Managerservlet
WebSocket =NewWebSocket ("Ws://localhost:8080/websocket");
}
Else{
Alert' current browser not support WebSocket ')
}
//Connection Error callback method
Websocket.onerror = function () {
Setmessageinnerhtml ("WebSocket connection error occurred");
};
//Connection successfully established callback method
Websocket.onopen = function () {
Setmessageinnerhtml ("WebSocket Connection succeeded");
}
//The callback method that receives the message
Websocket.onmessage = function (event) {
Setmessageinnerhtml (Event.data);
if(event.data=="1"){
Location.reload ();
}
}
//Connection shutdown callback method
Websocket.onclose = function () {
Setmessageinnerhtml ("WebSocket connection off");
}
//Monitoring window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception.
Window.onbeforeunload = function () {
Closewebsocket ();
}
//Display messages on a Web page
function setmessageinnerhtml(InnerHTML) {
document.getElementById (' message '). InnerHTML + = InnerHTML +' <br/> ';
}
//Close WebSocket connection
function closewebsocket() {
Websocket.close ();
}
</script>
</body>
</html>

The previously inserted Java code obtains the information in the database, the following JS code realizes websocket communication.

Managerservlet.java:
 PackageFun
ImportJavax.servlet.ServletException;
ImportJavax.servlet.http.HttpServlet;
ImportJavax.servlet.http.HttpServletRequest;
ImportJavax.servlet.http.HttpServletResponse;
Importjavax.websocket.*;
ImportJavax.websocket.server.ServerEndpoint;
ImportJava.io.IOException;
ImportJava.sql.PreparedStatement;
ImportJava.util.concurrent.CopyOnWriteArraySet;

/**
* This class implements the Servlet class for database operation, and realizes the function of WebSocket.
*/

//The note is used to specify a URI that the client can use to connect to WebSocket, a servlet-like annotation mapping;
The //servlet registration is placed in Web. Xml.
@ServerEndpoint(Value ="/websocket")
Public class managerservlet extends httpservlet {
The thread-safe set of the//concurrent package that holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can identify the user
Private StaticCopyonwritearrayset<managerservlet> Websocketset =NewCopyonwritearrayset<managerservlet> ();
//This session is not httpsession, equivalent to the user's unique identity, used to communicate with the specified user
PrivateJavax.websocket.Session session=NULL;

Public void Doget(HttpServletRequest request, httpservletresponse response)throwsservletexception,ioexception {
String msg;
String Name=request.getparameter ("Name");
//Here The submit is the method of database operation, if inserting data is successful, send update signal
if(Submit (name)) {
//Send update signal
SendMessage ();
msg="ok!";
}Else{
msg="error!";
}
Response.sendredirect ("manager.jsp?msg="+MSG);
}
Public void DoPost(HttpServletRequest request,httpservletresponse reponse)throwsServletexception, IOException {
Doget (Request,reponse);
}
/**
* Insert a name into the database
* @param Name
* @return
*/
Public Boolean Submit(String name) {
DB db=NewDB ();
String sql=INSERT into users values (?);
Try{
PreparedStatement pstmt=db.con.preparestatement (SQL);
Pstmt.setstring (1, name);
Pstmt.executeupdate ();
return true;
}Catch(Exception e) {
E.printstacktrace ();
return false;
}finally{
Db.close ();
}
}

/**
* @OnOpen allows us to intercept the creation of a new session.
* The session class allows us to send data to the user.
* In the method OnOpen, we'll let the user know this handshake was
* Successful.
* Called when establishing a WebSocket connection
*/
@OnOpen
Public void OnOpen(Session session) {
System.out.println ("Session"+ Session.getid () +"has opened a connection");
Try{
This. session=session;
Websocketset.add ( This);//Add in Set
Session.getbasicremote (). SendText ("Connection established");
}Catch(IOException ex) {
Ex.printstacktrace ();
}
}

/**
* When a user sends a message to the server, this method would intercept the message
* and allow us to react to it. For now, the message is read as a String.
* Used when receiving client messages, this is useless in this case
*/
@OnMessage
Public void OnMessage(String message, session session) {
System.out.println ("Message from"+ Session.getid () +": "+ message);
}

/**
* The user closes the connection.
*
* Note:you can ' t send messages to the client from this method
* Called when connection is closed
*/
@OnClose
Public void OnClose(Session session) {
Websocketset.remove ( This);//Remove from set
System.out.println ("Session"+session.getid () +"has closed!");
}

/**
* Note: OnError () can only occur once. The parameters are optional.
* @param session
* @param t
*/
@OnError
Public void OnError(Session session, Throwable T) {
T.printstacktrace ();
}

/**
* This method is not the same as the above methods. Without annotations, it is based on the method you need to add.
* @throws IOException
* Send a custom signal, "1" means to tell the foreground, the database has changed, need to refresh
*/
Public void SendMessage()throwsioexception{
//Mass message
for(Managerservlet Item:websocketset) {
Try{
Item.session.getBasicRemote (). SendText ("1");
}Catch(IOException e) {
E.printstacktrace ();
Continue;
}
}

}
}

This class first inherits the HttpServlet, the purpose is to receive the form data to complete the database modification. Second, this class implements the function of websocket . In the Doget () method, you can see that once the database has changed, you will be sent to the foreground "1", the foreground receives "1" can refresh the page.

Read the full text

WebSocket Real-time refresh of front-end pages when implementing database updates

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.