问题
Socket长连接参数解析报错 java.lang.NumberFormatException: null
详细问题
笔者使用技术框架Servlet + JSP,基于Socket长连接实现实时聊天室
JSP核心代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><html>
<head><title>实时聊天室</title><script><c:set var="ChatObjectId" value="${ChatObjectId}"/>var socket;function connect() {socket = new WebSocket("ws://localhost:8080/bms/chat?ChatObjectId=" + ${ChatObjectId});socket.onopen = function () {console.log("WebSocket连接已打开");};socket.onmessage = function (event) {var message = event.data;// 处理接收到的消息,例如将其显示在聊天窗口中var chatWindow = document.getElementById("chat-window");var newMessage = document.createElement("p");newMessage.textContent = message;chatWindow.appendChild(newMessage);};}function sendMessage() {var input = document.getElementById("message");var message = input.value;socket.send(message);input.value = "";}function disconnect() {socket.close();}</script>
</head>
<body><div id="chat-window"></div><input type="text" id="message" /><button onclick="sendMessage()">发送</button><button onclick="connect()">连接</button><button onclick="disconnect()">断开连接</button>
</body>
</html>
java核心代码
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;@ServerEndpoint("/chat")
public class ChatServer {private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());private static Map<Integer, Session> userSessions = Collections.synchronizedMap(new HashMap<>());@OnOpenpublic void onOpen(Session session, @PathParam("ChatObjectId") String ChatObjectId) {sessions.add(session);// 将字符串转换为整数类型的用户IDInteger ChatObjectId= Integer.parseInt(ChatObjectId); // 将会话与userId关联,并添加到userSessions集合中userSessions.put(ChatObjectId, session);}@OnMessagepublic void onMessage(String message, Session session) throws IOException {try {Jsonb jsonb = JsonbBuilder.create();MessagePayload payload = jsonb.fromJson(message, MessagePayload.class);Integer targetUserId = payload.getUserId();String content = payload.getContent();sendToUser(targetUserId, content);} catch (JsonbException e) {e.printStackTrace();}}public void sendToUser(Integer userId, String message) throws IOException {Session session = userSessions.get(userId);if (session != null) {session.getBasicRemote().sendText(message);}}@OnClosepublic void onClose(Session session) {sessions.remove(session);}@OnErrorpublic void onError(Throwable error) {error.printStackTrace();}
}
运行项目,控制台报错
java.lang.NumberFormatException: nullat java.lang.Integer.parseInt(Integer.java:542)at java.lang.Integer.parseInt(Integer.java:615)at com.iflytek.bms.web.listener.ChatServer.onOpen(ChatServer.java:23)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.apache.tomcat.websocket.pojo.PojoEndpointBase.doOnOpen(PojoEndpointBase.java:69)at org.apache.tomcat.websocket.pojo.PojoEndpointServer.onOpen(PojoEndpointServer.java:48)at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:136)at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:936)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)at java.lang.Thread.run(Thread.java:748)
解决方案
在JSP页面修改
socket = new WebSocket("ws://localhost:8080/bms/chat?ChatObjectId=" + ${ChatObjectId});
为
socket = new WebSocket("ws://localhost:8080/bms/chat/ChatObjectId=" + ${ChatObjectId});
原因
@PathParam注解通常用于解析路径参数(修改后的/),而不是查询参数(使用?和&拼接的参数),因此后端接口无法正常获取ChatObjectId的内容,由于默认值为Null,导致报次错误。
疑问
似乎一切都可以解释的通,但是笔者事后复现错误,发现不进行修改也可以正常连接(笔者尝试清楚IDEA缓存于游览器缓存,确定并非IDEA或游览器缓存所导致的),对于该问题,笔者感到好奇,若是有大佬明白,希望指点
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈