我想使用jsp实现服务器发送事件,但它不起作用, 我的代码如下所示,但它甚至没有显示日期
date.jsp
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
%>
<%
Date date = new Date();
out.write(+date.toString()+);
out.flush();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
%>
我的ex.html代码就像休闲一样
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("date.jsp");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
获取服务器更新
也没有显示日期......
我正在使用tomact服务器,代码中是否有任何问题
答案 0 :(得分:0)
你应该使用像body onLoad或按钮onClick听众那样可运行的东西, 你应该使用正确的jsp或servlet路径(不在WEB-INF文件夹中), 你应该使用正确的事件数据格式,带有“data:”前缀和“\ n \ n”后缀。
ex.html
<!DOCTYPE html>
<html>
<body onLoad = RegisterSSE()>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
function RegisterSSE()
{
alert("wtf");
if(typeof(EventSource) != "undefined")
{
var source = new EventSource ("http://localhost:8080/web_war_exploded/date.jsp");
source.onmessage = function(event)
{
document.getElementById("result").innerHTML += event.data + "<br/>";
};
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
}
</script>
</body>
</html>
date.jsp
<%
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
Date date = new Date();
out.write("event: server-time\n\n");
out.write("data: "+date.toString() + "\n\n");
out.flush();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
%>
毕竟你应该使用谷歌,你的问题并不新鲜,请看下面的链接:
java-servlet-and-server-sent-events