WebSocket Get Service Layer objects, manipulate database

Source: Internet
Author: User
Tags config json log log

To manipulate the database in WebSocket, you need to load the configuration files in the already configured spring to get the service layer objects. The following methods can be realized under the condition of WebSocket.
the first, obtained through Contextloader

Sharedfarmusersmanager Sharedfarmusersmanager = (Sharedfarmusersmanager) Contextloader.getcurrentwebapplicationcontext (). Getbean ("Sfum");

second, by loading the entire configuration file and then acquiring been after loading, this performance is poor and is not recommended

Classpathxmlapplicationcontext cc = new Classpathxmlapplicationcontext (new string[] {"Applicationcontext-common.xml" });
Sharedfarmusersmanagerimpl bean1 = (Sharedfarmusersmanagerimpl) cc.getbean ("Sharedfarmusersmanagerimpl");

third, get httpsession through Configurator, get service through HttpSession
The first step is to write a class that inherits 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);}  
    }  
}

The second step is to write the @serverendpoint and get the service in the OnOpen method

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 Annotation is a class-level annotation whose function is to define the current class as a websocket server side.
 The value of the annotation will be used to listen to the terminal access URL address of the user connection. * Configurator: HttpSession can be obtained from the OnOpen method through Gethttpsessionconfigurator,
 Spring's service can then be obtained through the HttpSession ServletContext container, enabling the spring bean to be injected into the websocket in disguise. * @author Zho */@ServerEndpoint (value = "/websocket/chat", Configurator=gethttpsessionconfigurator.class) public class mywebsocket{//private static final log log= Logfactory.getlog (Chatannotation.class);
    Private Websocketservice Websocketservice; A static variable that is used to record the current number of online connections.  
    It should be designed to be thread-safe.  
    Private final static Atomicinteger Onlinecount = new Atomicinteger (0); The thread-safe set of the concurrent package that holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can be user ID//private static copyonwritearrayset<mywebsocket> Websocketset = new 
    Copyonwritearrayset<mywebsocket> ();
    private static list<mywebsocket> clients = new arraylist<> ();  
    A connection session with a client, which is required to send data to the client 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);   The current client joins the collection//Addonlinecount ();
Online number plus 1, corresponding to create a locked method MyWebSocket.onlineCount.incrementAndGet ();//online number plus 1//String message = "Login successful"; 
        Broadcast (message);   Sendlatestnews ();//Send a new record of stealing vegetables to this user}

The third step, because the HTTP protocol and the WebSocket protocol, resulting in the inability to get the protocol directly from the WebSocket, put out execution, will report null pointer value exception, because this httpsession is not set in. and set the HttpSession. You need to write a listener that inherits Servletrequestlistener.

Import javax.servlet.ServletRequestEvent;
Import Javax.servlet.ServletRequestListener;
Import Javax.servlet.annotation.WebListener;
Import Javax.servlet.http.HttpServletRequest;

Import org.springframework.stereotype.Component;

/**
 * Function: Bring all request requests on HttpSession
 * @author zho * *
/@WebListener//config listener
@ Component public
class Requestlistener implements Servletrequestlistener {public

    void requestinitialized ( Servletrequestevent SRE)  {
        //Bring all request requests on HttpSession
        (httpservletrequest) Sre.getservletrequest ()). GetSession ();

    }
    Public Requestlistener () {
    } public

    void requestdestroyed (servletrequestevent arg0)  {
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.