WebSocket获取service层对象,操作数据库
来源:互联网 发布:nginx 域名无法访问 编辑:程序博客网 时间:2024/06/06 08:50
在websocket中操作数据库,需要加载已经配置好的spring中的配置文件,获取service层对象。在搭建好websocket条件下以下几种方法可实现
第一种,通过ContextLoader获取
SharedFarmUsersManager sharedFarmUsersManager = (SharedFarmUsersManager) ContextLoader.getCurrentWebApplicationContext().getBean("sfum");
第二种,通过加载整个配置文件,加载完之后再获取been,这种性能较差,不建议使用
ClassPathXmlApplicationContext cc = new ClassPathXmlApplicationContext(new String[] {"applicationContext-common.xml"});SharedFarmUsersManagerImpl bean1 = (SharedFarmUsersManagerImpl) cc.getBean("sharedFarmUsersManagerImpl");
第三种,通过Configurator获取httpsession,通过httpsession可获取service
第一步编写一个继承Configurator的类
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
import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.atomic.AtomicInteger;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.websocket.EndpointConfig;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.struts2.ServletActionContext;import org.directwebremoting.json.JsonUtil;import org.directwebremoting.json.parse.JsonParseException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.web.context.ContextLoader;import org.springframework.web.context.support.WebApplicationContextUtils;import com.alibaba.fastjson.JSON;import com.nmfz.app.action.SharedFarmUsers;import com.nmfz.app.manager.SharedFarmUsersManager;import com.nmfz.app.manager.impl.SharedFarmUsersManagerImpl;import net.sf.json.JSONObject;/** * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端。注解的值将被用于监听用户连接的终端访问URL地址。 * configurator:通过GetHttpSessionConfigurator可以在onOpen方法中取得HttpSession,然后通过HttpSession的ServletContext容器可以取得spring的service,实现在websocket中变相注入spring bean。 * @author zho */@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;/** * 作用:将所有request请求都携带上httpSession * @author zho * */@WebListener//配置Listener@Componentpublic class RequestListener implements ServletRequestListener { public void requestInitialized(ServletRequestEvent sre) { //将所有request请求都携带上httpSession ((HttpServletRequest) sre.getServletRequest()).getSession(); } public RequestListener() { } public void requestDestroyed(ServletRequestEvent arg0) { }}
阅读全文
1 0
- WebSocket获取service层对象,操作数据库
- 自定义标签获取service或者dao层的对象方式
- 定时器 获取 service层
- Service层获取HttpServletRequest request
- 框架学习(1)——service层,dao层和service实现类进行数据库操作
- 获取层对象
- Spring MVC 在JSP中获取service层的Bean对象
- Spring MVC 在JSP中获取service层的Bean对象
- NDK层获取Application对象
- 使用单态(Singleton)模式获取数据库操作对象
- 在Controller层无法注入Service层的对象
- ADODB数据库抽象层操作
- dao层数据库查询操作
- WEB SERVICE 的数据库操作
- java中在Service层获取request,获取绝对路径
- 获取对象操作
- 【PDO对象操作数据库】
- redis数据库--操作对象
- 《python 核心编程第二版》第五章
- 数据结构实验之栈与队列九:行编辑器
- “下周回国贾跃亭”怒怼顾博士,文件是否签名造假!
- 用MAVEN搭建SSM框架
- Android Studio常见couldn't find "*.so"的问题
- WebSocket获取service层对象,操作数据库
- VS2015 使用ODataV4创建Web Api和OData客户端
- 小白笔记-_-Json与对象之间的转化
- 基于Spark的数据处理 --图数据库的数据处理与转换(一)
- 对Numpy数组按axis运算的理解
- Qml签名修改
- BrainTumorSeg
- org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine
- 为什么很多人喜欢把INF的初值赋成0x3f3f3f3f而不是0x7fffffff?