관리 메뉴

거니의 velog

231216_SPRING CRUD 보강 6 본문

대덕인재개발원_웹기반 애플리케이션

231216_SPRING CRUD 보강 6

Unlimited00 2023. 12. 16. 12:09

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div class="container-fluid px-2 px-md-4">
	<div class="page-header min-height-300 border-radius-xl mt-4"
		style="background-image: url('https://images.unsplash.com/photo-1531512073830-ba890ca4eba2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80');">
		<span class="mask  bg-gradient-secondary opacity-6"></span>
	</div>
	<form class="card card-body mx-3 mx-md-4 mt-n6" id="boardForm" method="post" action="/board/insert.do" enctype="multipart/form-data">
		<div class="row gx-4 mb-2">
			<div class="col-md-12">
				<div class="input-group input-group-outline mb-4">
					<input type="text" class="form-control" id="boTitle" name="boTitle" value="" placeholder="제목을 입력해주세요.">
				</div>
			</div>
			<div class="col-md-12">
				<div class="input-group input-group-outline mb-4">
					<textarea class="form-control" cols="50" rows="20" id="boContent" name="boContent"></textarea>
				</div>
			</div>
			<div class="col-md-12">
				<div class="input-group input-group-outline mb-4">
					<input type="file" class="form-control" id="boFile" name="boFile" multiple="multiple" />
				</div>
			</div>
			<div class="col-md-12"><br/></div>
			<div class="col-md-12">
				<div class="row">
					<div class="col-md-2">
						<div class="card shadow-lg">
							<div class="card-header mt-n4 mx-3 p-0 bg-transparent position-relative z-index-2">
								<a class="d-block blur-shadow-image text-center"> 
									<img src="${pageContext.request.contextPath}/resources/assets/img/icons/img.jpg" alt="img-blur-shadow" class="img-fluid shadow border-radius-lg">
								</a>
								<div class="colored-shadow" style="background-image: url(&quot;https://images.unsplash.com/photo-1536321115970-5dfa13356211?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;ixlib=rb-1.2.1&amp;auto=format&amp;fit=crop&amp;w=934&amp;q=80&quot;);"></div>
							</div>
							<div class="card-body text-center bg-white border-radius-lg p-3 pt-0">
								<h6 class="mt-3 mb-1 d-md-block d-none">
									파일명을 입력하세요!
								</h6>
								<p class="mb-0 text-xs font-weight-bolder text-info text-uppercase">
									<button type="button" class="btn btn-primary fileDelete">delete</button>
								</p>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="col-md-12">
				<button type="button" class="btn btn-outline-primary" id="insertBtn">등록</button>
				<button type="button" class="btn btn-outline-danger" onclick="javascript:location.href='/board/detail.do'">취소</button>
				<button type="button" class="btn btn-outline-info" onclick="javascript:location.href='/board/list.do'">목록</button>
			</div>
		</div>
	</form>
</div>
<script>
	$(function(){
		CKEDITOR.replace("boContent");
		CKEDITOR.config.width="100%";
		CKEDITOR.config.height="500px";
		
		var insertBtn = $("#insertBtn");
		var boardForm = $("#boardForm");
		
		insertBtn.on("click", function(){
			var title = $("#boTitle").val();
			var content = CKEDITOR.instances.boContent.getData();
			
			if(!title) {
				alert("제목을 입력해 주세요.");
				return false;
			}
			if(!content) {
				content("내용을 입력해 주세요.");
				return false;
			}
			
			boardForm.submit();
		});
	});
</script>
package kr.or.ddit.controller.board;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import kr.or.ddit.ServiceResult;
import kr.or.ddit.service.IBoardService;
import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.MemberVO;
import kr.or.ddit.vo.PaginationInfoVO;

@Controller
@RequestMapping("/board")
public class BoardController {
	
	@Inject
	private IBoardService boardService;
	
	@RequestMapping(value="/list.do", method = RequestMethod.GET)
	public String boardList(
			@RequestParam(name = "page", required = false, defaultValue = "1") int currentPage,
			@RequestParam(required = false, defaultValue = "title") String searchType,
			@RequestParam(required = false) String searchWord,
			Model model
			) {
		PaginationInfoVO<BoardVO> pagingVO = new PaginationInfoVO<BoardVO>();
		
		// 검색을 진행
		if(StringUtils.isNotBlank(searchWord)) {
			pagingVO.setSearchType(searchType);
			pagingVO.setSearchWord(searchWord);
			model.addAttribute("searchType", searchType);
			model.addAttribute("searchWord", searchWord);
		}
		
		pagingVO.setCurrentPage(currentPage); // startRow, endRow, startPage, endPage 가 결정
		int totalRecord = boardService.selectBoardCount(pagingVO); // totalRecord(총 게시글 수)
		
		pagingVO.setTotalRecord(totalRecord); // totalPage 결정
		List<BoardVO> dataList = boardService.selectBoardList(pagingVO);
		pagingVO.setDataList(dataList);
		
		model.addAttribute("pagingVO", pagingVO);
		
		return "board/list";
	}
	
	@RequestMapping(value="/detail.do", method = RequestMethod.GET)
	public String boardDetail(int boNo, Model model) {
		BoardVO boardVO = boardService.selectBoard(boNo);
		model.addAttribute("board", boardVO);
		return "board/detail";
	}
	
	@RequestMapping(value="/form.do", method = RequestMethod.GET)
	public String boardForm() {
		return "board/form";
	}
	
	@RequestMapping(value = "/insert.do", method = RequestMethod.POST)
	public String boardInsert(
			HttpServletRequest req,
			BoardVO boardVO, 
			Model model
			) throws Exception {
		
		String goPage = "";
		
		Map<String, String> errors = new HashMap<String, String>();
		if(StringUtils.isBlank(boardVO.getBoTitle())) {
			errors.put("boTitle", "제목을 입력해 주세요.");
		}
		if(StringUtils.isBlank(boardVO.getBoContent())) {
			errors.put("boContent", "내용을 입력해 주세요.");
		}
		if(errors.size() > 0) {
			model.addAttribute("errors", errors);
			model.addAttribute("boardVO", boardVO);
			goPage = "board/form";
		}else {
			HttpSession session = req.getSession();
			MemberVO memberVO = (MemberVO) session.getAttribute("sessionInfo");
			boardVO.setBoWriter(memberVO.getMemId()); // 로그인 한 사용자의 id로 작성자를 설정
			ServiceResult result = boardService.insertBoard(req, boardVO);
			
			if(result.equals(ServiceResult.OK)) {
				goPage = "redirect:/board/detail.do?boNo=" + boardVO.getBoNo();
			}else {
				model.addAttribute("message", "서버 에러, 다시 시도해주세요!");
				goPage = "board/form";
			}
		}
		
		return goPage;
		
	}
	
}
package kr.or.ddit.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import kr.or.ddit.ServiceResult;
import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.PaginationInfoVO;

public interface IBoardService {

	public int selectBoardCount(PaginationInfoVO<BoardVO> pagingVO);
	public List<BoardVO> selectBoardList(PaginationInfoVO<BoardVO> pagingVO);
	public BoardVO selectBoard(int boNo);
	public ServiceResult insertBoard(HttpServletRequest req, BoardVO boardVO) throws Exception;

}
package kr.or.ddit.service.impl;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import kr.or.ddit.ServiceResult;
import kr.or.ddit.controller.util.FileUploadUtils;
import kr.or.ddit.mapper.IBoardMapper;
import kr.or.ddit.service.IBoardService;
import kr.or.ddit.vo.BoardFileVO;
import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.PaginationInfoVO;

@Service
public class BoardServiceImpl implements IBoardService {

	@Inject
	private IBoardMapper boardMapper;
	
	@Override
	public int selectBoardCount(PaginationInfoVO<BoardVO> pagingVO) {
		return boardMapper.selectBoardCount(pagingVO);
	}

	@Override
	public List<BoardVO> selectBoardList(PaginationInfoVO<BoardVO> pagingVO) {
		return boardMapper.selectBoardList(pagingVO);
	}

	@Override
	public BoardVO selectBoard(int boNo) {
		boardMapper.incrementhit(boNo); // 조회수 증가
		return boardMapper.selectBoard(boNo);
	}

	@Override
	public ServiceResult insertBoard(HttpServletRequest req, BoardVO boardVO) throws Exception {
		ServiceResult result = null;
		
		int status = boardMapper.insertBoard(boardVO);
		if(status > 0) {
			List<BoardFileVO> boardFileList = boardVO.getBoardFileList();
			FileUploadUtils.boardFileUpload(boardFileList, boardVO.getBoNo(), req, boardMapper);
			result = ServiceResult.OK;
		}else {
			result = ServiceResult.FAILED;
		}
		
		return result;
	}

}
package kr.or.ddit.mapper;

import java.util.List;

import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.PaginationInfoVO;

public interface IBoardMapper {

	public int selectBoardCount(PaginationInfoVO<BoardVO> pagingVO);
	public List<BoardVO> selectBoardList(PaginationInfoVO<BoardVO> pagingVO);
	public void incrementhit(int boNo);
	public BoardVO selectBoard(int boNo);
	public int insertBoard(BoardVO boardVO);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.or.ddit.mapper.IBoardMapper">

	<sql id="boardSearch">
		<if test="searchType != null and searchType == 'title'">
			and (bo_title like '%' || #{searchWord} || '%')
		</if>
		<if test="searchType != null and searchType == 'writer'">
			and (bo_writer like '%' || #{searchWord} || '%')
		</if>
		<if test="searchType != null and searchType == 'both'">
			and (bo_title like '%' || #{searchWord} || '%')
			and (bo_writer like '%' || #{searchWord} || '%')
		</if>
	</sql>

	<select id="selectBoardCount" parameterType="pagingVO" resultType="int">
		select count(bo_no) 
		from board 
		where 1=1 
		<include refid="boardSearch" />
	</select>
	
	<select id="selectBoardList" parameterType="pagingVO" resultType="boardVO">
		select 
			b.* 
		from (
			select 
				a.*, row_number() over (order by a.bo_no desc) rnum
			from (
				select 
					bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
				from board 
				where 1=1 
				<include refid="boardSearch" /> 
				order by bo_no desc
			) a
		) b
		<![CDATA[
			where b.rnum >= #{startRow} and b.rnum <= #{endRow}
		]]>
	</select>
	
	<update id="incrementhit" parameterType="int">
		update board 
		set 
			bo_hit = bo_hit + 1 
		where bo_no = ${boNo}
	</update>
	
	<select id="selectBoard" parameterType="int" resultType="boardVO">
		select 
			bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
		from board 
		where bo_no = ${boNo}
	</select>
	
	<insert id="insertBoard" parameterType="boardVO" useGeneratedKeys="true">
		<selectKey keyProperty="boNo" order="BEFORE" resultType="int">
			select seq_board.nextval from dual
		</selectKey>
		insert into board (
			bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
		) values (
			#{boNo}, #{boTitle}, #{boContent}, #{boWriter}, sysdate, 0
		)
	</insert>

</mapper>

package kr.or.ddit.controller.util;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import kr.or.ddit.mapper.IBoardMapper;
import kr.or.ddit.vo.BoardFileVO;

public class FileUploadUtils {

	public static void boardFileUpload(List<BoardFileVO> boardFileList, int boNo, HttpServletRequest req,
			IBoardMapper boardMapper) throws Exception {

		String savePath = "/resources/board/";
		
		if(boardFileList != null && boardFileList.size() > 0) {
			for(BoardFileVO boardFileVO : boardFileList) {
				String saveName = UUID.randomUUID().toString();
				saveName = saveName + "_" + boardFileVO.getFileName().replaceAll(" ", "_");
				
				// 업로드 서버경로 + /resources/board/10
				String saveLocate = req.getServletContext().getRealPath(savePath + boNo);
				File file = new File(saveLocate);
				if(!file.exists()) {
					file.mkdirs();
				}
				
				// saveLocate + "/" + UUID_원본파일명
				saveLocate += "/" + saveName;
				boardFileVO.setBoNo(boNo); // 게시글 번호 설정
				boardFileVO.setFileSavepath(saveLocate); // 파일 업로드 경로 설정
				boardMapper.insertBoardFile(boardFileVO); // 공지사항 게시글 파일 데이터 추가
				
				File saveFile = new File(saveLocate);
				boardFileVO.getItem().transferTo(saveFile); // 파일 복사
			}
		}
		
	}
	
}
package kr.or.ddit.mapper;

import java.util.List;

import kr.or.ddit.vo.BoardFileVO;
import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.PaginationInfoVO;

public interface IBoardMapper {

	public int selectBoardCount(PaginationInfoVO<BoardVO> pagingVO);
	public List<BoardVO> selectBoardList(PaginationInfoVO<BoardVO> pagingVO);
	public void incrementhit(int boNo);
	public BoardVO selectBoard(int boNo);
	public int insertBoard(BoardVO boardVO);
	public void insertBoardFile(BoardFileVO boardFileVO);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.or.ddit.mapper.IBoardMapper">

	<sql id="boardSearch">
		<if test="searchType != null and searchType == 'title'">
			and (bo_title like '%' || #{searchWord} || '%')
		</if>
		<if test="searchType != null and searchType == 'writer'">
			and (bo_writer like '%' || #{searchWord} || '%')
		</if>
		<if test="searchType != null and searchType == 'both'">
			and (bo_title like '%' || #{searchWord} || '%')
			and (bo_writer like '%' || #{searchWord} || '%')
		</if>
	</sql>

	<select id="selectBoardCount" parameterType="pagingVO" resultType="int">
		select count(bo_no) 
		from board 
		where 1=1 
		<include refid="boardSearch" />
	</select>
	
	<select id="selectBoardList" parameterType="pagingVO" resultType="boardVO">
		select 
			b.* 
		from (
			select 
				a.*, row_number() over (order by a.bo_no desc) rnum
			from (
				select 
					bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
				from board 
				where 1=1 
				<include refid="boardSearch" /> 
				order by bo_no desc
			) a
		) b
		<![CDATA[
			where b.rnum >= #{startRow} and b.rnum <= #{endRow}
		]]>
	</select>
	
	<update id="incrementhit" parameterType="int">
		update board 
		set 
			bo_hit = bo_hit + 1 
		where bo_no = #{boNo}
	</update>
	
	<select id="selectBoard" parameterType="int" resultType="boardVO">
		select 
			bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
		from board 
		where bo_no = #{boNo}
	</select>
	
	<insert id="insertBoard" parameterType="boardVO" useGeneratedKeys="true">
		<selectKey keyProperty="boNo" order="BEFORE" resultType="int">
			select seq_board.nextval from dual
		</selectKey>
		insert into board (
			bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit 
		) values (
			#{boNo}, #{boTitle}, #{boContent}, #{boWriter}, sysdate, 0
		)
	</insert>
	
	<insert id="insertBoardFile" parameterType="boardFileVO">
		insert into boardfile (
			file_no, bo_no, file_name, file_size, file_fancysize, file_mime, file_savepath, file_downcount 
		) values (
			seq_boardfile.nextval, #{boNo}, #{fileName}, #{fileSize}, #{fileFancysize}, #{fileMime}, #{fileSavepath}, 0
		)
	</insert>

</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
	</settings>
	
	<typeAliases>
		<typeAlias type="kr.or.ddit.vo.MemberVO" alias="memberVO"/>
		<typeAlias type="kr.or.ddit.vo.BoardVO" alias="boardVO"/>
		<typeAlias type="kr.or.ddit.vo.PaginationInfoVO" alias="pagingVO"/>
		<typeAlias type="kr.or.ddit.vo.BoardFileVO" alias="boardFileVO"/>
	</typeAliases>

</configuration>

 

'대덕인재개발원_웹기반 애플리케이션' 카테고리의 다른 글

231216_SPRING CRUD 보강 8  (0) 2023.12.16
231216_SPRING CRUD 보강 7  (0) 2023.12.16
231216_SPRING CRUD 보강 5  (0) 2023.12.16
231216_SPRING CRUD 보강 4  (0) 2023.12.16
231216_SPRING CRUD 보강 3  (0) 2023.12.16