映射控制器时如何使用Spring4发送STOMP消息

时间:2014-06-30 18:12:51

标签: spring-4 spring-websocket

我有以下代码......

@Controller
@RequestMapping("/stomp/**")
public class StompController {
    @MessageMapping("/hello")
    @SendTo("/topic/greet")
    public Greeting greet(HelloMessage message) throws Exception{
        System.out.println("Inside the method "+message.getName());
        Thread.sleep(3000);
        return new Greeting("Hello, "+message.getName()+"!");
    }
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/stomp/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp/hello").withSockJS();
    }
}

<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        document.getElementById('response').innerHTML = '';
    }

    function connect() {
        var socket = new SockJS('/stomp/hello');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/stomp/topic/greet', function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

    function disconnect() {
        stompClient.disconnect();
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("/stomp/app/hello", {}, JSON.stringify({ 'name': name }));
    }

    function showGreeting(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }
</script>

客户端代码似乎连接正常但我没有看到控制台消息对我有意义&#34; / stomp / app / hello&#34;是错误的道路。正确的道路应该是什么?

我也试过/ app / stomp / hello没有骰子......

更新

我可以删除@RequestMapping("/stomp/**")并移除与stomp相关的东西,它适用于我的简单测试,但是,我需要它来处理一个不允许这样的更复杂的应用程序。

1 个答案:

答案 0 :(得分:1)

@RequestMapping@MessageMapping注释可以以类似的方式使用,但完全不同。 @MessageMapping也可以在类型级别(see reference documentation)使用,因此您可以使用@MessageMapping("/stomp/**")为控制器添加注释。

没有什么能阻止您使用@MessageMapping@RequestMapping注释控制器 - 类似的编程模型,不同的用途。