CAPITAL WILL BE DISPLAYED HERE
Add the SockJS support by adding sockjs-0.3.4.js in your resources or adding the following code: On form submission a method of JavaScript gets invoked, where we handle the WebSocket events onopen, onmessage etc as discussed earlier: var stompClient = null; function setConnected(connected) { document.getElementById('show').disabled = connected; } function connect() { if (window.WebSocket) { message = "supported"; console.log("BROWSER SUPPORTED"); } else { console.log("BROWSER NOT SUPPORTED"); } var country = document.getElementById('country').value; var socket = new WebSocket( "ws://localhost:8081/Ch10_Spring_Message_Handler /webS/myHandler"); socket.onmessage=function(data){ showResult("Message Arrived"+data.data) }; setConnected(true); socket.onopen = function(e) { console.log("Connection established!"); socket.send(country); console.log("sending data"); }; } function disconnect() { if (socket != null) { socket.close(); } setConnected(false); console.log("Disconnected"); } function showResult(message) { var response = document.getElementById('messageDiv'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.appendChild(document.createTextNode(message)); response.appendChild(p); } We already discussed about how to write the WebSocket URLs and event handling mechanism Deploy the application and access the page Select the country from dropdown and click on show capital button The message will appear displaying the name of the capital The following diagram shows the flow of the application: We had added the Console logs as well as the Alert messages to know the progress and to and fro of the messages As per requirement you can customize it or can completely omit as well In the earlier example, we have used WebSocket for communication but still its support is limited The SockJS is a JavaScript library which provides the objects like WebSocket SockJS The SockJS library provides cross browser, JavaScript API to enable low latency, cross domain communication between the browser and server It aims to support the following goals: Instead of using WebSocket instance, the SockJS instance is used The API which are close to WebSocket API both for server as well as client side APIs Faster communication support JavaScript for client side It comes with some chosen protocols which supports cross domain communication The following code shows how to enable in the SockJS support for WebSocketConfigurere as: @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler_sockjs").setAllowedOrigins("*").withSockJS(); } Or even we can configure in XML as: We can update the Capital demo developed earlier to support SockJS as follows: Add country_sockjs.jsp in WebContent to use with SockJS as follows: var socket = new SockJS( "http://localhost:8080/Ch10_Spring_Message_Handler /webS/myHandler_sockjs"); Add MyWebSocketConfigurer_sockjs in com.packt.ch10.config package to configure the WebSocket as we did earlier To enable the SockJS support we have to modify the registerWebSocketHandlers() method as shown in the configuration above using withSockJS() Run the application and request for country_sockjs.jsp to use the SockJS You can observe the console logs as well In the above example, we had use WebSocket to get the connection and handle the events The new WebSocket protocol also has been introduced for the communication which we used here It uses less bandwidth It has no headers like HTTP gives simpler, efficient communication We can also use STOMP for the communication STOMP Simple (or Streaming) Text Oriented Message Protocol (STOMP) over WebSocket provides a straightforward mapping from a STOMP frame to a JavaScript object WebSocket is fastest protocol but, still it is not supported by all browsers The browsers have problems to support proxies and protocol handling It will take a while to get wide support by all the browsers, meanwhile we need to find some substitute or real time solution The SockJS supports STOMP protocol for communicating with any message broker from the scripting languages and is an alternative to AMQP STOMP is lightweight and easy to implement both on client as well as server side It comes with reliable sending single message and then disconnect or consume all messages from the destination It defines following different frames that are mapped to WebSocket frames: CONNECT: It connects the client to the server SUBSCRIBE: It is used to register which can listen to the given destination UNSUBSCRIBE: It is used to remove existing subscription SEND (messages sent to the server): The frame sends a message to the destination MESSAGE (for messages send from the server): It conveys the messages from the subscriptions to the client BEGIN: It starts the transaction COMMIT: It commits the ongoing transaction ABORT: It rollbacks the ongoing transaction DISCONNECT: It disconnects the client from the server It also supports the following standard headers: content-length: The SEND, MESSAGE and ERROR frames contain content-length header having its value as content length of the message body content-type: The SEND, MESSAGE and ERROR frames contain content-type It is similar to MIME type in web technology receipt: The CONNECT frame may contain receipt as header attribute to acknowledge the server of the RECEIPT frame heart-beat: It got added by the CONNECT and CONNECTED frames It contains two positive integer values separated by the comma 1st value represents outgoing heart beats '0' specifies it cannot send heart beats 2nd value denotes incoming heart beats '0' denotes unwillingness to receive the heart beats Spring STOMP support The Spring WebSocket application works as a STOMP broker to all the clients Each message will be routed through the Spring controllers These controllers are capable of handling HTTP request and response by @RequestMapping annotation Similarly they are capable of handling WebSocket Messages in all those methods who are annotated by @Messaging Spring also facilitates integration of RabbitMQ, ActiveMQ as the STOMP brokers for the message broad casting Let' us develop an application to use STOMP step by step: Create Ch10_Spring_Messaging_STOMP as a dynamic web application and add the jars which we added earlier Add mapping for DispatcherServlet in web.xml having books as name and 'webS' as URL pattern Add books-servlet.xml to register bean for 'viewResolver' Registration to discover the controllers and to consider all MVC annotations Add WebSocketConfig_custom as a class in com.packt.ch10.config package to add the '/book' as endpoint enabled for SockJS '/topic' as SimpleBroker for '/bookApp' as prefix The code is as shown below: @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig_custom extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker( MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/bookApp"); } @Override public void registerStompEndpoints( StompEndpointRegistry registry) { registry.addEndpoint("/book").withSockJS(); } } The @EnableWebSocketMessageBroker enables the class to act as a message broker Add POJO MyBook with bookName as data member in com.packt.ch10.model package Similarly add Result having result as data member as POJO having getOffer method as: public void getOffer(String bookName) { if (bookName.equals("Spring 5.0")) { result = bookName + " is having offer of having 20% off"; } else if (bookName.equals("Core JAVA")) { result = bookName + " Buy two books and get 10% off"; } else if (bookName.equals("Spring 4.0")) { result = bookName + " is having for 1000 till month end"; } else result = bookName + " is not available on the list"; } Add index.html to have the link for the 'bookPage' from the controller as follows: CLICK to get BOOK Page Add WebSocketController class in com.packt.ch10.controller package and annotate it by @Controller("webs") Add bookPage() method annotated by @RequestMapping to send bookPage.jsp to the client as shown below: @Controller("/webS") public class WebSocketController { @RequestMapping("/bookPage") public String bookPage() { System.out.println("hello"); return "book"; } 10 Add bookPage.jsp in the jsps folder The page will display book names to get offers associated with them The code will be as follows: Connect Disconnect SELECT BOOK NAME Core JAVA Spring 5.0 Spring 4.0 Send to 11 We will be handling the call back methods, once the client click the button Add the scripts for sockjs and STOMP as: src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/ stomp.js"/> 12 Now we will add connect, disconnect, send, subscribe one by one Let' us first add connect method to get the STOMP connection as follows: var stompClient = null;