2017-01-23 61 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 
}