Minh Hoang VO
Minh Hoang VO

Reputation: 11

Web Socket Mapping with Java

I am new to websocket so I have a few problems in my project. I am creating a chatroom. I have an login page which will be handle by UsernameServlet, then it will links to chatpage.html which will be open a websocket (chatroom server endpoint).

Here is my loginpage.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>

Here is my UserNameServlet @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");

        }

Here is my chatPage.html

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

My ChatroomServerEndpoint.java

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

Therefore, my question is: Does my link to websocket server is correct and how do I have access roomName in chatpage.html?

Upvotes: 0

Views: 1042

Answers (1)

Tudormi
Tudormi

Reputation: 1112

You can add the roomName parameter as a session attribute of the HTML session defined via the loginpage.html. After you redirect, you can access the HTML session's attribute by building a WebSocket endpoint configurator.

            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);
            }
        }

Afterwards, in the ServerEndpoint, you would have:

    @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");
        }
     }

Upvotes: 1

Related Questions