页面代码:
<!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代码:
@RequestMapping("getDate.json") public void getDate(HttpServletResponse response){ Date date = new Date(); OutputStream bos = null; try { String result = "data:"+date.getTime()+"\n\n"; bos = new BufferedOutputStream(response.getOutputStream()); response.setContentType("text/event-stream"); response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding(Charset.forName("UTF-8").name()); response.addHeader("Connection", "close"); bos.write(result.getBytes()); bos.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-10-04 23:35:19