在Java ee websocket中存储字段

时间:2015-06-11 13:05:22

标签: java-ee websocket java-ee-7

我使用PathParam创建了一个javaee websocket端点。参数和会话分别存储在@OnOpen字段中。

websocket侦听某些事件并将一些数据发送到会话(使用path参数)。

问题是在捕获事件时两个字段都为空。这是什么原因?每个会话有多个端点实例吗?我读了spec:“如果开发人员使用默认的ServerEndpointConfig.Configurator,每个活动客户端连接就会有一个端点实例。” 以下是示例代码:

@ServerEndpoint(value = "/allbookings/{projectId}", encoders = {JSONEncoder.class},
                configurator = WebSocketUserConfig.class)
public class BookingsByProject {

    private Session session;
    private String  projectId;

    @OnOpen
    public void open(Session session, EndpointConfig conf, @PathParam(PROJECT_ID_KEY) String projectId) {
        if(projectId!=null){
            this.session = session;
            this.projectId = projectId;
        } else {
            session.close();
        }
    }

    @OnClose
    public void close(Session session, CloseReason reason) {
        log.debug("Session closed.");
    }

    public void createdEventFired(@Observes @Created Booking entity) {
        if(session.isOpen){
            session.getAsyncRemote().sendObject(converter.from(null, repo.getBookingsByProjectId(projectId)));
        }
    }

}

问题是在createdEventFired会话和projectId上总是为null!为什么呢?

为了完整起见,配置程序(仅添加用户属性):

public class WebSocketUserConfig extends ServerEndpointConfig.Configurator {
    /**
     * Key used in config to mark if requesting user is admin.
     */
    public static final String IS_ADMIN_ADMIN = "isAdmin";

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        config.getUserProperties().put(IS_ADMIN_ADMIN, request.isUserInRole(UserRole.ADMIN.name()));
        super.modifyHandshake(config, request, response);
    }

}

0 个答案:

没有答案