我有下一个websocket
@ServerEndpoint(value="/list")
public class WebSocketList implements ServletContextListener {
private ServletContextEvent sce;
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized");
this.sce = sce;
}
@OnMessage
public void receiveMessage(ByteBuffer bb, Session sn) {
if (sce == null)
System.out.println("not good");
}
File beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="annotated">
</beans>
在调试中,方法ServletContextEvent
中的对象contextInitialized
不为空,但是当我从客户端收到消息时(在方法receiveMessage中),总是记录“不好” - 对象{{1} } 一片空白。
更新:当我在两种方法中添加ServletContextEvent
时,请记下下一步 -
System.out.println(this)
答案 0 :(得分:0)
我遇到了同样的问题,正如@Sotirios所提到的那样,问题是receivedMessage(ByteBuffer, Session)
是在与contextInitialized(ServletContextEvent)
不同的对象上调用的。
解决此问题的一种方法是将private ServletContextEvent sce
字段设为静态,但我怀疑这样做可能会在上下文停止或重新加载时导致问题。更好的方法是从sce
事件中提取所需的所有信息,并将其存储在一个或多个对象字段中。
在我的情况下,我需要存储的是当前servlet上下文的路径,所以我只是这样做:
private static String path;
@Override
public void contextInitialized(ServletContextEvent sce) {
this.path = sce.getServletContext().getContextPath();
}