README.adoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. :spring_version: current
  2. :spring_boot_version: 2.3.2.RELEASE
  3. :jackson: https://wiki.fasterxml.com/JacksonHome
  4. :AtMessageMapping: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/handler/annotation/MessageMapping.html
  5. :AtController: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/stereotype/Controller.html
  6. :AtEnableWebSocketMessageBroker: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/simp/config/EnableWebSocketMessageBroker.html
  7. :Stomp_JS: http://jmesnil.net/stomp-websocket/doc/
  8. :AtSendTo: https://docs.spring.io/spring/docs/{spring_version}/javadoc-api/org/springframework/messaging/handler/annotation/SendTo.html
  9. :toc:
  10. :icons: font
  11. :source-highlighter: prettify
  12. :project_id: gs-messaging-stomp-websocket
  13. This guide walks you through the process of creating a "`Hello, world`" application that
  14. sends messages back and forth between a browser and a server. WebSocket is a thin,
  15. lightweight layer above TCP. This makes it suitable for using "`subprotocols`" to embed
  16. messages. In this guide, we use
  17. http://en.wikipedia.org/wiki/Streaming_Text_Oriented_Messaging_Protocol[STOMP] messaging
  18. with Spring to create an interactive web application.
  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. :java_version: 1.8
  24. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[]
  25. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[]
  26. [[scratch]]
  27. == Starting with Spring Initializr
  28. For all Spring applications, you should start with the https://start.spring.io[Spring
  29. Initializr]. The Initializr offers a fast way to pull in all the dependencies you need for
  30. an application and does a lot of the set up for you. This example needs only the Websocket
  31. dependency.
  32. The following listing shows the `pom.xml` file that is created when you choose Maven:
  33. ====
  34. [src,xml]
  35. ----
  36. include::initial/pom.xml[]
  37. ----
  38. ====
  39. The following listing shows the `build.gradle` file that is created when you choose Gradle:
  40. ====
  41. [src,java]
  42. ----
  43. include::initial/build.gradle[]
  44. ----
  45. ====
  46. == Adding Dependencies
  47. The Spring Initializr does not provide everything you need in this case. For Maven, you
  48. need to add the following dependencies:
  49. ====
  50. [source,xml]
  51. ----
  52. <dependency>
  53. <groupId>org.webjars</groupId>
  54. <artifactId>webjars-locator-core</artifactId>
  55. </dependency>
  56. <dependency>
  57. <groupId>org.webjars</groupId>
  58. <artifactId>sockjs-client</artifactId>
  59. <version>1.0.2</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>org.webjars</groupId>
  63. <artifactId>stomp-websocket</artifactId>
  64. <version>2.3.3</version>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.webjars</groupId>
  68. <artifactId>bootstrap</artifactId>
  69. <version>3.3.7</version>
  70. </dependency>
  71. <dependency>
  72. <groupId>org.webjars</groupId>
  73. <artifactId>jquery</artifactId>
  74. <version>3.1.1-1</version>
  75. </dependency>
  76. ----
  77. ====
  78. The following listing shows the finished `pom.xml` file:
  79. ====
  80. [src,xml]
  81. ----
  82. include::complete/pom.xml[]
  83. ----
  84. ====
  85. If you use Gradle, you need to add the following dependencies:
  86. ====
  87. [source,java]
  88. ----
  89. implementation 'org.webjars:webjars-locator-core'
  90. implementation 'org.webjars:sockjs-client:1.0.2'
  91. implementation 'org.webjars:stomp-websocket:2.3.3'
  92. implementation 'org.webjars:bootstrap:3.3.7'
  93. implementation 'org.webjars:jquery:3.1.1-1'
  94. ----
  95. ====
  96. The following listing shows the finished `build.gradle` file:
  97. ====
  98. [src,java]
  99. ----
  100. include::complete/build.gradle[]
  101. ----
  102. ====
  103. [[initial]]
  104. == Create a Resource Representation Class
  105. Now that you have set up the project and build system, you can create your STOMP message
  106. service.
  107. Begin the process by thinking about service interactions.
  108. The service will accept messages that contain a name in a STOMP message whose body is a
  109. JSON object. If the name is `Fred`, the message might resemble the following:
  110. ====
  111. [source,json]
  112. ----
  113. {
  114. "name": "Fred"
  115. }
  116. ----
  117. ====
  118. To model the message that carries the name, you can create a plain old Java object with a
  119. `name` property and a corresponding `getName()` method, as the following listing (from
  120. `src/main/java/com/example/messagingstompwebsocket/HelloMessage.java`) shows:
  121. ====
  122. [source,java,tabsize=2]
  123. ----
  124. include::complete/src/main/java/com/example/messagingstompwebsocket/HelloMessage.java[]
  125. ----
  126. ====
  127. Upon receiving the message and extracting the name, the service will process it by
  128. creating a greeting and publishing that greeting on a separate queue to which the client
  129. is subscribed. The greeting will also be a JSON object, which as the following listing
  130. shows:
  131. ====
  132. [source,json]
  133. ----
  134. {
  135. "content": "Hello, Fred!"
  136. }
  137. ----
  138. ====
  139. To model the greeting representation, add another plain old Java object with a `content`
  140. property and a corresponding `getContent()` method, as the following listing (from
  141. `src/main/java/com/example/messagingstompwebsocket/Greeting.java`) shows:
  142. ====
  143. [source,java,tabsize=2]
  144. ----
  145. include::complete/src/main/java/com/example/messagingstompwebsocket/Greeting.java[]
  146. ----
  147. ====
  148. Spring will use the {jackson}[Jackson JSON] library to automatically marshal instances of
  149. type `Greeting` into JSON.
  150. Next, you will create a controller to receive the hello message and send a greeting
  151. message.
  152. == Create a Message-handling Controller
  153. In Spring's approach to working with STOMP messaging, STOMP messages can be routed to
  154. {AtController}[`@Controller`] classes. For example, the `GreetingController` (from
  155. `src/main/java/com/example/messagingstompwebsocket/GreetingController.java`) is mapped to
  156. handle messages to the `/hello` destination, as the following listing shows:
  157. ====
  158. [source,java,tabsize=2]
  159. ----
  160. include::complete/src/main/java/com/example/messagingstompwebsocket/GreetingController.java[]
  161. ----
  162. ====
  163. This controller is concise and simple, but plenty is going on. We break it down step by
  164. step.
  165. The {AtMessageMapping}[`@MessageMapping`] annotation ensures that, if a message is sent to
  166. the `/hello` destination, the `greeting()` method is called.
  167. The payload of the message is bound to a `HelloMessage` object, which is passed into
  168. `greeting()`.
  169. Internally, the implementation of the method simulates a processing delay by causing the
  170. thread to sleep for one second. This is to demonstrate that, after the client sends a
  171. message, the server can take as long as it needs to asynchronously process the message.
  172. The client can continue with whatever work it needs to do without waiting for the
  173. response.
  174. After the one-second delay, the `greeting()` method creates a `Greeting` object and
  175. returns it. The return value is broadcast to all subscribers of `/topic/greetings`, as
  176. specified in the {AtSendTo}[`@SendTo`] annotation. Note that the name from the input
  177. message is sanitized, since, in this case, it will be echoed back and re-rendered in the
  178. browser DOM on the client side.
  179. == Configure Spring for STOMP messaging
  180. Now that the essential components of the service are created, you can configure Spring to
  181. enable WebSocket and STOMP messaging.
  182. Create a Java class named `WebSocketConfig` that resembles the following listing (from
  183. `src/main/java/com/example/messagingstompwebsocket/WebSocketConfig.java`):
  184. ====
  185. [source,java,tabsize=2]
  186. ----
  187. include::complete/src/main/java/com/example/messagingstompwebsocket/WebSocketConfig.java[]
  188. ----
  189. ====
  190. `WebSocketConfig` is annotated with `@Configuration` to indicate that it is a Spring
  191. configuration class. It is also annotated with
  192. {AtEnableWebSocketMessageBroker}[`@EnableWebSocketMessageBroker`]. As its name suggests,
  193. `@EnableWebSocketMessageBroker` enables WebSocket message handling, backed by a message
  194. broker.
  195. The `configureMessageBroker()` method implements the default method in
  196. `WebSocketMessageBrokerConfigurer` to configure the message broker. It starts by calling
  197. `enableSimpleBroker()` to enable a simple memory-based message broker to carry the
  198. greeting messages back to the client on destinations prefixed with `/topic`. It also
  199. designates the `/app` prefix for messages that are bound for methods annotated with
  200. `@MessageMapping`. This prefix will be used to define all the message mappings. For
  201. example, `/app/hello` is the endpoint that the `GreetingController.greeting()` method is
  202. mapped to handle.
  203. The `registerStompEndpoints()` method registers the `/gs-guide-websocket` endpoint,
  204. enabling SockJS fallback options so that alternate transports can be used if WebSocket is
  205. not available. The SockJS client will attempt to connect to `/gs-guide-websocket` and use
  206. the best available transport (websocket, xhr-streaming, xhr-polling, and so on).
  207. == Create a Browser Client
  208. With the server-side pieces in place, you can turn your attention to the JavaScript client
  209. that will send messages to and receive messages from the server side.
  210. Create an `index.html` file similar to the following listing (from
  211. `src/main/resources/static/index.html`):
  212. ====
  213. [source,html]
  214. ----
  215. include::complete/src/main/resources/static/index.html[]
  216. ----
  217. ====
  218. This HTML file imports the `SockJS` and `STOMP` javascript libraries that will be used to
  219. communicate with our server through STOMP over websocket. We also import `app.js`, which
  220. contains the logic of our client application. The following listing (from
  221. `src/main/resources/static/app.js`) shows that file:
  222. ====
  223. [source,javascript,tabsize=2]
  224. ----
  225. include::complete/src/main/resources/static/app.js[]
  226. ----
  227. ====
  228. The main pieces of this JavaScript file to understand are the `connect()` and `sendName()`
  229. functions.
  230. The `connect()` function uses https://github.com/sockjs[SockJS] and {Stomp_JS}[stomp.js]
  231. to open a connection to `/gs-guide-websocket`, which is where our SockJS server waits for
  232. connections. Upon a successful connection, the client subscribes to the `/topic/greetings`
  233. destination, where the server will publish greeting messages. When a greeting is received
  234. on that destination, it will append a paragraph element to the DOM to display the greeting
  235. message.
  236. The `sendName()` function retrieves the name entered by the user and uses the STOMP client
  237. to send it to the `/app/hello` destination (where `GreetingController.greeting()` will
  238. receive it).
  239. == Make the Application Executable
  240. Spring Boot creates an application class for you. In this case, it needs no further
  241. modification. You can use it to run this application. The following listing (from
  242. `src/main/java/com/example/messagingstompwebsocket/MessagingStompWebsocketApplication.java`)
  243. shows the application class:
  244. ====
  245. [source,java,tabsize=2]
  246. ----
  247. include::complete/src/main/java/com/example/messagingstompwebsocket/MessagingStompWebsocketApplication.java[]
  248. ----
  249. ====
  250. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/spring-boot-application-new-path.adoc[]
  251. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_subhead.adoc[]
  252. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_with_both.adoc[]
  253. Logging output is displayed. The service should be up and running within a few seconds.
  254. == Test the service
  255. Now that the service is running, point your browser at http://localhost:8080 and click the *Connect* button.
  256. Upon opening a connection, you are asked for your name. Enter your name and click *Send*.
  257. Your name is sent to the server as a JSON message over STOMP. After a one-second simulated
  258. delay, the server sends a message back with a "`Hello`" greeting that is displayed on the
  259. page. At this point, you can send another name or you can click the *Disconnect* button to
  260. close the connection.
  261. == Summary
  262. Congratulations! You have just developed a STOMP-based messaging service with Spring.
  263. == See Also
  264. The following guides may also be helpful:
  265. * https://spring.io/guides/gs/serving-web-content/[Serving Web Content with Spring MVC]
  266. * https://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot]
  267. include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/footer.adoc[]