[22/03/17] 채팅기능(3) 자바스크립트 삼항 연산자로 보낸이 받는이 체크



🧐 설계

  1. 나의 멘토링 방 페이지에 사용자가 들어온다.
  2. 방제목과 방비밀번호를 입력하여 채팅방을 개설한다.
  3. 채팅방을 클릭하여 비밀번호를 입력해서 방에 입장한다.
  4. 채팅방에 입장하여 모달창에서 채팅을 한다!
  5. 추가된 db : 채팅방에 비밀번호 컬럼이 추가되었다.

myMentoring.html

방생성하고 입장하기

 <div class="card card-body blur shadow-blur mx-1 mx-md-1 mt-n3">
            <form th:action="@{/mentoring/room}" method="post" name="chatRoomSave">
                <div class="row">
                    <div class="col-md-3">
                        <div class="input-group input-group-outline">
                            <label class="form-label">방 제목</label>
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="input-group input-group-outline">
                            <label class="form-label">비밀번호 4자리 숫자</label>
                            <input type="password" class="form-control" id="password" name="password" maxlength="4">
                        </div>
                    </div>

                    <div class="col-md-3">
                        <button id="btn-create" class="btn btn-warning">1:1 채팅방 개설</button>
                    </div>
                </div>
            </form>
            <table class="table table-hover table-sm">
                <thead>
                <th>멘토링 1:1 채팅방</th>
                </thead>
                <tbody>
                <tr th:each="room : ${rooms}">
                    <form action="/mentoring/room" method="get" name="roomIn">
                        <input type="hidden" name="roomId" th:value="${room.roomId}">
                        <td><input type="button" class="btn btn-link btn-lg"
                                   th:onclick="roomPwCheck([[${room.password}]])" th:value="${room.name}"></td>
                    </form>
                    <span th:if="(${#strings.equals(session['loginEmail'],'[email protected]')} or ${session.loginNick}==${room.chatMentor})">
                <td>
                    <button type="button" class="btn btn-danger" th:onclick="deleteById([[${room.chatRoomId}]])">
                        채팅방 삭제
                    </button>
                </td>
                </span>
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <th:block th:replace="/member/mypage :: myPageSideBarFragment"></th:block>
</div>
<th:block th:replace="/layout/fragments/script :: scriptFragment"></th:block>
</body>

<script th:inline="javascript">
    $("#btn-create").on("click", function (e) {
        e.preventDefault();

        let name = $("input[name='name']").val();
        let password = $("#password").val();
        const chatRoomSave = document.forms["chatRoomSave"];

        console.log(password);
        //채팅방 이름 체크
        if (name == "") {
            alert("채팅방 이름을 적어주세요")
        } else {
            //비밀번호 입력 체크
            if (password == null || isNaN(password)) {
                alert("방 비밀번호 4자리 숫자를 입력해주세요.")
            } else {
                alert(name + "방이 개설되었습니다.");
                chatRoomSave.submit();
            }
        }
    });

    function deleteById(chatRoomId) {
        const reqUrl = "/mentoring/chat/" + chatRoomId;
        $.ajax({
            url: reqUrl,
            type: 'delete',
            success: function () {
                alert('삭제되었습니다.')
                location.reload();
            }, error: function () {
                alert('요청실패')
            }
        })
    }

    //채팅방 비밀번호 체크
    function roomPwCheck(roomPw) {
        let roomPwCheck = prompt("채팅방 비밀번호를 입력하세요.");
        const roomIn = document.forms["roomIn"];
        if (roomPw == roomPwCheck) {
            roomIn.submit();
        } else {
            alert('비밀번호가 틀렸습니다.');
        }
    }


</script>

나는 멘토링 방에서 방을 클릭하고
room.html에서 모달로 채팅을 하도록 하였다.

room.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<html lang="en" itemscope itemtype="http://schema.org/WebPage">

<!-- 공통 헤더-->
<th:block th:replace="/layout/fragments/head :: headFragment"></th:block>

<body>
<th:block th:replace="/layout/fragments/navbar :: navbarFragment"></th:block>
<div class="modal fade" id="chatModal" data-bs-backdrop="static" tabindex="-1" aria-labelledby="staticBackdropLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">

            <div class="user-container modal-header">
                <label class="modal-title" id="staticBackdropLabel" for="nickname">[[${room.name}]]</label>
                <span type="text" id="nickname" th:text="${session['loginNick']}"
                      th:value="${session['loginNick']}"></span>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="display-container modal-body" style="height: 1000px">
                <ul class="chatting-list" id="msgArea">
                </ul>
            </div>

            <div class="input-container modal-footer">
                <span>
                    <textarea type="text" id="msg" class="chatting-input form-control"
                              aria-label="Recipient's username"
                              aria-describedby="button-addon2"></textarea>
                    <button type="button" id="button-send" class="send-button">전송</button>
                </span>
            </div>

        </div>
    </div>

</div>

<div class="wrapper" style="margin-top: 100px;">
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#chatModal">채팅방 입장하기</button>
</div>

</body>
<th:block th:replace="/layout/fragments/script :: scriptFragment"></th:block>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script th:inline="javascript">
    $(document).ready(function () {
        let roomName = [[${room.name}]];
        let roomId = [[${room.roomId}]];
        let username = [[${session.loginNick}]];

        console.log(roomName + ", " + roomId + ", " + username  );

        let sockJs = new SockJS("/stomp/chat");
        //1. SockJS를 내부에 들고있는 stomp를 내어줌
        let stomp = Stomp.over(sockJs);

        //2. connection이 맺어지면 실행
        stomp.connect({}, function (){
            console.log("STOMP Connection")

            //4. subscribe(path, callback)으로 메세지를 받을 수 있음
            stomp.subscribe("/sub/chat/room/" + roomId, function (chat) {
                console.log("chat : "+chat);
                let content = JSON.parse(chat.body);
                let message = content.message;
                let writer = content.writer;
                console.log("content : "+content);

                //css 적용하여 반환
                const item = new LiModel(writer, message);
                item.makeLi();

                function LiModel(writer, message) {
                    this.writer = writer;
                    this.msg = message;
                    const chatList = document.querySelector(".chatting-list");
                    this.makeLi = () => {
                        const li = document.createElement("li");
                        li.classList.add(username === this.writer ? "sent" : "received")
                        const dom = `<span class="profile">
                    <span class="user">${this.writer}</span>
                    <img class="image" src="https://png.pngtree.com/png-vector/20191009/ourmid/pngtree-user-icon-png-image_1796659.jpg" alt="any">
                    </span>
                    <span class="message">${this.msg}</span>`;
                        li.innerHTML = dom;
                        chatList.appendChild(li)
                    }
                }

            });

            //3. send(path, header, message)로 메세지를 보낼 수 있음
            stomp.send('/pub/chat/enter', {}, JSON.stringify({roomId: roomId, writer: username}))
        });

        //엔터를 누르면 메시지 전송
        $("#msg").on("keyup",function(event){
            if(event.keyCode === 13){
                event.preventDefault();
                document.getElementById('button-send').click();
            }
        });

        $("#button-send").on("click", function(e){
            let msg = document.getElementById("msg");

            console.log(username + ":" + msg.value);
            stomp.send('/pub/chat/message', {}, JSON.stringify({roomId: roomId, message: msg.value, writer: username}));
            msg.value = '';
        });
    });
</script>
</html>

채팅은 바닐라 자바스크립트 강의에서 배웠던 css를 사용하였다.

좋은 웹페이지 즐겨찾기