JavaWebSocket,获取并使用HttpSession与SpringBean

注意!本文最终示例的有几行使用SpringGetBean的代码,若是与您并未使用Spring可自行删除相关代码,并不影响其它代码.

本文的Bean指Spring的Bean,因为有些同学在运行时出现了NullPointException,其实就是Bean的问题.

ps.需要javaee-api7.0的jar别忘了

1.如何获取HttpSession

需新建一个类,在websocket中调用:

/**
 * 获取httpSession
 */
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec,
                                HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession=(HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

2.如何使用Spring中的bean

我知道两种方法解决:
1.使用比较原始的方法getBean;
2.使用可以正常使用Bean的类,在此类中写方法再调用那个类来实现Bean(有点绕,未亲测);

我这里介绍一下方法1:

//其实就是在刚开始学习Spring的时候,调用Bean的方法
private ApplicationContext ctx = new ClassPathXmlApplicationContext("config/spring/*.xml");
private DemoService demoService = (DemoService) ctx.getBean("DemoService");

3.综上两点,WebSocket的示例

注意:后端中的@ServerEndpoint(value=”/demo”)与前端中的WebSocket(“ws://localhost:8080/demo”)是要对应的.

不废话,看着代码谁都懂了:

/* 后端java代码 */

@ServerEndpoint(value="/demo", configurator=GetHttpSessionConfigurator.class)
public class WebSocket {

    //这个session不同于httpsession,下面自然有用处
    private Session session;
    private HttpSession httpSession;
    private ApplicationContext ctx = new ClassPathXmlApplicationContext("config/spring/*.xml");
    private DemoService demoService = (DemoService) ctx.getBean("DemoService");

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config){
        this.session = session;
        //获取HttpSession
        httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        System.out.println("WebSocket建立连接");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        System.out.println("WebSocket连接关闭");
    }

    /**
     * 向页面发送消息
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("向页面发送消息");
        try {
            //使用SpringBean操作HttpSession示例
            httpSession.setAttribute("Demo", demoService.Demo((String) httpSession.getAttribute("id")));
            //使用this.session向页面发送'1',这是为了触发onmessage方法,下文会提到
            this.session.getBasicRemote().sendText("1");
            System.out.println("已发送消息");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("WebSocket发生错误");
        error.printStackTrace();
    }

}
/* 前端js代码 */

<script type="text/javascript">
    var websocket = null;
    // 判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/demo");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //websocket开始
    websocket.onopen = function () {
        $("#startweb").html('websocket开始');
        //websocket发送,设置5s发送一次
        setInterval(
            function() {
                websocket.send(1);
            }, 5000);
    }
    //websocket收到后端返回,触发onmessage事件(由于5s发送一次,所以同样5s触发一次该事件)
    websocket.onmessage = function (event) {
        //可以设置一些自己需要的事件        
        $("#demo").click();
    }
    //还有诸如onclose等等事件,并不必须,不再赘述
</script>


以上代码都亲测可行.
不过关键地方还是要大家自己去设置方法事件,不过影响不大.


加油,共勉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值