2017-01-23 89 views
0

我一直在研究Spring WebSocket example。我想创建这样一个应用程序,它将从db < - > server < - > client交换信息。我创建了我自己的bean,它将查询数据库,在这种情况下它是AnimalBean。这是应用程序的控制器:Spring WebSocket从服务器发送多个pair-value消息

@Controller 
public class GreetingController { 

    @MessageMapping("/hello") 
    @SendTo("/topic/greetings") 
    public Greeting greeting(HelloMessage message, AnimalBean ab) throws Exception { 
     return new Greeting(ab.getCows() + "\t" + new Date() + "\t" + message.getName()); 
    } 

} 

因为我想给动物的不同计数像ab.getCows()ab.getRabbits()等方式向客户我想知道是否有可能在一个JSON消息发送这样的例子消息是这样的:

{"cows":"4", "rabbits":"60"}

C和它来实现的,什么是做到这一点的最简单的方法?

回答

1

假设动物豆是你的豆豆。更新的类看起来像。

@Controller 
public class GreetingController { 

    @Autowired 
    private AnimalBean ab; 

    @MessageMapping("/hello") 
    @SendTo("/topic/greetings") 
    public AnimalInfogreeting(HelloMessage message) throws Exception { 
     return new AnimalInfo(ab.getCows(), ab.getRabbits()); 
    } 

} 

创建POJO类。

public class AnimalInfo{ 
    private int cows; 
    pirvate int rabbits; 

    public AnimalInfo(int cows, int rabbits){ 
     this.cows= cows; 
     this.rabbits =rabbits; 
    } 

    //getters and setters 
} 
相关问题