JFinal使用WebSocket

1、先建立一个Maven项目,如果是老项目,也可转成maven项目,参见我之前写的一篇帮助:
Myeclipse普通java项目转maven项目

2、pom.xml引用相关jar包,1.7之后支持,配置如下:

    

        
            javax
            javaee-api
            7.0
            provided
        
    

tomcat7和jave EE 1.7都支持,注意引用一个,不要重复。

3、编写事件拦截处理代码:
ZhiWebSocketHandler.java

package com.yyxz.main;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;

public class ZhiWebSocketHandler extends Handler {

    private Pattern filterUrlRegxPattern;
    
    public ZhiWebSocketHandler(String filterUrlRegx) {
        if (StrKit.isBlank(filterUrlRegx))
            throw new IllegalArgumentException("The para filterUrlRegx can not be blank.");
        filterUrlRegxPattern = Pattern.compile(filterUrlRegx);
    }
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        // TODO Auto-generated method stub
        if (filterUrlRegxPattern.matcher(target).find())
            return ;
        else {
            next.handle(target, request, response, isHandled);
        }
    }

}

在JFinal Config中进行注册:

public class DemoConfig extends JFinalConfig {
//...
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("ctx"));
        me.add(new ZhiWebSocketHandler("^/websocket"));
// 也可以使用UrlSkipHandler,就不用编写Handler处理类了
//      me.add(new UrlSkipHandler("^/websocket", false));
    }
//...
}

4、后台监听websocket代码:
WebSocketController.java

package com.yyxz.controller;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocketController {
    public WebSocketController() {
        System.out.println(" WebSocket init~~~");
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("onOpen");
    }

    @OnClose

    public void onClose(Session session) {
        System.out.println("onClose");
    }
    
//  @OnError
//  public void onError(Session session) {
//      System.out.println("onError");
//  }

    @OnMessage
    public void onMessage(String requestJson, Session session)
            throws IOException {
        requestJson = "一一小知回复:" + requestJson; 
        System.out.println(requestJson);
        session.getBasicRemote().sendText(requestJson);
    }
}

5、在前端发起,编写页面:
webSocketTest.jsp

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>





Java后端WebSocket的Tomcat实现


    Welcome
    


结果如下:

JFinal使用WebSocket_第1张图片
image.png
JFinal使用WebSocket_第2张图片
image.png

你可能感兴趣的:(JFinal使用WebSocket)