In case you haven’t heard what Websocket is, long story short it’s a brand new cool technique of asynchronous client-server communication for web application. Instead of periodic / long ajax polling, newer browsers allow you to have a persistent socket (almost like TCP) where both client and server can send messages anytime.
Yes the all-new Spring 4 came with shiny Websocket support! Here’s a stock ticker app to get you started (thanks toraymondhlee’s article for the inspiration). This app will let you add/remove a stock code and update its price every second (by randomly adding / subtracting some percentage)
Environment / Tools
- Java 7
- Tomcat 7.0.47
- Servlet API 3
- Spring Framework 4.0.2.RELEASE
- SockJS 0.3
- StompJS
Maven Dependencies
Most dependencies are similar to Spring MVC but there’s few addition required to support websocket. You also need to use Servlet 3.
web.xml
You need to use version 3 of the web.xml schema, and on DispatcherServlet config, set<async-supported>true</async-supported>. Here’ssrc/main/webapp/WEB-INF/web.xml
Setup Websocket Message Broker On Servlet Context XML
Apart from the standard Spring MVC config, one new stuff we’re introducing is theWebsocket Message Broker. The message broker will help us listening, mapping and sending messages. Note that as suggested by Spring docs we’re using STOMP message protocol and SockJS to support non-websocket browser.
Also note following configs:
- Stomp endpoint: /ws
- Message broker app prefix: /app
- Message queue prefix: /topic
Here’s src/main/webapp/WEB-INF/servlet-context.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:resourcesmapping="/resources/**"location="/resources/"/>
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/WEB-INF/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<context:component-scanbase-package="com.gerrydevstory.stockticker"/>
<websocket:message-brokerapplication-destination-prefix="/app">
<websocket:stomp-endpointpath="/ws">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-brokerprefix="/topic"/>
</websocket:message-broker>
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:resourcesmapping="/resources/**"location="/resources/"/>
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/WEB-INF/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<context:component-scanbase-package="com.gerrydevstory.stockticker"/>
<websocket:message-brokerapplication-destination-prefix="/app">
<websocket:stomp-endpointpath="/ws">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-brokerprefix="/topic"/>
</websocket:message-broker>
The Domain Object
Stock class is a simple POJO with code, price and time fields. I’ve also addedgetTimeStr() to format the time as string and additional constructor.
Broadcast Prices And Add / Remove Stock
At the core of this app is the HomeController class. There’s aupdatePriceAndBroadcast() method which is scheduler to run every 1 second usingTaskScheduler. This controller also has websocket handler method to add new stock and remove all. Note the usage of@MessageMapping annotation, it will make more sense once we go through the javascript part below.
Client Side Stuff
To render the stock prices, I created an empty HTML table. The idea is we will empty the table and fill it in with new prices per update
Underneath that, I’ll also add few form input so you can add a new stock and remove everything
<pclass="new">
Code: <inputtype="text"class="code"/>
Price: <inputtype="text"class="price"/>
<buttonclass="add">Add</button>
<buttonclass="remove-all">Remove All</button>
</p>
The javascript stuff is a bit complicated. Apart from JQuery, there are 2 libraries used here: StompJS and SockJS. As opposed of using direct API, SockJS provides fallback for older browser not supporting websocket. StompJS provides higher level abstraction of sending and receiving messages in STOMP protocol.
StompJS did not come with CDN, so I had to manually download it and place it onsrc/main/webapp/resources/stomp.js
Next is the inline script block. Here I used SockJS to connect to the Spring websocket STOMP endpoint/ws (recall servlet-context.xml above). My webapp context path is/stockticker.
The connectCallback function above registers renderPrice callback when a message is sent to/topic/price. This function empties the result HTML table and re-add the cells with new stock price
And lastly, utilising JQuery let’s create handlers for adding and removig stocks
Download And Try The Source Code
The source code of this demo app is available on github. Clone it using git:
1
|
git clone https://github.com/gerrytan/stockticker.git
|
Import it as Existing Maven Project in STS (File > Import > Existing Maven Project) and run on in-memoryTomcat 7.0.47 using following Run Configuration (Run > Run Configurations…):
And this Tomcat container has to run on Java 7 to enable Websocket support.