SSE服务器推送事件

如果你还不知道怎么用Maven搭建SpringMVC项目,请点此这里查看

1. 新建一个演示控制器,代码如下

/**
 * 
 */
package com.zhazhapan.spring.springtest;

import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author pantao
 *
 */
@Controller
public class SseController {

    @RequestMapping(value = "/push", produces = "text/event-stream")
    public @ResponseBody String push() {
        Random random = new Random();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "data:Testing " + random.nextInt() + "\n\n";
    }
}

2. 添加jquery.js到src/main/resources/assets/js目录下(没有的话可以新建),下载jQuery-3.2.1

3. 在src/main/resources/views目录下新建演示页面sse.jsp,内容如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SSE Demotitle>
head>
<body>
    <div id="msgFromPush">div>
    <script type="text/javascript" src="assets/js/jquery-3.2.1.js">script>
    <script type="text/javascript" type="text/javascript">
        //只有新式的浏览器才有,EventSource是SSE的客户端
        if (!!window.EventSource) {
            var source = new EventSource('push');
            s = '';
            //添加SSE监听,获得服务器推送的消息
            source.addEventListener('message', function(e) {
                s += e.data + "
"
; $('#msgFromPush').html(s); }); source.addEventListener('open', function(e) { console.log("连接打开"); }); source.addEventListener('error', function(e) { if (e.readyState == EventSource.CLOSED) { console.log('连接关闭'); } else { console.log(e.readyState); } }) } else { console.log('你的浏览器不支持SSE'); }
script> body> html>

4. 添加路径映射

//这是一个继承自WebMvcConfigurerAdapter的配置类
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //对外暴露访问路径
    registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/sse").setViewName("/sse");
}

5. 运行效果

SSE服务器推送事件_第1张图片

你可能感兴趣的:(Java,spring,springmvc)