Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

승띵이의 개발일지

[Spring Boot] 게시판 만들기 1(feat. CKEditor5) 본문

언어/Spring Boot

[Spring Boot] 게시판 만들기 1(feat. CKEditor5)

승띵이 2022. 11. 16. 11:45
게시판 만들기

 

오늘은 페브리즈 페이지에 게시판 기능을 구현해 보려고 한다. 

 

게시판은 크게 공지사항, 자유게시판, Q&A 3개의 게시판으로 나누어 구현해 보려고 한다.

 

오늘도 고고고~

 

CKEditor

 

CKEditor는 이지윅 에디터로써 'WYSIWYG'는  What You See Is What You Get의 준말로써 '보이는 대로 얻는다'라는 의미를 가지고 있다. 

 

HTML처럼 따로 CSS를 적용하여 디자인을 변경하는 것이 아니라 문서 편집 과정에서 변경하는 방식을 의미한다.

 

본 포스팅에서도 CKEditor를 사용하여 게시판 글쓰기 기능을 구현해 보려고 한다.

 

 

결과

 

글쓰기 페이지

 

CKEditor를 활용하여 textarea 부분을 위 사진과 같은 형태로 지정하였다.

 

제목, 내용이 공란일시 경고 문구 등장

 

돌아가기 버튼 클릭 시 전 페이지로 돌아가기

 

 

HTML & CSS

 

HTML과 CSS를 활용하여 대제목과 제목, 내용을 담을 수 있는 form을 생성한다. 

 

코드는 생략.

 

Javascript

 

const form = window.document.getElementById('form')

const Warning = {
    getElementById: () => form.querySelector('[rel="warningRow"]'),
    show: (text) => {
        const warningRow = Warning.getElementById();
        warningRow.querySelector('.text').innerText = text;
        warningRow.classList.add('visible');

    },
    hide: () => Warning.getElementById().classList.remove('visible')
};

let editor;	
ClassicEditor
    .create(form['content'])
    .then( e => editor = e );  //e는 에디터 전체를 의미

form['back'].addEventListener('click', () => window.history.length < 2 ? window.close() : window.history.back());
// 뒤로 갈 수 있으면 뒤로가고 아니면 창 끈다

form.onsubmit = e => {
    e.preventDefault();
    Warning.hide();

    if (form['title'].value === '') {
        Warning.show('제목을 입력해주세요.');
        form['title'].focus();
        return false;
    }
    if (editor.getData() === '') {
        Warning.show('제목을 입력해주세요.');
        editor.focus();
        return false;
    }
}

 

JS를 활용해 textarea 태그를 ckeditor로 설정 및 뒤로가기, 공란 시 경고문구 출력 기능 구현하였다. 

 

 

DB

 

create schema study_bbs; //study_bbs 스키마 생성

create table study_bbs.boards	//게시판 테이블
(
    `id`   varchar(10)  not null,
    `text` varchar(100) not null,
    constraint primary key (`id`)
);

insert into study_bbs.boards(`id`, `text`) //board 값 insert
values ('free', '자유게시판'),
       ('notice', '공지사항'),
       ('qna', 'QNA');

create table study_bbs.article	//게시글 테이블 
(
    `index`       int unsigned   not null auto_increment,
    `user_email`  varchar(50)    not null,
    `board_id`    varchar(10)    not null,
    `title`       varchar(100)   not null,
    `content`     varchar(10000) not null,
    `view`        int unsigned   not null default 0,
    `written_on`  datetime       not null default now(),
    `modified_on` datetime       not null default now(),
    constraint primary key (`index`),
    constraint foreign key (`user_email`) references study_member.users (`email`)
        on delete cascade
        on update cascade,
    constraint foreign key (`board_id`) references study_bbs.boards (`id`)
        on delete cascade
        on update cascade
);

create table study_bbs.article_like	//게시글 좋아요 테이블 
(
    `user_email`    varchar(50)  not null,
    `article_index` int unsigned not null,
    `created_on`    datetime     not null default now(),
    constraint primary key (`user_email`, `article_index`),
    constraint foreign key (`user_email`) references study_member.users (`email`)
        on delete cascade
        on update cascade,
    constraint foreign key (`article_index`) references study_bbs.article (`index`)
        on delete cascade
        on update cascade
);

create table study_bbs.comment_like	//댓글 좋아요 테이블
(
    `user_email`    varchar(50)  not null,
    `comment_index` int unsigned not null,
    `created_on`    datetime     not null default now(),
    constraint primary key (`user_email`, `comment_index`),
    constraint foreign key (`user_email`) references study_member.users (`email`)
        on delete cascade
        on update cascade,
    constraint foreign key (`comment_index`) references study_bbs.comments (`index`)
        on delete cascade
        on update cascade
);

create table study_bbs.comments	//댓글 테이블 
(
    `index`         int unsigned  not null auto_increment,
    `comment_index` int unsigned  null,
    `user_email`    varchar(50)   not null,
    `article_index` int unsigned  not null,
    `content`       varchar(1000) not null,
    `written_on`    datetime      not null default now(),
    constraint primary key (`index`),
    constraint foreign key (`comment_index`) references study_bbs.comments (`index`)
        on delete cascade
        on update cascade,
    constraint foreign key (`user_email`) references study_member.users (`email`)
        on delete cascade
        on update cascade,
    constraint foreign key (`article_index`) references study_bbs.article (`index`)
        on delete cascade
        on update cascade
)

 

 

BbsController

 

@Controller(value = "com.smchoi.studymemberbbs.controllers.BbsController")
@RequestMapping(value = "/bbs")
public class BbsController {
    @RequestMapping(value = "write",
            method = RequestMethod.GET,
            produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView getWrite(@SessionAttribute(value = "user", required = false) UserEntity user) {
        // login 에서 setAttribute 값을 가져옴. 세션에서 가져왔다는 뜻
        // required 가 true 이면 값이 무조건 존재하여야하지만(없으면 400 오류) false 인 경우 값이 없어도 null 값으로 처리가 된다.
        ModelAndView modelAndView;


        if (user == null) { // 로그인 확인 작업. 해당 user 는 Session 에서 가져온 값이다.
            modelAndView = new ModelAndView("redirect:/member/login");
        } else {
            modelAndView = new ModelAndView("bbs/write");
            
        return modelAndView;
    }
}

 

BbsController를 생성하여 @RequestMappgin을 "/bbs"로 설정한 후 ModelAndView getWrite()의 @RequestMapping을 value는 "write", 방식은 GET 방식, produce는 HTML 형태로 지정해 주었다. 

 

getWrite() 매개변수를 @SessionAttribute("user", required = false) UserEntity user로 설정해 주었다.

이것의 의미는 login에서 setAttribute 값을 가져온다는 것을 뜻한다. 

 

required가 true이면 값이 무조건 존재해야만 하지만 false인 경우 값이 없어도 null 값을 받아올 수 있다.

만일, required가 true일 때 값이 없다면 404 Not Found Error가 발생하게 된다. 

 

본 게시판에서 비회원의 글 작성을 허용하지 않으려고 한다. 사용자가 서버의 DB에 등록된 회원으로 로그인 상태라면 글 작성이 가능하게 하려고 한다. 

 

그러기 위해 매개변수로 받아온 세션 어노테이션의 user가 로그인 상태인지 확인하는 작업을 수행하였다. 

 

만일 user가 null이라면 이것은 로그인 상태가 아닌 상태임으로 login 창으로 redirect 시켜준다.

아닐 경우, 글 작성 페이지로 넘어가도록 처리하였다.

Comments