As James Strachan says - http://activemq.apache.org/ajax.html is an ideal out-of-the-box solution for your problem.
If you still want to create such solution manually you can just create JMS connection in your Ajax servlet (connection per request). Consider using Spring JMS template for that reason ( http://static.springsource.org/spring/docs/2.5.x/reference/jms.html ). Then just receive the message in the Servlet doGet/doPost method. Consider low timeout value for receiving in that case. Such solution will work for the Queues and durable Topics.
For non-durable Topics consider external message listener. Spring MessageListenerContainer
is an excellent tool for that purpose:
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer
<property name="connectionFactory" ref="jmsFactory"/>
<property name="destination" ref="myTopic" />
<property name="messageListener" ref="lastTenUpdatesCache" />
</bean>
Bean lastTenUpdatesCache
will be a singleton bean implementing MesssageListener
. This bean would be responsible for caching last ten messages (just putting it into a java.util list). It will be injected into your Ajax servlet so in your doGet/doPost method you can ask it about last 10 messages sent to the topic.