以下是实现JAVA后台向HTML页面推送消息的简单实现。
后台代码(将方法放在Controller中):
前台代码:
后台代码(将方法放在Controller中):
public String getPushMessage(){
String message="msg";
getResponse().setContentType("text/event-stream;charset=UTF-8");
getResponse().setCharacterEncoding("UTF-8");
try {
PrintWriter writer=getResponse().getWriter();
writer.write("data: "+message+"\n\n");//一定要用\n\n结尾哦
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
前台代码:
$(function(){
if(window.Notification){
if(window.Notification.permission != "granted"){
window.Notification.requestPermission();
}
}
else{
alert('你的浏览器不支持此消息提示功能,请使用chrome内核的浏览器!');
}
var eventSource=new EventSource("getPushMessage");
eventSource.onmessage=function(event){
var message=event.data;
alert(message);
//以下代码的功能是使消息能够在windows桌面弹出(HTML页面最小化了也没关系)
var notification = new Notification("title", {
body: message,
icon: 'img/title.jpg',
requireInteraction:true//表示需要和用户交互,即:用户点击关闭弹窗才会消失
});
}
});