websocket实现数据库更新时前端页面实时刷新
<div class="category_r">
<label>
<span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">javaweb<em></em>
</span>
</label>
</div>
</div>
<div class="bog_copyright">
</div>
<div style="clear:both"></div><div style="border:solid 1px #ccc; background:#eee; float:left; min-width:200px;padding:4px 10px;"><p style="text-align:right;margin:0;"><span style="float:left;">目录<a href="https://blog.csdn.net/VVVinegar/article/details/71706670" title="系统根据文章中H1到H6标签自动生成文章目录">(?)</a></span><a href="#" onclick="javascript:return openct(this);" title="展开">[+]</a></p><ol style="display:none;margin-left:14px;padding-left:14px;line-height:160%;"><li><a href="https://blog.csdn.net/VVVinegar/article/details/71706670#t0">userjsp</a></li><li><a href="https://blog.csdn.net/VVVinegar/article/details/71706670#t1">ManagerServletjava</a></li></ol></div><div style="clear:both"></div><div id="article_content" class="article_content csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post" style="overflow: hidden;">
<div class="markdown_views">
<p>如题,实现以上功能,我知道主要有两大种思路:</p>
- 轮询:轮询的原理是隔一段时间向服务器发送一个请求,这里不累述。这里主要谈一下第二种思路。
- websocket进行前后端通讯:websocket是html5的新协议,基于TCP,在一次握手后,建立http连接,实现客户端与服务端全双工通信。相比较轮询机制,节约资源,不需要频繁的请求。
下面通过最精简的javaweb+mysql实例说明,只贴出关键代码。(原码放在github中,里面有本例需要的websocket-api.jar,.sql文件以及README.doc,方便理解本例)。
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>
<table id="table" border="1">
<tr>
<th >id</th>
<th >name</th>
</tr>
<%
//的到数据库信息,放在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>
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
//建立连接,这里的/websocket ,是ManagerServlet中开头注解中的那个值
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
if(event.data=="1"){
location.reload();
}
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
</script>
</body>
</html>
前面插入的java代码得到数据库中的信息,后面的js代码实现websocket通讯。
ManagerServlet.java:
package fun;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* 这个类即实现了进行数据库操作的Servlet类,又实现了Websocket的功能.
*/
//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket,类似Servlet的注解mapping;
// servlet的注册放在了web.xml中。
@ServerEndpoint(value = "/websocket")
public class ManagerServlet extends HttpServlet {
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<ManagerServlet> webSocketSet = new CopyOnWriteArraySet<ManagerServlet>();
//这个session不是Httpsession,相当于用户的唯一标识,用它进行与指定用户通讯
private javax.websocket.Session session=null;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
String msg;
String name=request.getParameter("name");
//这里submit是数据库操作的方法,如果插入数据成功,则发送更新信号
if(submit(name)){
//发送更新信号
sendMessage();
msg="ok!";
}else {
msg="error!";
}
response.sendRedirect("manager.jsp?msg="+msg);
}
public void doPost(HttpServletRequest request,HttpServletResponse reponse) throws ServletException, IOException {
doGet(request,reponse);
}
/**
* 向数据库插入一个name
* @param name
* @return
*/
public boolean submit(String name){
DB db=new DB();
String sql="insert into users(name) 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 that the handshake was
* successful.
* 建立websocket连接时调用
*/
@OnOpen
public void onOpen(Session session){
System.out.println("Session " + session.getId() + " has opened a connection");
try {
this.session=session;
webSocketSet.add(this); //加入set中
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
* 接收到客户端消息时使用,这个例子里没用
*/
@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
* 关闭连接时调用
*/
@OnClose
public void onClose(Session session){
webSocketSet.remove(this); //从set中删除
System.out.println("Session " +session.getId()+" has closed!");
}
/**
* 注意: OnError() 只能出现一次. 其中的参数都是可选的。
* @param session
* @param t
*/
@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @throws IOException
* 发送自定义信号,“1”表示告诉前台,数据库发生改变了,需要刷新
*/
public void sendMessage() throws IOException{
//群发消息
for(ManagerServlet item: webSocketSet){
try {
item.session.getBasicRemote().sendText("1");
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
这个类首先继承了HttpServlet,目的是接收表单数据完成数据库的修改。其次,这个类实现了websocket的功能。在doGet()方法中,可以看到,一旦数据库发生改变,就会向前台发送“1”,前台收到“1”后即可刷新页面。
<div style="clear:both; height:10px;"></div>
</div>
websocket实现数据库更新时前端页面实时刷新的更多相关文章
- websocket+订阅发布者模式模拟实现股票价格实时刷新
1.新建文件夹 2.文件夹中新建index.html 和 index.js index.html <!DOCTYPE html> <html lang="en"& ...
- flask处理数据,页面实时刷新展示
背景: 后端 flask(python)处理数据,页面实时刷新,类似于打包页面的动态展示,展示效果如图: 代码如下: 前端主要使用以下循环处理, 2--- 2秒刷新一次 {% if 0 == stop ...
- WebSocket实现数据库更新前台实时显示
通过一个小实例来实现数据库更新后,推送消息给前台,让前台进行相应操作. 需求 数据库更新之后服务器推送消息给前台,让前台做操作.(数据库的数据不是由服务器写入的) 实现的话说到底都是用轮询,因为数据库 ...
- Vue+WebSocket 实现页面实时刷新长连接
最近vue项目要做数据实时刷新,折线图每秒重画一次,数据每0.5秒刷新一次,说白了就是实时刷新,因为数据量较大,用定时器估计页面停留一会就会卡死... 与后台人员讨论过后决定使用h5新增的WebSoc ...
- web页面实时刷新之browser sync
web开发对实时刷新的需求 在刚开始学习前端时每次修改文件内容后都需要手工刷新下浏览器来看效果,做的次数多了就特别难受,有时仅仅修改了一个字母都需要刷新下页面查看 之后接触到编写边看的集成IDE,文件 ...
- 基于node的前端页面实时更新。呦吼~
学习了gulp,webpack后越发觉得前端开发万分的有趣,首当其冲的就是解决了狂按f5的尴尬. 当我们按下ctrl+s保存后页面自动更新了,我就觉得我f5键在隐隐的发笑. 1.node_npm_li ...
- 基于python的websocket开发,tomcat日志web页面实时打印监控案例
web socket 接收器:webSocket.py 相关依赖 # pip install bottle gevent gevent-websocket argparse from bottle i ...
- Vue 数组和对象更新,但是页面没有刷新
在使用数组的时候,数组内部数据发生改变,但是与数组绑定的页面的数据却没有发生变化. <ul> <li v-for="(item,index) in todos" ...
- vue基础篇---修改对象或数组的值,页面实时刷新
这个问题估计大家很难想到,如果一个数组[1,2,3,4],然后我们v-for遍历,我们改变数组的值,arr[1] = 5 ,难道不应该改变么?按理说根据vue的特性应该是改变的,但是事实上确实数组已经 ...
随机推荐
- git学习记录——分支管理和多人协作
在公司里难免会出现多个人一起工作,这就需要构建多个分支派发给多个人去干活 这就产生一个需求,分支管理 分支的创建,合并和删除 其他版本控制系统如SVN等都有分支管理,但是用过之后你会发现,这些版本控制 ...
- WPF 从属性赋值到MVVM模式详解
示例源码 这两天学习了一下MVVM模式,和大家分享一下,也作为自己的学习笔记.这里不定义MVVM的概念,不用苍白的文字说它的好处,而是从简单的赋值讲起,一步步建立一个MVVM模式的Simple.通过前 ...
- shell总结:读取文件、参数、if、分割字符串、数组长度、空文件、变量赋值、多进程、按行切割文件、查看线程
Reference: http://saiyaren.iteye.com/blog/1943207 1. Shell 读取文件和写文件 for line in $(<top30000. ...
- 论ul、ol和dl的区别
1.ul是无序列表,也就是说没有排列限制可以随意加li: <ul> <li>可以随意放置</li> <li>可以随意放置</li> < ...
- Django REST Framework之认证组件
什么是认证 认证即需要知道是谁在访问服务器,需要有一个合法身份.认证的方式可以有很多种,例如session+cookie.token等,这里以token为例.如果请求中没有token,我们认为这是未登 ...
- 基于LSTM对西储大学轴承故障进行分析
这篇文章是小萌新对西储大学轴承故障进行分析,固定特征为故障直径为0.007,电机转速为1797,12k驱动端故障数据(Drive_End)即DE-time.故障类型y值:滚动体故障,内圈故障,3时,6 ...
- python基础--线程、进程
并发编程: 操作系统:(基于单核研究) 多道技术: 1.空间上的复用 多个程序共用一个计算机 2.时间上的复用 切换+保存状态 例如:洗衣 烧水 做饭 切换: 1.程序遇到IO操作系统会立刻剥夺着CP ...
- P1561 [USACO12JAN]爬山Mountain Climbing
P1561 [USACO12JAN]爬山Mountain Climbing 题目描述 Farmer John has discovered that his cows produce higher q ...
- 【python之路16】作业
#!usr/bin/env python # -*- coding:utf-8 -*- # 数据库中原有 old_dict = { "#1": {'hostname': 'c1', ...
- 2018 8.8 提高A组模拟赛
T1 Description 被污染的灰灰草原上有羊和狼.有N只动物围成一圈,每只动物是羊或狼. 该游戏从其中的一只动物开始,报出[1,K]区间的整数,若上一只动物报出的数是x,下一只动物可以报[x+ ...