6. 게시글 등록 - 스프링부트(SpringBoot)

Haeun Shin·2021년 1월 27일
0

스프링 부트

목록 보기
6/10
post-thumbnail

0. thymeleaf layout dialect 사용하기

  1. build.gradle에 implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' 추가

  1. Gradle - Refresh Gradle Project

Refresh 후 등록한 jar가 초기화된다면 여기 참고




1. Service

1. BoardService.java

  • src/main/java/service/BoardService.java(인터페이스)
import com.board.domain.BoardDTO;

public interface BoardService {
	// 게시글 등록
	public boolean registerBoard(BoardDTO params);
}

2. BoardServiceImpl.java

  • src/main/java/service/BoardServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.board.domain.BoardDTO;
import com.board.mapper.BoardMapper;

@Service
public class BoardServiceImpl implements BoardService{
	
	@Autowired
	private BoardMapper boardMapper;
	
	@Override
	public boolean registerBoard(BoardDTO params) {
		int queryResult = 0;
		
		// 쿼리가 정상적으로 실행되면 1을 반환함.
		queryResult = boardMapper.insertBoard(params);
		
		// 정상적으로 실행되면 true, 아니면 false
		return (queryResult == 1) ? true : false;
	}
}




2. Controller

BoardController.java

  • src/main/java/controller/BoardController.java
package com.board.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.board.domain.BoardDTO;
import com.board.service.BoardService;

@Controller
public class BoardController {
	
	@Autowired
	private BoardService boardService;
	
	// 게시글 작성 GET
	@GetMapping(value = "/board/write.do")
	public String openBoardWrite(@RequestParam(value = "idx", required = false) Long idx, Model model) {
		
		model.addAttribute("board", new BoardDTO());

		return "board/write";
	}
	
	// 게시글 작성 POST
	@PostMapping(value = "/board/register.do")
	public String registerBoard(final BoardDTO params) {
		try {
			boolean isRegistered = boardService.registerBoard(params);
			if (isRegistered == false) {
				// TODO => 게시글 등록에 실패하였다는 메시지를 전달
			}
		} catch (DataAccessException e) {
			// TODO => 데이터베이스 처리 과정에 문제가 발생하였다는 메시지를 전달

		} catch (Exception e) {
			// TODO => 시스템에 문제가 발생하였다는 메시지를 전달
		}

		return "redirect:/board/list.do";
	}
}

원래는 @RequestMapping(value = "...", method = RequestMethod.XXX) 이렇게 사용했었지만, 스프링 4.3부터는 @GetMapping, @PostMapping 등 요청 메서드의 타입별로 매핑을 처리할 수 있는 애너테이션이 추가되었다.




3. View

1. write.html

  • src/main/resources/templates/board/write.html
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="board/layout/basic">
	<th:block layout:fragment="title">
		<title>thiThe page is a write page</title>
	</th:block>

	<th:block layout:fragment="content">
		<div class="card-content">
			<form class="form-horizontal" th:action="@{/board/register.do}" th:object="${board}" method="post" onsubmit="return registerBoard(this)">
				<!--/* update의 경우 서버로 전달할 게시글 번호 (PK) */-->
				<input type="hidden" th:if="*{idx != null and idx > 0}" th:field="*{idx}" />

				<div class="form-group">
					<label for="noticeYn" class="col-sm-2 control-label">공지글 설정</label>
					<div class="col-sm-10" style="margin-top: 10px;">
						<input type="checkbox" th:value="*{noticeYn}" id="noticeYn" name="noticeYn" th:checked="*{#strings.equals( noticeYn, 'Y' )}" />
					</div>
				</div>

				<div class="form-group">
					<label for="secretYn" class="col-sm-2 control-label">비밀글 설정</label>
					<div class="col-sm-10" style="margin-top: 10px;">
						<input type="checkbox" th:value="*{secretYn}" id="secretYn" name="secretYn" th:checked="*{#strings.equals( secretYn, 'Y' )}" />
					</div>
				</div>

				<div class="form-group">
					<label for="title" class="col-sm-2 control-label">제목</label>
					<div class="col-sm-10">
						<input type="text" th:field="*{title}" class="form-control" placeholder="제목을 입력해 주세요." />
					</div>
				</div>

				<div class="form-group">
					<label for="writer" class="col-sm-2 control-label">이름</label>
					<div class="col-sm-10">
						<input type="text" th:field="*{writer}" class="form-control" placeholder="이름을 입력해 주세요." />
					</div>
				</div>

				<div class="form-group">
					<label for="content" class="col-sm-2 control-label">내용</label>
					<div class="col-sm-10">
						<textarea th:field="*{content}" class="form-control" placeholder="내용을 입력해 주세요."></textarea>
					</div>
				</div>

				<div class="btn_wrap text-center">
					<a th:href="@{/board/list.do}" class="btn btn-default waves-effect waves-light">뒤로가기</a>
					<button type="submit" class="btn btn-primary waves-effect waves-light">저장하기</button>
				</div>
			</form>
		</div>
		<!-- /.card-content -->
	</th:block>

	<th:block layout:fragment="script">
		<script th:inline="javascript">
			/*<![CDATA[*/

			function registerBoard(form) {

				form.noticeYn.value = form.noticeYn.checked == false ? 'N' : 'Y';
				form.secretYn.value = form.secretYn.checked == false ? 'N' : 'Y';

				var result = (
						   isValid(form.title, "제목", null, null)
						&& isValid(form.writer, "이름", null, null)
						&& isValid(form.content, "내용", null, null)
				);

				if ( result == false ) {
					return false;
				}
			}
			/*[- end of function -]*/

			/*]]>*/
		</script>
	</th:block>
</html>

2. 부트스트랩 적용

  1. 파일 다운
    파일 다운로드하기


  2. src/main/resources에 copy




3. body.html, header.html

  • templates/board/fragments/body.html, header.html
<!-- header.html -->
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
	<head th:fragment="main-head">
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
		<meta name="description" content="">
		<meta name="author" content="">

		<th:block layout:fragment="title"></th:block>

		<link rel="stylesheet" th:href="@{/css/style.css}" />
		<link rel="stylesheet" th:href="@{/plugin/mCustomScrollbar/jquery.mCustomScrollbar.min.css}" />

		<th:block layout:fragment="add-css"></th:block>
	</head>
</html>
<!-- body.html -->
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
	<body th:fragment="main-body">
		<div class="fixed-navbar">
			<div class="pull-left">
				<h1 class="page-title">Board</h1>
			</div>
		</div>
		<!-- /.fixed-navbar -->

		<div id="wrapper">
			<div class="main-content">
				<div class="row row-inline-block small-spacing">
					<div class="col-xs-12">
						<div class="box-content">
							<div class="clearfix">
								<h4 class="box-title pull-left"></h4>
								<!-- /.box-title -->
	
								<th:block layout:fragment="search"></th:block>
	
							</div>
							<!-- //.clearfix -->
	
							<th:block layout:fragment="content"></th:block>
	
							<th:block layout:fragment="paging"></th:block>
						</div>
						<!-- /.box-content -->
						
						<th:block layout:fragment="add-content"></th:block>

					</div>
					<!-- /.col-xs-12 -->
				</div>
				<!-- /.row row-inline-block small-spacing -->
				<footer class="footer">
					<ul class="list-inline">
						<li>2016 © NinjaAdmin.</li>
					</ul>
				</footer>
			</div>
			<!-- /.main-content -->
		</div>
		<!-- /#wrapper -->

		<script th:src="@{/scripts/jquery.min.js}"></script>
		<script th:src="@{/plugin/bootstrap/js/bootstrap.min.js}"></script>
		<script th:src="@{/plugin/mCustomScrollbar/jquery.mCustomScrollbar.concat.min.js}"></script>

		<script th:src="@{/scripts/main.js}"></script>
		<script th:src="@{/scripts/common.js}"></script>

		<th:block layout:fragment="script"></th:block>
	</body>
</html>

4. basic.html

  • templates/board/layout/basic.html
<!DOCTYPE html>
<html lang="ko" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
	<head th:replace="board/fragments/header :: main-head"> </head>
	<body th:replace="board/fragments/body :: main-body"> </body>
</html>



4. 연결확인

1. 연결

  • Run As - Spring Boot App

2. 웹에 접속

  • 웹에서 localhost:8080/board/write.do 입력 후 내용 입력하고 저장

3. 결과 확인

  • 아직 저장 후의 페이지를 지정하지 않았기 때문에 오류나는 게 정상

4. DB 확인

  • DB에서 Insert 확인하면 끝






JAR 초기화되지 않게 적용하기

1. 프로젝트에 libs 폴더 생성 후 jar 파일 넣기


2. build.gradleimplementation files('lib/jar파일이름') 넣기


3. Gradle - Refresh Gradle Project


4. Project and External Dependencies 확인


0개의 댓글