頁面代碼:html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML 5 服務器發送事件</title> </head> <body> <h1>得到服務器更新</h1> <div id="result"></div> <script> if(typeof(EventSource)!=="undefined") { var source=new EventSource("/test/getDate.json"); source.onopen = function(){ } 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>
後臺java代碼:java
@RequestMapping("getDate.json") public void getDate(HttpServletResponse response,HttpServletRequest request){ Date date = new Date(); OutputStream bos = null; try { String result = "data:"+111+"\n\n"; String result2 = "data:"+222+"\n\n"; //聲明瀏覽器在鏈接斷開以後進行再次鏈接以前的等待時間 10秒 String retry = "retry:"+10000+"\n\n"; //事件的標識符 String id="id:100\n\n"; //最後一次接收到的事件的標識符 String last = request.getHeader("Last-Event-ID"); logger.info(last); bos = new BufferedOutputStream(response.getOutputStream()); response.setContentType("text/event-stream"); bos.write(result.getBytes()); bos.write(result2.getBytes()); bos.write(retry.getBytes()); bos.write(id.getBytes()); bos.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } }