我正在尝试使用Eclipse IDE进行websocket通信,当我运行代码时,我得到了NullPointerException。我已经检查过,并且getAttribute中的名称与bean中的名称相同
package ws;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.server.ServerEndpoint;
import fundstarter.model.ConnectToRMIBean;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
@ServerEndpoint(value="/ws", configurator = HandShake.class)
public class WebSocketAnnotation {
private Session session;
private ConnectToRMIBean sessionUser;
private HttpSession httpSession;
private static final Set<WebSocketAnnotation> myConnections = new CopyOnWriteArraySet<WebSocketAnnotation>();
public WebSocketAnnotation() {
}
@OnOpen
public void start(Session session, EndpointConfig config) {
this.session = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
myConnections.add(this);
this.sessionUser = (ConnectToRMIBean) httpSession.getAttribute("RMIBean");
//sendMessage("New message");
}
@OnClose
public void end() {
// clean up once the WebSocket connection is closed
myConnections.remove(this);
}
@OnMessage
public void receiveMessage(String message) {
sendMessage(message);
}
@OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
private void sendMessage(String text) {
try {
System.out.println("[WebSocketAnnot]RMIBean User Id -> " + this.sessionUser.getUserID());
this.session.getBasicRemote().sendText(text);
} catch (IOException e) {
try {
this.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
谁能告诉我我的错误是什么?
最佳答案
我发现了错误。这是HandShake上的ModifyHandshake方法的错字
关于java - HttpSession getAttribute()返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34366424/