spring websocket stomp如何向服务端传递参数

本文详细介绍了HTML页面通过STOMP给服务端传递参数的两种方式:在消息头中添加参数和在路径中添加参数。同时,提供了对应Java代码接收参数的方法,包括使用@Header或@DestinationVariable注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前的这篇文章,html页面和java代码是写死的只能向greetings这个主题发送信息,很显然有很大的局限性,现在我们看下如何传递参数。html页面中通过stomp给服务端传递参数有2种方式:在消息头中添加参数,在路径中添加参数。


方式1:在消息头中添加参数

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


对应的java代码可以通过如下方式来接收参数:使用@Header或者@Headers

@Controller
public class ChatController {

	@Autowired
	private SimpMessagingTemplate template;

	@MessageMapping("/hello")
	public String send(String message, @Header("atytopic") String topic,
			@Headers Map<String, Object> headers) {

		System.out.println("message==" + message);
		System.out.println("topic==" + topic);
		System.out.println("headers==" + headers);

		template.convertAndSend("/topic/" + topic, message);

		return "";
	}

}


方式2:在路径中添加参数,这个类似于rest服务在url中写参数。

function sendName() {
            var name = document.getElementById('name').value;
            stompClient.send("/app/hello/aty/greetings", {}, name);
        }


后台java代码如下:使用@DestinationVariable接收

@Controller
public class Chat2Controller {

	@Autowired
	private SimpMessagingTemplate template;

	// 如果只有一个模板变量,那么可以直接使用@DestinationVariable
	@MessageMapping("/hello/{userName}/{topic}")
	public String send(String message, @DestinationVariable("topic") String topic, @DestinationVariable(value="userName") String userName) {

		System.out.println("message=="+message);
		System.out.println("topic=="+topic);
		System.out.println("userName=="+userName);
		
		template.convertAndSend("/topic/"+topic, message);

		return "";
	}

	
}


可以看到这2种方式都可以正确传递参数到服务端。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值