1탄에서는 Smart Editor 2.0 버전을 설치하여 단순 적용해보았다. 이번에는 MySQL과 Spring Boot을 연동하여 작성한 게시글을 DB에 전송해보려고 한다. 블로그용으로 새로 샘플을 만들고 JPA로 바꾸다보니 일이 생각보다 커지는건 기분탓이겠지ㅎㅎㅎ..
[Naver] SmartEditor 2.0으로 게시판만들기 - 1. 에디터 적용
다시 생각해도 힘든 기억이 떠오르는 네이버 스마트 에디터 적용기... 개발하면서 이것만큼은 무조건 블로그에 정리하겠다고 다짐했다. 프로젝트를 마치고 이제서야 겨우 정리할 시간이 생겨
beforb.tistory.com
* 목차
1. 스마트 에디터 2.0으로 게시판 만들기 - 스마트에디터 글 작성하기(Frontend)
2. 스마트 에디터 2.0으로 게시판 만들기 - Spring Boot/DB 연동하기(Backend)
3. 스마트 에디터 2.0으로 게시판 만들기 - 싱글사진 업로드하기
4. 스마트 에디터 2.0으로 게시판 만들기 - 멀티사진 업로드하기
5. 스마트 에디터 2.0으로 게시판 만들기 - 동영상 올리기
1. DB 세팅하기
resources/application.properties 설정
MySQL에서 사용할 database정보를 연결해준다.
# DB - MySQL 설정
spring.datasource.url=jdbc:mysql://localhost:3306/sujinhope?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=아이디
spring.datasource.password=비밀번호
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA 설정
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
server.address=localhost
server.port=8080
# 변경시 자동 restart
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true
# Thymeleaf 설정
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=file:src/main/resources/templates/
2. DTO, Controller, Service, Repository 생성하기
1) model/Post.java, model/BaseTime.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity(name = "post")
public class Post extends BaseTime {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long postNo;
    
    @Column
    private String title;
    @Column(columnDefinition = "TEXT")
    private String content;
    
}
게시글을 처음 작성한 시간과 수정할 때 자동으로 시간을 입력할 수 있도록 별도로 BaseTime을 생성하고 Post에서 상속받도록 하였다.
package com.example.spring.thymeleaf.model;
import java.time.LocalDateTime;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.Getter;
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTime {
    @CreatedDate
    private LocalDateTime createdAt;
    @LastModifiedDate
    private LocalDateTime modifiedAt;
    
}
위의 Auto 기능을 사용하려면 @SpringBootApplication이 붙어있는 메인 메소드에 추가로 @EnableJpaAuditing 태그를 붙여주어야 한다. JPA의 자세한 기능들은 따로 포스팅을 해보려고 한다.
package com.example.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
2) controller/PostController.java
package com.example.spring.thymeleaf.controller;
import javax.servlet.http.HttpServletRequest;
import com.example.spring.thymeleaf.model.Post;
import com.example.spring.thymeleaf.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
@Controller
@RequestMapping("smarteditor")
public class EditorController {
    @Autowired
    PostService postService;
    @RequestMapping("/")
    public ModelAndView insertEditor(HttpServletRequest req, ModelMap model) throws Exception {
        ModelAndView mav = new ModelAndView("smarteditor/newPost");
        return mav;
    }
    @RequestMapping("/savePost")
    public View savePost(HttpServletRequest req, Post post) throws Exception {
        ModelMap model = new ModelMap();
        model.addAttribute("result", HttpStatus.OK);
        postService.savePost(post);
        return new MappingJackson2JsonView();
    }
    
}
3-1) service/PostService.java
package com.example.spring.thymeleaf.service;
// 생략
public interface PostService {
    
    public void savePost(Post post) throws SQLException;
}
3-2) service/PostServiceImpl.java
package com.example.spring.thymeleaf.service.impl;
// 생략
@Service
public class PostServiceImpl implements PostService {
    @Autowired
    PostRepository postRepository;
    @Override
    public void savePost(Post post) throws SQLException {
        postRepository.save(post);
    }
    
}
4) repository/PostRepository.java
package com.example.spring.thymeleaf.repository;
@Repository
public interface PostRepository extends JpaRepository<Post, String> {
    // JPA에서 기본으로 제공되는 메소드는 선언없이 사용 가능하다.
}
3. ajax로 내용 전송하기
백엔드 구성을 모두 끝냈으니 이제 자바스크립트에서 게시글 내용을 전송하면 된다. 1탄에서 했던 코드에 ajax로 서버에 전송하는 부분을 덧붙였다.
savePost = function() {
      oEditors.getById["editorTxt"].exec("UPDATE_CONTENTS_FIELD", [])
      let content = document.getElementById("editorTxt").value
      if(content == '') {
        alert("내용을 입력해주세요.")
        oEditors.getById["editorTxt"].exec("FOCUS")
        return
      } else {
        let post = {
          title: $("#title")[0].value
          , content: content
        }
        $.ajax({
          url: "/smarteditor/savePost"
          , data: post
          , success: function(data) {
            console.log('success')
            alert('저장하였습니다.')
          }
          , error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR)
            alert('오류가 발생하였습니다.')
          }
        })
      }
    }
4. 결과 화면

DB 결과

'프로젝트' 카테고리의 다른 글
| [AWS] AWS Parameter Store 조회 안될 때(Parameter 조회하는법) (0) | 2022.06.06 | 
|---|---|
| [AWS S3] S3에 업로드한 이미지가 열리지 않고 다운로드 될 때 (0) | 2022.06.03 | 
| [VSCode] terminal color setting (+Spring error/warn 색깔 구분하기!) (1) | 2022.05.05 | 
| [Naver] SmartEditor 2.0으로 게시판만들기 - 3. 싱글사진 업로드하기 (3) | 2021.11.09 | 
| [Project] Naver SmartEditor 2.0으로 게시판만들기 - 1. 에디터 적용 (5) | 2021.11.04 | 
										
									
										
									
										
									
										
									
댓글