10. 게시판 화면 퍼블리싱 - Tailwind · fetch · DOM · XSS > 웹DB프로그래밍(2027 겨울)

본문 바로가기

[퍼블리싱] 10. 게시판 화면 퍼블리싱 - Tailwind · fetch · DOM · XSS

필기자
22시간 7분전 98 0
  • - 첨부파일 : 실습코드_10차시.zip (70.5K) - 다운로드

본문

게시판 화면 퍼블리싱

  • HTML(HyperText Markup Language)·CSS(Cascading Style Sheets)·JavaScript
  • Tailwind CSS
  • fetch 와 비동기
  • DOM(Document Object Model)
  • XSS(Cross-Site Scripting)

실습 파일: 이 차시까지 실습을 마친 board 프로젝트 전체가 글 아래 첨부 파일 실습코드_10차시.zip 에 있음. 압축을 풀고 IntelliJ 에서 board 폴더를 열면 바로 실행할 수 있음 (DB 이름 board, root 암호 12345678 기준)

목차

  • 10-1 제공 화면 구성
  • 10-2 화면을 이루는 세 가지 기술
  • 10-3 Tailwind CSS 기본
  • 10-4 fetch 기본
  • 10-5 비동기와 Promise
  • 10-6 DOM - 화면을 JavaScript 로 바꾸기
  • 10-7 글 목록 화면
  • 10-8 글쓰기 화면
  • 10-9 글 보기 화면
  • 10-10 보안 - XSS 와 textContent
  • 10-11 개발자 도구로 확인하기
  • 10-12 핵심 정리
  • 10-13 확인 문제

10-1 제공 화면 구성

  • 게시판 화면(HTML·CSS·JS)은 미리 작성해 제공함
  • 화면 작성은 실무에서 프런트엔드 개발자의 역할, 학생은 서버 API(Application Programming Interface) 개발에 집중
  • 화면 파일은 이 글 아래 첨부 파일 실습코드_10차시.zip 의 board/src/main/resources/static 폴더에 있음
  • 압축을 풀어 그 static 폴더를 자신의 프로젝트 src/main/resources 안에 덮어씀 (같은 이름의 파일은 덮어쓰기). 압축을 푼 board 프로젝트를 그대로 열어 실행해도 됨
  • 서버를 재실행하고 http://localhost:8080/boards/list.html 접속
#폴더 src/main/resources/static
static/
  hello.html  # 그대로 - 6차시 첫 실습 화면
  boards/  # 새로 생김 - 게시판 화면 폴더
    list.html  # 새로 생김 - 글 목록, GET /api/boards 호출
    write.html  # 새로 생김 - 글쓰기, POST /api/boards 호출
    view.html  # 새로 생김 - 글 보기, GET /api/boards/{id} 호출
화면 주소호출 API기능
/boards/list.htmlGET /api/boards글 목록을 조회해 표로 출력
/boards/write.htmlPOST /api/boards입력값을 JSON 으로 전송해 등록
/boards/view.html?id=1GET /api/boards/1글 한 개를 조회해 출력

JSON: JavaScript Object Notation

화면과 서버는 API 주소와 JSON 형식 만 일치하면 서로 독립적임. 이후 화면을 Vue·React 로 바꿔도 서버 코드는 그대로 사용함

10-2 화면을 이루는 세 가지 기술

HTML CSS JavaScript
기술역할비유게시판 적용
HTML내용과 구조건물의 뼈대표, 입력칸, 버튼
CSS모양 (색, 크기, 배치)인테리어Tailwind 클래스
JavaScript동작 (클릭 처리, 서버 호출, 화면 갱신)전기·수도fetch 로 API 호출, 표 채우기
  • 퍼블리싱
    • 디자인 시안을 HTML·CSS 로 구현하는 작업
    • 국내에서는 퍼블리셔라는 직무가 따로 있기도 함
  • 프런트엔드 개발
    • 퍼블리싱 결과물에 JavaScript 로 동작과 서버 연동을 구현하는 작업
    • 규모가 커지면 React, Vue 같은 화면 프레임워크를 사용함

CSS 프레임워크 비교와 Tailwind 를 쓰는 이유

구분BootstrapTailwind직접 작성
사용처기존 교안이 수업 (Tailwind CSS)CSS 파일 직접 작성
방식완성된 컴포넌트 클래스 (btn, card)단일 기능 유틸리티 클래스 조합 (px-4, bg-blue-600)선택자와 속성을 직접 작성
디자인 자유도사이트마다 비슷한 모양이 되기 쉬움높음제약 없음
CSS 파일별도로 필요HTML 안에서 처리별도로 작성
현재 추세관리자 화면, 오래된 사이트최근 신규 서비스에서 가장 많이 사용함-
학습 부담컴포넌트 클래스 이름 암기클래스 이름이 CSS 속성과 대응함CSS 전반을 알아야 함
  • 수업은 CDN(Content Delivery Network, 인터넷 주소에서 바로 불러오는 방식)을 사용하므로 설치가 필요 없음
  • 실제 서비스에서는 사용한 클래스만 추출해 작은 CSS 파일로 만드는 빌드 과정을 거침

10-3 Tailwind CSS 기본

  • 미리 정의된 클래스 이름을 class 속성에 나열해 스타일을 지정하는 CSS 프레임워크
  • CDN 스크립트 한 줄로 설치 없이 사용
class의미
max-w-4xl mx-auto최대 너비 제한, 가운데 정렬
px-6 py-10좌우 안쪽 여백 1.5rem, 위아래 2.5rem
bg-white rounded-xl shadow-sm흰 배경, 둥근 모서리, 옅은 그림자
text-2xl font-bold text-gray-800큰 글자, 굵게, 진한 회색
flex items-center justify-between가로 배치, 세로 가운데, 양 끝 정렬
hover:bg-blue-50마우스를 올리면 옅은 파란 배경

10-4 fetch 기본

fetch 흐름
코드의미
fetch('/api/boards')GET 요청 (기본값)
fetch(url, { method: 'POST', headers: {...}, body: ... })POST 요청, 본문에 JSON 을 담아 전송
'Content-Type': 'application/json'요청 본문이 JSON 임을 서버에 알림
JSON.stringify(객체)JavaScript 객체를 JSON 문자열로 변환
res.json()응답 JSON 문자열을 JavaScript 객체로 변환
element.textContent = 값사용자가 입력한 문자열을 태그 안에 텍스트로 삽입 (HTML 로 해석하지 않아 안전)

10-5 비동기와 Promise

동기와 비동기
  • 동기(Synchronous)
    • 작업이 끝날 때까지 기다렸다가 다음 작업을 수행함
    • 서버 응답을 기다리는 동안 화면이 멈춤
  • 비동기(Asynchronous)
    • 요청을 보낸 뒤 다른 작업을 계속하다가 응답이 도착하면 처리함
    • fetch 는 비동기. 응답을 기다리는 동안에도 스크롤, 클릭이 가능함
  • Promise
    • 비동기 작업의 결과(성공 또는 실패)를 나중에 전달하는 객체
    • .then(성공 시 처리), .catch(실패 시 처리)

같은 코드를 async / await 로 작성하기

#코드 then 방식 (제공 화면)
fetch('/api/boards')                     // 서버에 GET /api/boards 요청
    .then(res => res.json())              // 응답이 도착하면 본문 JSON 을 객체로 변환
    .then(boards => {                      // 변환 결과(글 배열)를 받아서
        console.log(boards.length + '개'); // 글 개수 출력
    })
    .catch(err => alert('목록을 불러오지 못했습니다'));   // 서버가 꺼져 있는 등 요청 자체가 실패한 경우
#코드 async / await 방식
async function loadBoards() {
    try {
        const res = await fetch('/api/boards');   // 응답이 도착할 때까지 이 함수 안에서만 대기
        const boards = await res.json();          // 본문 JSON 을 객체로 변환
        console.log(boards.length + '개');        // 글 개수 출력
    } catch (err) {                              // 요청 자체가 실패한 경우
        alert('목록을 불러오지 못했습니다');
    }
}
loadBoards();                                     // 함수 실행
  • 두 방식의 동작은 같음. await 는 then 을 읽기 쉽게 작성하는 문법
  • React, Vue 코드에서는 async / await 를 더 많이 사용함

10-6 DOM - 화면을 JavaScript 로 바꾸기

DOM
  • DOM (Document Object Model)
    • 브라우저가 HTML 을 해석해 만든 트리 구조의 객체 모델
    • JavaScript 는 DOM 을 변경해 화면을 갱신함
코드기능
document.getElementById('rows')id 로 요소 하나를 찾음
document.querySelector('.title')CSS 선택자와 일치하는 첫 번째 요소를 찾음
document.createElement('tr')새 요소를 생성함
부모.appendChild(자식)생성한 요소를 부모 요소의 자식으로 추가함
태그.textContent = 값값을 텍스트로 설정함 (태그로 해석하지 않음)
태그.innerHTML = 값값을 HTML 로 설정함 (태그를 해석하므로 사용자 입력에 쓰면 위험)
태그.addEventListener('click', 함수)클릭 이벤트 처리 함수를 등록함

10-7 글 목록 화면

#코드 src/main/resources/static/boards/list.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <!-- 한글이 깨지지 않도록 문자 인코딩을 UTF-8 로 지정함 -->
    <meta charset="UTF-8">
    <!-- 모바일에서도 화면 폭에 맞춰 표시되게 함 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>글 목록 - 웹DB 게시판</title>
    <!-- Tailwind CSS (CDN): class 이름만 지정하면 스타일이 적용됨 -->
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<!--
    자주 쓰는 Tailwind 클래스 묶음 (다른 화면도 같은 뜻)
    - bg-gray-50 min-h-screen : 연한 회색 바탕, 화면 높이만큼 채움
    - max-w-4xl mx-auto : 내용 폭을 제한하고 가운데 정렬
    - px-6 py-10 : 안쪽 여백 (px 좌우, py 위아래, 숫자 1 = 0.25rem)
    - mt-2 mb-6 : 바깥 여백 (mt 위, mb 아래)
    - flex items-center justify-between : 가로로 나란히, 세로 가운데, 양 끝으로 벌림
    - gap-4 : 나란한 요소 사이 간격
    - text-sm / text-2xl font-bold : 글자 작게 / 글자 크고 굵게
    - text-gray-600 / bg-blue-600 : 글자색 / 배경색 (숫자가 클수록 진함)
    - rounded-xl shadow-sm border : 둥근 모서리, 옅은 그림자, 테두리
    - hover:bg-blue-50 : 마우스를 올렸을 때만 적용
    - w-full / w-16 : 폭 꽉 채움 / 고정 폭
-->
<!-- 상단 메뉴 영역 (모든 화면 공통) -->
<header class="bg-white border-b border-gray-200">
    <div class="max-w-4xl mx-auto px-6 h-16 flex items-center justify-between">
        <!-- 사이트 이름: 누르면 글 목록으로 이동 -->
        <a href="/boards/list.html" class="text-xl font-bold text-blue-600">웹DB 게시판</a>
        <!-- 메뉴 링크 묶음 -->
        <nav class="flex items-center gap-4 text-sm">
            <a href="/boards/list.html" class="text-gray-600 hover:text-blue-600">글 목록</a>
            <a href="/boards/write.html" class="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700">글쓰기</a>
        </nav>
    </div>
</header>

<!-- 본문 영역 -->
<main class="max-w-4xl mx-auto px-6 py-10">
    <!-- 화면 제목과 전체 글 수 -->
    <div class="flex items-end justify-between mb-6">
        <h1 class="text-2xl font-bold text-gray-800">글 목록</h1>
        <span class="text-sm text-gray-500">전체 <b id="count">0</b>건</span>
    </div>

    <!-- 글 목록 표 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <table class="w-full text-sm">
            <!-- 표 머리글 행 (열 이름) -->
            <thead class="bg-gray-100 text-gray-600">
            <tr>
                <th class="py-3 w-16">번호</th>
                <th class="py-3 text-left px-4">제목</th>
                <th class="py-3 w-28">작성자</th>
                <th class="py-3 w-32">작성일</th>
                <th class="py-3 w-16">조회</th>
            </tr>
            </thead>
            <!-- 글 행이 추가될 영역 (스크립트가 채움) -->
            <tbody id="rows"></tbody>
        </table>
    </div>
</main>

<!-- 하단 꼬리말 -->
<footer class="py-8 text-center text-xs text-gray-400">웹DB프로그래밍 게시판</footer>

<!-- 화면 동작: 서버 API 를 fetch 로 호출하고 받은 JSON 으로 화면을 채움 -->
<script>
    // 1. 서버에 글 목록 요청  GET /api/boards (method 를 적지 않으면 GET)
    fetch('/api/boards')
        .then(res => res.json())   // 응답 본문(JSON 문자열)을 자바스크립트 객체·배열로 변환함
        .then(boards => {   // boards: 글 객체 배열
            document.getElementById('count').textContent = boards.length;   // 전체 글 수 표시
            const rows = document.getElementById('rows');   // 행을 추가할 tbody

            // 2. 글이 없으면 안내 행 하나만 추가하고 종료함
            if (boards.length === 0) {
                // 고정 문구이므로 innerHTML 로 삽입해도 안전함
                rows.innerHTML = '<tr><td colspan="5" class="py-16 text-center text-gray-400">아직 글이 없습니다. 첫 글을 써 보세요.</td></tr>';
                return;
            }

            // 3. 글 하나마다 표의 행(tr)을 하나씩 생성함
            boards.forEach(board => {
                const tr = document.createElement('tr');   // 새 tr 요소를 생성함 (아직 화면에는 없음)
                tr.className = 'border-t border-gray-100 hover:bg-blue-50';   // class 지정 (위쪽 테두리, 마우스를 올리면 파란 배경)
                // 셀 골격은 innerHTML 로 한 번에 삽입함 (번호·작성일·조회수는 서버가 생성한 값이므로 그대로 삽입함)
                // 제목 링크는 ?id=글번호 를 추가해 상세 화면에 번호를 전달함, 작성일은 앞 10글자(날짜)만
                tr.innerHTML = `
                    <td class="py-3 text-center text-gray-500">${board.id}</td>
                    <td class="py-3 px-4"><a href="/boards/view.html?id=${board.id}" class="text-gray-800 hover:text-blue-600"></a></td>
                    <td class="py-3 text-center"></td>
                    <td class="py-3 text-center text-gray-500">${board.createdAt.substring(0, 10)}</td>
                    <td class="py-3 text-center text-gray-500">${board.viewCount}</td>`;
                // 사용자가 입력한 값(제목·작성자)은 textContent 로 설정함 (문자 그대로 표시됨)
                // innerHTML 로 삽입하면 글 속 <script> 같은 태그가 실행될 수 있음 (XSS 공격 방지)
                tr.querySelector('a').textContent = board.title;
                tr.children[2].textContent = board.writer;   // 세 번째 칸(작성자)
                rows.appendChild(tr);   // 완성한 행을 표에 추가해 화면에 표시함
            });
        });
</script>
</body>
</html>
  • fetch('/api/boards')
    • 서버에서 글 목록(JSON 배열)을 받음
  • boards.forEach(board => ...)
    • 글마다 표의 tr 행을 하나씩 생성
  • board.createdAt.substring(0, 10)
    • "2026-12-05T13:17:49" 에서 날짜 부분만 추출
  • textContent 로 제목·작성자 삽입
    • 글에 <script> 같은 태그를 써도 실행되지 않음 (XSS 방지)

글이 없을 때

빈 글 목록

글이 있을 때

글 목록

10-8 글쓰기 화면

#코드 src/main/resources/static/boards/write.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <!-- 한글이 깨지지 않도록 문자 인코딩을 UTF-8 로 지정함 -->
    <meta charset="UTF-8">
    <!-- 모바일에서도 화면 폭에 맞춰 표시되게 함 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>글쓰기 - 웹DB 게시판</title>
    <!-- Tailwind CSS (CDN): class 이름만 지정하면 스타일이 적용됨 -->
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- 상단 메뉴 영역 (모든 화면 공통) -->
<header class="bg-white border-b border-gray-200">
    <div class="max-w-4xl mx-auto px-6 h-16 flex items-center justify-between">
        <!-- 사이트 이름: 누르면 글 목록으로 이동 -->
        <a href="/boards/list.html" class="text-xl font-bold text-blue-600">웹DB 게시판</a>
        <!-- 메뉴 링크 묶음 -->
        <nav class="flex items-center gap-4 text-sm">
            <a href="/boards/list.html" class="text-gray-600 hover:text-blue-600">글 목록</a>
            <a href="/boards/write.html" class="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700">글쓰기</a>
        </nav>
    </div>
</header>

<!-- 본문 영역 -->
<main class="max-w-4xl mx-auto px-6 py-10">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">글쓰기</h1>

    <!-- 글쓰기 입력 폼 -->
    <form id="writeForm" class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 space-y-5">
        <!-- 제목 입력 칸 -->
        <div>
            <label for="title" class="block text-sm font-medium text-gray-700 mb-1">제목</label>
            <input type="text" id="title" placeholder="제목을 입력하세요" required
                   class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <!-- 작성자 입력 칸 -->
        <div>
            <label for="writer" class="block text-sm font-medium text-gray-700 mb-1">작성자</label>
            <input type="text" id="writer" placeholder="이름" required
                   class="w-60 rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <!-- 내용 입력 칸 (textarea 는 여러 줄 입력) -->
        <div>
            <label for="content" class="block text-sm font-medium text-gray-700 mb-1">내용</label>
            <textarea id="content" rows="10" placeholder="내용을 입력하세요" required
                      class="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
        </div>
        <!-- 취소·등록 단추 -->
        <div class="flex justify-end gap-2">
            <a href="/boards/list.html" class="px-5 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-100">취소</a>
            <button type="submit" class="px-5 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700">등록</button>
        </div>
    </form>
</main>

<!-- 하단 꼬리말 -->
<footer class="py-8 text-center text-xs text-gray-400">웹DB프로그래밍 게시판</footer>

<!-- 화면 동작: 서버 API 를 fetch 로 호출하고 받은 JSON 으로 화면을 채움 -->
<script>
    // 폼을 제출하면(등록 단추, Enter) 실행할 함수 등록
    document.getElementById('writeForm').addEventListener('submit', e => {
        e.preventDefault();   // 폼의 기본 전송(화면 새로 고침)을 막고 fetch 로 직접 전송함

        // 1. 입력값을 객체로 모음 (전송할 때 JSON 문자열로 변환함)
        const body = {   // 서버로 보낼 값을 객체로 모음
            title: document.getElementById('title').value,   // 입력 칸의 값은 .value 로 읽음
            writer: document.getElementById('writer').value,
            content: document.getElementById('content').value
        };

        // 2. 서버에 등록 요청  POST /api/boards
        fetch('/api/boards', {
            method: 'POST',   // 새 자원을 생성하는 요청이므로 POST
            headers: { 'Content-Type': 'application/json' },   // 본문 형식이 JSON 임을 서버에 알림
            body: JSON.stringify(body)   // 객체를 JSON 문자열로 변환해 본문에 담음
        })
            .then(res => res.json())   // 응답 본문(JSON 문자열)을 자바스크립트 객체·배열로 변환함
            // 3. 응답으로 받은 새 글 번호로 상세 화면 이동
            .then(board => location.href = '/boards/view.html?id=' + board.id);   // 서버가 반환한 새 글 번호(board.id)로 이동
    });
</script>
</body>
</html>
  • e.preventDefault()
    • 폼의 기본 동작(화면 새로 고침하며 전송)을 막고 fetch 로 직접 전송
  • body 객체
    • title, writer, content 세 값을 묶음, 서버 BoardRequest 의 필드 이름과 일치해야 함
  • location.href = '/boards/view.html?id=' + board.id
    • 등록 응답으로 받은 새 글 번호의 보기 화면으로 이동
글쓰기 화면

10-9 글 보기 화면

#코드 src/main/resources/static/boards/view.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <!-- 한글이 깨지지 않도록 문자 인코딩을 UTF-8 로 지정함 -->
    <meta charset="UTF-8">
    <!-- 모바일에서도 화면 폭에 맞춰 표시되게 함 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>글 보기 - 웹DB 게시판</title>
    <!-- Tailwind CSS (CDN): class 이름만 지정하면 스타일이 적용됨 -->
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- 상단 메뉴 영역 (모든 화면 공통) -->
<header class="bg-white border-b border-gray-200">
    <div class="max-w-4xl mx-auto px-6 h-16 flex items-center justify-between">
        <!-- 사이트 이름: 누르면 글 목록으로 이동 -->
        <a href="/boards/list.html" class="text-xl font-bold text-blue-600">웹DB 게시판</a>
        <!-- 메뉴 링크 묶음 -->
        <nav class="flex items-center gap-4 text-sm">
            <a href="/boards/list.html" class="text-gray-600 hover:text-blue-600">글 목록</a>
            <a href="/boards/write.html" class="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700">글쓰기</a>
        </nav>
    </div>
</header>

<!-- 본문 영역 -->
<main class="max-w-4xl mx-auto px-6 py-10">
    <!-- 글 본문 카드 -->
    <article class="bg-white rounded-xl shadow-sm border border-gray-200">
        <!-- 제목과 작성자·작성일·조회수 -->
        <div class="px-8 py-6 border-b border-gray-100">
            <h1 id="title" class="text-2xl font-bold text-gray-800"></h1>
            <div class="mt-2 text-sm text-gray-500 flex gap-4">
                <span id="writer"></span>
                <span id="createdAt"></span>
                <span>조회 <span id="viewCount"></span></span>
            </div>
        </div>
        <!-- 글 내용 (whitespace-pre-line: 입력한 줄바꿈을 그대로 표시함) -->
        <div id="content" class="px-8 py-8 text-gray-700 leading-relaxed whitespace-pre-line"></div>
    </article>

    <!-- 목록 단추 -->
    <div class="mt-6 flex justify-end">
        <a href="/boards/list.html" class="px-5 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-100">목록</a>
    </div>
</main>

<!-- 하단 꼬리말 -->
<footer class="py-8 text-center text-xs text-gray-400">웹DB프로그래밍 게시판</footer>

<!-- 화면 동작: 서버 API 를 fetch 로 호출하고 받은 JSON 으로 화면을 채움 -->
<script>
    // 1. 주소의 ?id=1 에서 글 번호를 읽음
    const id = new URLSearchParams(location.search).get('id');   // location.search 는 주소의 ?id=1 부분, get('id') 로 '1' 을 읽음

    // 2. 서버에 글 한 개 요청  GET /api/boards/1
    fetch('/api/boards/' + id)
        .then(res => res.json())   // 응답 본문(JSON 문자열)을 자바스크립트 객체·배열로 변환함
        .then(board => {   // board: 글 객체 (id, title, writer, content 등)
            // 3. 받은 값을 화면에 채움 (사용자가 입력한 값이므로 textContent 로 설정함, XSS 방지)
            document.title = board.title + ' - 웹DB 게시판';   // 브라우저 탭 제목 변경
            document.getElementById('title').textContent = board.title;
            document.getElementById('writer').textContent = board.writer;
            // 작성일 '2027-01-04T14:00:00' 에서 앞 16글자만, T 는 공백으로 치환함
            document.getElementById('createdAt').textContent = board.createdAt.substring(0, 16).replace('T', ' ');
            document.getElementById('viewCount').textContent = board.viewCount;
            document.getElementById('content').textContent = board.content;
        });
</script>
</body>
</html>
  • new URLSearchParams(location.search).get('id')
    • 주소의 ?id=1 에서 1 을 추출
  • whitespace-pre-line
    • 내용의 줄바꿈을 화면에서도 줄바꿈으로 표시 (Tailwind)
글 보기 화면

10-10 보안 - XSS 와 textContent

XSS
  • XSS (Cross Site Scripting)
    • 게시판 글에 악성 스크립트를 삽입해 다른 사용자의 브라우저에서 실행시키는 공격
    • 다른 사용자의 로그인 정보(쿠키)를 탈취하거나 화면을 조작함
  • 예: 제목에 아래 문자열을 입력
    • <img src=x onerror="alert(document.cookie)">
    • innerHTML 로 설정하면 img 태그로 해석되어 스크립트가 실행됨
    • textContent 로 설정하면 문자열 그대로 표시됨
#코드 src/main/resources/static/boards/list.html (일부)
// 사용자가 입력한 문자열은 textContent 로 설정한다 (HTML 태그가 실행되지 않게)
tr.querySelector('a').textContent = board.title;    // 제목 칸
tr.children[2].textContent = board.writer;          // 작성자 칸

규칙: 사용자가 입력한 값은 textContent 로 설정함. innerHTML 은 개발자가 직접 작성한 고정 HTML 에만 사용

React, Vue 는 기본으로 문자열을 이스케이프 처리하지만 원리는 같음. 서버에서도 입력값 검증을 함께 해야 함

10-11 개발자 도구로 확인하기

탭표시 내용사용 시점
Network화면이 보낸 요청과 받은 응답 (주소, 메서드, 상태 코드, JSON)목록이 표시되지 않을 때 API 응답이 404·500 인지 확인
ConsoleJavaScript 오류, console.log 출력화면 코드에서 오류가 발생했는지 확인
Elements현재 DOM 구조와 적용된 CSSTailwind 클래스가 제대로 적용되었는지 확인
  • F12 (Mac: Cmd + Option + I) 로 개발자 도구를 엶
  • Network 탭을 연 상태에서 새로 고침(F5)해야 요청이 기록됨
  • 요청 항목을 클릭하면 Headers(요청·응답 헤더), Response(응답 본문)를 확인할 수 있음

10-12 핵심 정리

화면 = HTML(구조) + CSS(모양) + JavaScript(동작)

Tailwind 는 유틸리티 클래스를 조합하는 CSS 프레임워크. 최근 신규 서비스에서 많이 사용함

fetch 는 API 를 비동기로 호출함. then 또는 async / await 로 응답을 처리함

JavaScript 는 DOM 을 변경해 화면을 갱신함

사용자 입력은 textContent 로 설정해 XSS 를 방지함

화면이 이상하면 개발자 도구 Network·Console 부터 확인

10-13 확인 문제

  1. HTML, CSS, JavaScript 의 역할을 각각 쓰시오.
    • 답: 구조·내용, 모양, 동작(서버 호출, 화면 변경)
  2. Bootstrap 과 Tailwind CSS 의 방식 차이를 쓰시오.
    • 답: Bootstrap 은 완성된 컴포넌트 클래스를 사용하고, Tailwind 는 단일 기능 유틸리티 클래스를 조합해 직접 디자인함
  3. 동기와 비동기의 차이를 fetch 예로 설명하시오.
    • 답: 동기는 응답을 받을 때까지 멈추고, 비동기(fetch)는 요청을 보낸 뒤 다른 작업을 하다가 응답이 도착하면 then 으로 처리함
  4. textContent 와 innerHTML 의 차이와, 사용자 입력에 textContent 를 쓰는 이유는?
    • 답: textContent 는 값을 텍스트로, innerHTML 은 HTML 로 해석해 설정함. 사용자 입력을 HTML 로 해석하면 XSS 공격 스크립트가 실행될 수 있음
  5. 목록 화면이 비어 있을 때 원인을 찾는 순서를 쓰시오.
    • 답: 개발자 도구 Network 에서 /api/boards 요청의 상태 코드와 응답 확인, Console 에서 JavaScript 오류 확인, 서버 로그 확인

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색