README.adoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. :spring_version: current
  2. :jackson: https://wiki.fasterxml.com/JacksonHome
  3. :AtMessageMapping: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/handler/annotation/MessageMapping.html
  4. :AtController: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/stereotype/Controller.html
  5. :AtEnableWebSocketMessageBroker: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/simp/config/EnableWebSocketMessageBroker.html
  6. :Stomp_JS: http://jmesnil.net/stomp-websocket/doc/
  7. :AtSendTo: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/handler/annotation/SendTo.html
  8. :toc:
  9. :icons: font
  10. :source-highlighter: prettify
  11. :project_id: gs-messaging-stomp-websocket
  12. This guide walks you through the process of creating a "`Hello, world`" application that
  13. sends messages back and forth between a browser and a server. WebSocket is a thin,
  14. lightweight layer above TCP. This makes it suitable for using "`subprotocols`" to embed
  15. messages. In this guide, we use
  16. http://en.wikipedia.org/wiki/Streaming_Text_Oriented_Messaging_Protocol[STOMP] messaging
  17. with Spring to create an interactive web application. STOMP is a subprotocol operating
  18. on top of the lower-level WebSocket.
  19. == What You Will build
  20. You will build a server that accepts a message that carries a user's name. In response,
  21. the server will push a greeting into a queue to which the client is subscribed.
  22. == What You Need
  23. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/prereq_editor_jdk_buildtools.adoc[]
  24. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/how_to_complete_this_guide.adoc[]
  25. [[scratch]]
  26. == Starting with Spring Initializr
  27. You can use this https://start.spring.io/#!type=maven-project&groupId=com.example&artifactId=messaging-stomp-websocket&name=messaging-stomp-websocket&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.messaging-stomp-websocket&dependencies=websocket[pre-initialized project] and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
  28. To manually initialize the project:
  29. . Navigate to https://start.spring.io.
  30. This service pulls in all the dependencies you need for an application and does most of the setup for you.
  31. . Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
  32. . Click *Dependencies* and select *Websocket*.
  33. . Click *Generate*.
  34. . Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
  35. NOTE: If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
  36. NOTE: You can also fork the project from Github and open it in your IDE or other editor.
  37. ===
  38. [[initial]]
  39. == Create a Resource Representation Class
  40. Now that you have set up the project and build system, you can create your STOMP message
  41. service.
  42. Begin the process by thinking about service interactions.
  43. The service will accept messages that contain a name in a STOMP message whose body is a
  44. JSON object. If the name is `Fred`, the message might resemble the following:
  45. ====
  46. [source,json]
  47. ----
  48. {
  49. "name": "Fred"
  50. }
  51. ----
  52. ====
  53. To model the message that carries the name, you can create a plain old Java object with a
  54. `name` property and a corresponding `getName()` method, as the following listing (from
  55. `src/main/java/com/example/messagingstompwebsocket/HelloMessage.java`) shows:
  56. ====
  57. [source,java,tabsize=2]
  58. ----
  59. include::complete/src/main/java/com/example/messagingstompwebsocket/HelloMessage.java[]
  60. ----
  61. ====
  62. Upon receiving the message and extracting the name, the service will process it by
  63. creating a greeting and publishing that greeting on a separate queue to which the client
  64. is subscribed. The greeting will also be a JSON object, which as the following listing
  65. shows:
  66. ====
  67. [source,json]
  68. ----
  69. {
  70. "content": "Hello, Fred!"
  71. }
  72. ----
  73. ====
  74. To model the greeting representation, add another plain old Java object with a `content`
  75. property and a corresponding `getContent()` method, as the following listing (from
  76. `src/main/java/com/example/messagingstompwebsocket/Greeting.java`) shows:
  77. ====
  78. [source,java,tabsize=2]
  79. ----
  80. include::complete/src/main/java/com/example/messagingstompwebsocket/Greeting.java[]
  81. ----
  82. ====
  83. Spring will use the {jackson}[Jackson JSON] library to automatically marshal instances of
  84. type `Greeting` into JSON.
  85. Next, you will create a controller to receive the hello message and send a greeting
  86. message.
  87. == Create a Message-handling Controller
  88. In Spring's approach to working with STOMP messaging, STOMP messages can be routed to
  89. {AtController}[`@Controller`] classes. For example, the `GreetingController` (from
  90. `src/main/java/com/example/messagingstompwebsocket/GreetingController.java`) is mapped to
  91. handle messages to the `/hello` destination, as the following listing shows:
  92. ====
  93. [source,java,tabsize=2]
  94. ----
  95. include::complete/src/main/java/com/example/messagingstompwebsocket/GreetingController.java[]
  96. ----
  97. ====
  98. This controller is concise and simple, but plenty is going on. We break it down step by
  99. step.
  100. The {AtMessageMapping}[`@MessageMapping`] annotation ensures that, if a message is sent to
  101. the `/hello` destination, the `greeting()` method is called.
  102. The payload of the message is bound to a `HelloMessage` object, which is passed into
  103. `greeting()`.
  104. Internally, the implementation of the method simulates a processing delay by causing the
  105. thread to sleep for one second. This is to demonstrate that, after the client sends a
  106. message, the server can take as long as it needs to asynchronously process the message.
  107. The client can continue with whatever work it needs to do without waiting for the
  108. response.
  109. After the one-second delay, the `greeting()` method creates a `Greeting` object and
  110. returns it. The return value is broadcast to all subscribers of `/topic/greetings`, as
  111. specified in the {AtSendTo}[`@SendTo`] annotation. Note that the name from the input
  112. message is sanitized, since, in this case, it will be echoed back and re-rendered in the
  113. browser DOM on the client side.
  114. == Configure Spring for STOMP messaging
  115. Now that the essential components of the service are created, you can configure Spring to
  116. enable WebSocket and STOMP messaging.
  117. Create a Java class named `WebSocketConfig` that resembles the following listing (from
  118. `src/main/java/com/example/messagingstompwebsocket/WebSocketConfig.java`):
  119. ====
  120. [source,java,tabsize=2]
  121. ----
  122. include::complete/src/main/java/com/example/messagingstompwebsocket/WebSocketConfig.java[]
  123. ----
  124. ====
  125. `WebSocketConfig` is annotated with `@Configuration` to indicate that it is a Spring
  126. configuration class. It is also annotated with
  127. {AtEnableWebSocketMessageBroker}[`@EnableWebSocketMessageBroker`]. As its name suggests,
  128. `@EnableWebSocketMessageBroker` enables WebSocket message handling, backed by a message
  129. broker.
  130. The `configureMessageBroker()` method implements the default method in
  131. `WebSocketMessageBrokerConfigurer` to configure the message broker. It starts by calling
  132. `enableSimpleBroker()` to enable a simple memory-based message broker to carry the
  133. greeting messages back to the client on destinations prefixed with `/topic`. It also
  134. designates the `/app` prefix for messages that are bound for methods annotated with
  135. `@MessageMapping`. This prefix will be used to define all the message mappings. For
  136. example, `/app/hello` is the endpoint that the `GreetingController.greeting()` method is
  137. mapped to handle.
  138. The `registerStompEndpoints()` method registers the `/gs-guide-websocket` endpoint for websocket connections.
  139. == Create a Browser Client
  140. With the server-side pieces in place, you can turn your attention to the JavaScript client
  141. that will send messages to and receive messages from the server side.
  142. Create an `index.html` file similar to the following listing (from
  143. `src/main/resources/static/index.html`):
  144. ====
  145. [source,html]
  146. ----
  147. include::complete/src/main/resources/static/index.html[]
  148. ----
  149. ====
  150. This HTML file imports the https://stomp-js.github.io/[`StompJS`] javascript library that will be used to
  151. communicate with our server through STOMP over websocket. We also import `app.js`, which
  152. contains the logic of our client application. The following listing (from
  153. `src/main/resources/static/app.js`) shows that file:
  154. ====
  155. [source,javascript,tabsize=2]
  156. ----
  157. include::complete/src/main/resources/static/app.js[]
  158. ----
  159. ====
  160. The main pieces of this JavaScript file to understand are the `stompClient.onConnect` and `sendName`
  161. functions.
  162. `stompClient` is initialized with `brokerURL` referring to path `/gs-guide-websocket`,
  163. which is where our websockets server waits for
  164. connections. Upon a successful connection, the client subscribes to the `/topic/greetings`
  165. destination, where the server will publish greeting messages. When a greeting is received
  166. on that destination, it will append a paragraph element to the DOM to display the greeting
  167. message.
  168. The `sendName()` function retrieves the name entered by the user and uses the STOMP client
  169. to send it to the `/app/hello` destination (where `GreetingController.greeting()` will
  170. receive it).
  171. The `main.css` can be omitted if you like, or you can create an empty
  172. one, just so the `<link>` can be resolved.
  173. == Make the Application Executable
  174. Spring Boot creates an application class for you. In this case, it needs no further
  175. modification. You can use it to run this application. The following listing (from
  176. `src/main/java/com/example/messagingstompwebsocket/MessagingStompWebsocketApplication.java`)
  177. shows the application class:
  178. ====
  179. [source,java,tabsize=2]
  180. ----
  181. include::complete/src/main/java/com/example/messagingstompwebsocket/MessagingStompWebsocketApplication.java[]
  182. ----
  183. ====
  184. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/spring-boot-application-new-path.adoc[]
  185. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/build_an_executable_jar_subhead.adoc[]
  186. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/build_an_executable_jar_with_both.adoc[]
  187. Logging output is displayed. The service should be up and running within a few seconds.
  188. == Test the service
  189. Now that the service is running, point your browser at http://localhost:8080 and click the *Connect* button.
  190. Upon opening a connection, you are asked for your name. Enter your name and click *Send*.
  191. Your name is sent to the server as a JSON message over STOMP. After a one-second simulated
  192. delay, the server sends a message back with a "`Hello`" greeting that is displayed on the
  193. page. At this point, you can send another name or you can click the *Disconnect* button to
  194. close the connection.
  195. == Summary
  196. Congratulations! You have just developed a STOMP-based messaging service with Spring.
  197. == See Also
  198. The following guides may also be helpful:
  199. * https://stomp-js.github.io/[StompJS client library docs]
  200. * https://spring.io/guides/gs/serving-web-content/[Serving Web Content with Spring MVC]
  201. * https://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot]
  202. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/footer.adoc[]