是否可以在@OnMessage 函数中使用 POJO 而不是字符串?

问题描述

基本上,我可以使用:

@OnMessage
public void handleMessage(Message message,Session session) {

代替:

@OnMessage
public void handleMessage(String message,Session session) {

消息类看起来像:

public class Message {
    private String action;
    private String value;
}

解决方法

按照文档,这是不可能的:

允许的参数是:

Exactly one of any of the following choices
    if the method is handling text messages:
        String to receive the whole message
        Java primitive or class equivalent to receive the whole message converted to that type
        String and boolean pair to receive the message in parts
        Reader to receive the whole message as a blocking stream
        any object parameter for which the endpoint has a text decoder (Decoder.Text or Decoder.TextStream).
    if the method is handling binary messages:
        byte[] or ByteBuffer to receive the whole message
        byte[] and boolean pair,or ByteBuffer and boolean pair to receive the message in parts
        InputStream to receive the whole message as a blocking stream
        any object parameter for which the endpoint has a binary decoder (Decoder.Binary or Decoder.BinaryStream).
    if the method is handling pong messages:
        PongMessage for handling pong messages
and Zero to n String or Java primitive parameters annotated with the PathParam annotation for server endpoints.
and an optional Session parameter

https://docs.oracle.com/javaee/7/api/javax/websocket/OnMessage.html

但是如果您使用 JAXRS(带有 RESTEasy、Jersey 或 CXF),您将能够使用 Json Provider(Jackson、Gson)直接在目标对象中进行解析。