Eclipse 新建 Maven Web 工程
主要文件
AuthenticationServlet 用于登录验证
NotifyServlet 系统通知消息发送
WSServerProvider WebSocket连接类
login.jsp 登录验证页面
notify.jsp 通知消息发送页面
ws.jsp 主要演示代码WebSocket所在页面
由于只是测试 故仅在 ws.jsp 中使用 console.log(..) 打印接收内容
实际应用中 传输JSON等 需要前端后端约定好固定格式便于解析
设置WEB项目以 / 访问
login.jsp
AuthenticationServlet
package mytest.java.websocket;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
public class AuthenticationServlet extends HttpServlet {
private static final long serialVersionUID = 6278973495107695637L;
public AuthenticationServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId = request.getParameter("userId");
// TODO do real authentication here
String token = getHashToken(userId);
request.getSession().setAttribute("idtoken", userId+"-"+token); /// SESSION存储
response.sendRedirect("ws.jsp"); /// 跳转至 ws.jsp 即 WebSocket 示例代码所在页面
}
/// 把用户ID的摘要做TOKEN
private String getHashToken(String userId) {