您好,登錄后才能下訂單哦!
本篇內容介紹了“websocket建立連接時傳遞參數的方法”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
后臺獲取參數4中方法:
websocket的url
"ws:localhost:82/chat/123?username=ydh";
socket的注釋
@ServerEndpoint("/chat/{param}")
socket的open方法
@OnOpen public void open(Session session, @PathParam("param")String param) { System.out.println("用戶"+param+" 登錄"); Map<String, String> map = session.getPathParameters(); System.out.println("session.getPathParameters()"+map.toString()); String str = session.getQueryString(); System.out.println("session.getQueryString()"+str); String uri = session.getRequestURI().toString(); System.out.println("session.getRequestURI().toString()"+uri); }
結果
用戶123 登錄 session.getPathParameters(){param=123} session.getQueryString()username=baidu session.getRequestURI().toString()/chat/123?username=baidu
1、url站位,通過@PathParam注釋獲取
2、url站位,通過session.getPathParameters()獲取
3、url傳參,通過session.getQueryString()
4、url傳參,通過session.getRequestURI().toString()
從結果可以看出1、2兩個方法不需要截取,可以直接使用;而3、4兩個方法都需要截取字符串,稍微麻煩,但是請求的url比較清爽。
下面的是完整代碼
config代碼
import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig; import java.util.Set; public class ChatConfig implements ServerApplicationConfig { // 注解 @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { System.out.println("websocket......啟動!"+scanned.size()); return scanned; } // 接口 @Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned) { return null; } }
socket代碼
import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.Map; /** * @description: * @author: yangdehong * @version: 2017/6/4. */ @ServerEndpoint("/chat/{param}") public class ChatSocket { @OnOpen public void open(Session session, @PathParam("param")String param) { System.out.println("用戶"+param+" 登錄"); Map<String, String> map = session.getPathParameters(); System.out.println("session.getPathParameters()"+map.toString()); String str = session.getQueryString(); System.out.println("session.getQueryString()"+str); String uri = session.getRequestURI().toString(); System.out.println("session.getRequestURI().toString()"+uri); } @OnClose public void close(Session session){ System.out.println("sessionId:"+session.getId()+"關閉"); } @OnMessage public void message(Session session, String message, boolean last) throws IOException { System.out.println("sessionId:"+session.getId()+"-------"+message+"------"+last); session.getBasicRemote().sendText("接受成功"); } }
模擬登錄servlert
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @description: * @author: yangdehong * @version: 2017/6/3. */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); request.getSession().setAttribute("username", username); response.sendRedirect("chat.jsp"); } }
chat.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript"> var ws; var target = "ws:localhost:82/chat/123?username=" + '${username}'; window.onload = function () { if ('WebSocket' in window) { ws = new WebSocket(target); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(target); } else { alert('WebSocket is not supported by this browser.'); return; } }; </script> </head> <body> <div id="content"> </div> <div id="userList"> </div> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <form action="LoginServlet" method="get"> name:<input name="username"> <input type="submit" /> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>websocket</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
maven
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-websocket</artifactId> <version>8.0.26</version> </dependency>
“websocket建立連接時傳遞參數的方法”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。