Browse Source

SseEmitter support for multiline String

Closes gh-30965
pull/31284/head
rstoyanchev 1 year ago
parent
commit
2530efd1c7
  1. 3
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java
  2. 10
      spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java

3
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java

@ -237,6 +237,9 @@ public class SseEmitter extends ResponseBodyEmitter { @@ -237,6 +237,9 @@ public class SseEmitter extends ResponseBodyEmitter {
public SseEventBuilder data(Object object, @Nullable MediaType mediaType) {
append("data:");
saveAppendedText();
if (object instanceof String text) {
object = StringUtils.replace(text, "\n", "\ndata:");
}
this.dataToSend.add(new DataWithMediaType(object, mediaType));
append('\n');
return this;

10
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java

@ -104,6 +104,16 @@ public class SseEmitterTests { @@ -104,6 +104,16 @@ public class SseEmitterTests {
this.handler.assertWriteCount(1);
}
@Test
public void sendEventWithMultiline() throws Exception {
this.emitter.send(event().data("foo\nbar\nbaz"));
this.handler.assertSentObjectCount(3);
this.handler.assertObject(0, "data:", TEXT_PLAIN_UTF8);
this.handler.assertObject(1, "foo\ndata:bar\ndata:baz");
this.handler.assertObject(2, "\n\n", TEXT_PLAIN_UTF8);
this.handler.assertWriteCount(1);
}
@Test
public void sendEventFull() throws Exception {
this.emitter.send(event().comment("blah").name("test").reconnectTime(5000L).id("1").data("foo"));

Loading…
Cancel
Save