Java代码:
@ResponseBody
@RequestMapping(value = "/getDate", produces="text/event-stream;charset=UTF-8")
public void getDate(HttpServletResponse response) throws Exception {
log.info("getDate event start");
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
while(!response.getWriter().checkError()){
response.getWriter().write("data:"+new Date()+"
");
response.getWriter().flush();
Thread.sleep(1000);
}
response.getWriter().close();
log.info("getDate event end");
}
前端代码(jsp):
<%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<title>日期</title>
</head>
<body>
<div id='date'>
</div>
<script>
if (typeof(EventSource) !== "undefined") {
var eventSource = new EventSource("/Output/getDate");
eventSource.onmessage = function (event) {
document.getElementById("date").innerHTML = event.data;
}
eventSource.addEventListener('error', function (event) {
console.log("错误:" + event);
});
eventSource.addEventListener('open', function (event) {
console.log("建立连接:" + event);
});
}
else {
document.getElementById("date").innerHTML = "抱歉,您的浏览器不支持 server-sent 事件 ...";
}
</script>
</body>
</html>