首页 > 解决方案 > 返回 Flux 时 HttpStatus 406“不可接受”在 Spring 4.3.7 MVC Controller 到 html 页面中的 EventSource

问题描述

我试图通过spring webflux创建一个页面打开多少时间的计时器,我已经在springboot上制作了这个示例,但是spring mvc不起作用,所以我知道代码确实有效。我可以设置一些我不知道的东西吗?

控制器:

@Controller
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(){
        return "home";
    }

    @RequestMapping(value = "/timer", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public @ResponseBody Flux<String> startTimer(){
        Instant startTime = Instant.now();
        return Flux.fromStream(
                Stream.generate(() -> calculateTimeMethod(startTime, Instant.now()))
        ).delayElements(Duration.ofSeconds(1));
    }
}

JSP 主页.jsp:

<html>
<head>
    <title> Home </title>
</head>
<body>
    <label> tiempo trascurrido </label>
    <label id="timer"></label>

    <script>
        var eventSource = new EventSource("url/timer");
        eventSource.onmessage = function ( event ) {
            document.getElementById("timer").innerText = event.data;
        };
    </script>
</body>
</html>

主页加载但计时器未启动,控制台输出显示:加载资源失败:服务器响应状态为 406(不可接受)

标签: springspring-mvcspring-webfluxeventsource

解决方案


推荐阅读