通过Configurator获取httpsession,通过httpsession可获取service
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
public class GetHttpSessionConfigurator extends Configurator{
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
if(httpSession != null){
config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
}
第二步编写@ServerEndpoint,并在onOpen 方法中获取service
@ServerEndpoint(value = "/websocket/chat",configurator=GetHttpSessionConfigurator.class)
public class MyWebSocket{
// private static final Log log = LogFactory.getLog(ChatAnnotation.class);
// private WebSocketService webSocketService;
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private final static AtomicInteger onlineCount = new AtomicInteger(0);
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
// private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
private static List<MyWebSocket> clients = new ArrayList<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private HttpSession httpSession;
// ngs static int userid ;
@OnOpen
public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException {
System.out.println("Open!");
this.session = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
if(httpSession != null){
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());
SharedFarmUsersManager sharedFarmUsersManager = (SharedFarmUsersManager) ctx.getBean("sfum");
List<?> list = sharedFarmUsersManager.selectListBySql("select name from f_yh where id=1", null);
System.out.println(list);
}
clients.add(this); //当前客户端加入集合
// addOnlineCount(); //在线数加1,对应的创建一个上锁的方法
MyWebSocket.onlineCount.incrementAndGet();//在线数加1
// String message = "登录成功";
// broadcast(message);
sendLatestNews();
}
第三步,由于HTTP协议与websocket协议的不同,导致没法直接从websocket中获取协议,放出去执行,会报空指针值异常,因为这个HttpSession并没有设置进去。而设置HttpSession。需要写一个继承ServletRequestListener的监听器。
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
@WebListener//配置Listener
@Component
public class RequestListener implements ServletRequestListener {
public void requestInitialized(ServletRequestEvent sre) {
//将所有request请求都携带上httpSession
((HttpServletRequest) sre.getServletRequest()).getSession();
}
public RequestListener() {
}
public void requestDestroyed(ServletRequestEvent arg0) {
}
}