[JSP] JSP에서 ${ }이 안된다!!

조시현·2024년 4월 30일
0
post-thumbnail

발단

이 이야기의 시작은 이러하다.

게시판을 Spring MVC와 jsp를 통해서 개발하였고,
이후 댓글의 리스트를 출력하는 기능을 추가하는 과정이였다...

   @GetMapping("/{boardNo}")
    public ResponseEntity<?> selectCommentsByBoardNo(@PathVariable("boardNo") int boardNo) {
        List<CommentDto> comments = commentService.selectCommentsByBoardNo(boardNo);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
        return ResponseEntity.ok().headers(headers).body(comments);
    }

이번에는 댓글관련 기능은 이번에 배운 REST한 방식으로 진행해보자고
자신감 넘치게 위 처럼 코드를 짜고 시작하였다.

전개

그 후 jsp에서 호기롭게

<ul id="comment-list"></ul>

를 선언을 하고
script단을 작성하였다.

코드가 굉장히 못생기고
모양이 별로이니 여러분들도 위기가 올 수 있습니다.

위기

script 단에서

  fetch(`${root}/comment/${Board.boardNo}`)
            .then((response) => response.json())
            .then((data) => makeCommentList(data));
  
  
   function makeCommentList(comments) {
            console.log(comments)
            let tbody = ``;``
            comments.forEach(function (comment) {
                tbody += `
                          <tr id="view_${comment.commentId}" class="view text-center" data-id="${comment.commentId}" ondblclick="commentView(this);"></tr>
                          <tr>${comment.memberName}</tr>
                          <tr>${comment.content}</tr>
                          <tr>
                              <td>
                                      ${comment.registerTime}
                              <td>
                              <td>
                                  <button type="button" class="btn" onclick="createReply(this);">답글 쓰기</button>
                              <td>
                          </tr>
                          <td>
                              <button type="button" class="modifyViewBtn btn btn-outline-primary btn-sm" onclick="viewModify(this);">수정</button>
                              <button type="button" class="deleteBtn btn btn-outline-danger btn-sm" onclick="commentDelete(this);">삭제</button>
                          </td>
                          `;
            });
            document.querySelector("#comment-list").innerHTML = tbody;
        }   
            

열심히 작성을 한 후
실행을 하였다.

절정

그런데..

음...?
${} 안의 내용이 하나도 없었다!

그 이후.... 챗지피티, 블로그, 주변 사람들에게 2시간 동안 서칭을 한 결과...
무척 힘들었다

결말 (해결 방안)

script 해결 코드

  fetch(`${root}/comment/${Board.boardNo}`)
            .then((response) => response.json())
            .then((data) => makeCommentList(data));
  
  
   function makeCommentList(comments) {
            console.log(comments)
            let tbody = ``;``
            comments.forEach(function (comment) {
                tbody += `
                          <tr id="view_${"${comment.commentId}"}" class="view text-center" data-id="${"${comment.commentId}"}" ondblclick="commentView(this);"></tr>
                          <li>이름 : ${"${comment.memberId}"}</li>
                          <li>내용 : ${"${comment.content}"}</li>
                          <li>
                              <ul>${"${comment.registerTime}"}</ul>
                              <ul><button type="button" class="btn btn-outline-primary btn-sm" onclick="createReply(this);">답글 쓰기</button>
                              </ul>
                          </li>
                          <ui>
                              <button type="button" class="modifyViewBtn btn btn-outline-primary btn-sm" onclick="viewModify(this);">수정</button>
                              <button type="button" class="deleteBtn btn btn-outline-danger btn-sm" onclick="commentDelete(this);">삭제</button>
                          </ui>
                          <hr>
                          `;
            });
            document.querySelector("#comment-list").innerHTML = tbody;
        }

와!!!
해냈다 ...
진짜 소름이 돋고 짜릿하고 행복한 순간이였다.

해설

jsp에서 script단 즉, js에서 (``) 백틱 내부에서 ${}인 템플릿 리터럴을 사용하게 되면

jsp의 EL 표현식과 JavaScript의 템플릿 문자열이
겹치게 되어서 jsp의 EL 표현식이 ${}를 먼저 읽고 값을 가져가 버립니다.
그러면 자연스럽게 현재 js에서는 아무것도 없는 상태로 값이 들어가게 됩니다.

그러므로 2번싸주는방식즉,편법을이용하여서{}을 2번 싸주는 방식 즉, 편법을 이용하여서 {"${넣으려는 값}"}을 해주게 되면 가능한 것이였습니다.

profile
노력하는 개발자

0개의 댓글