Web Socket Mapping with Java

Web Socket Mapping with Java

本文关键字:Java with Mapping Socket Web      更新时间:2023-09-26

我是websocket的新手,所以我的项目中有一些问题。我正在创建一个聊天室。我有一个登录页面,将由UsernameServlet处理,然后它将链接到chatpage.html这将打开一个websocket(聊天室服务器端点)。

这是我的登录页面.html

<body>
    <form action="localhost:8080/chatRoom/UserNameServlet" name="submitForm" onchange="handleNewRoom()">
        <mark>Please select a room:</mark>
        <select id="roomSelect" name="roomSelect">
            <option value="room1">Room 1</option>
            <option value="room2">Room 2</option>
        </select>
        <mark>Please Enter username</mark>
        <input type="text" name="username" size="20"/>
        <input type="submit" value="Enter" />
    </form>
    <script>
        window.onload = function(){document.submitForm.action=submitAction();}
        function submitAction(){
            return document.location.pathname;
        }            
    </script>
</body>

这是我的用户名 @WebServlet("/UserNameServlet")

public class UserNameServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        String username = request.getParameter("username");
        HttpSession session = request.getSession(true);
        String roomName = request.getParameter("roomSelect");
        session.setAttribute("username", username);
        PrintWriter out = response.getWriter();
        if(username == null) response.sendRedirect("loginpage.html");
        else response.sendRedirect("chatPage.html");
        }

这是我的聊天页面.html

<script>
        var websocket = new WebSocket("ws://""+"+document.location.host+"+"document.location.pathname+"+""chatroomServerEndpoint/"+roomName+"");
</script>

我的聊天室服务器端点.java

@ServerEndpoint(value="/chatroomServerEndpoint/{chatroom}", configurator=ChatroomServerConfigurator.class)

因此,我的问题是:我指向 websocket 服务器的链接是否正确,我如何在聊天页面.html中访问房间名称?

您可以将 roomName 参数添加为通过登录页面.html定义的 HTML 会话的会话属性。重定向后,可以通过构建 WebSocket 终结点配置器来访问 HTML 会话的属性。

            import javax.servlet.http.HttpSession;
            import javax.websocket.HandshakeResponse;
            import javax.websocket.server.HandshakeRequest;
            import javax.websocket.server.ServerEndpointConfig;
            import javax.websocket.server.ServerEndpointConfig.Configurator;
            public class ChatRoomEndpointConfigurator extends Configurator {
                @Override
                public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
                HttpSession httpSession = (HttpSession) request.getHttpSession();
                sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
            }
        }

之后,在服务器端点中,您将拥有:

    @ServerEndpoint(value = "/chatroomServerEndpoint/{chatroom}",configurator=ChatRoomEndpointConfigurator.class)
    public class WSServer {
        protected Session wsSession;
        protected HttpSession httpSession;      
//Now, you can access the http's session attributes:  
        @OnOpen
        public void onOpen(Session session, EndpointConfig config) {
            this.wsSession=session;
            this.httpSession=(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
            String chatRoom = (String) httpSession.getAttribute("chatRoom");
        }
     }