Is there a way to create a dynamic @ServerEndpoint address in Java?

For example, I have a room

public class Room {
   private int id;
   private Set<User> users;
}

So, I want this to be the endpoint for my websocket application. But there can be many rooms, and I want each of them to have its own URI (for example, numbers / 1, numbers / 2, etc.).

Obviously, the @ServerEnpoint annotation allows only constants. So is there a way to do this?

+4
source share
2 answers

Something like that:

@ServerEndpoint(value = "/rooms/{roomnumber}")
public class....

static Map<String, Session> openSessions = ...
@OnOpen
public void onConnectionOpen(final Session session, @PathParam("roomnumber") final String roomnumber, 
...
   //store roomnumber in session
   session.getUserProperties().put("roomnumber", roomnumber);
   openSessions.put( String.valueOf(session.getId()), session ) 

To send messages only to specific numbers / customers:

// check if session corresponds to the roomnumber 
  for (Map.Entry<String, Session> entry : openSessions.entrySet()) {

    Session s = entry.getValue();
    if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(roomnumber_you_want_to_address)) {
  ... 

And when the client disconnects:

 @OnClose
public void onConnectionClose(Session session) {
    openSessions.remove(session.getId());
}
+3
source

@RequestMapping(value = "/endpoint/{endpointVariable}", method = RequestMethod.GET)
public ReturnDTO getReturnDTO(<params>){
    // Here the variable, endpointVariable, will be accessible
    // In my experiences its always been an integer, but I'm sure a string
    // would be possible.  check with debugger
}

http://www.journaldev.com/3358/spring-mvc-requestmapping-annotation-example-with-controller-methods-headers-params-requestparam-pathvariable

-2

Source: https://habr.com/ru/post/1615582/