Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ★ 1. BoardController.java
- package com.finger.spring.board.controller;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- import com.finger.spring.board.dto.BoardDto;
- import com.finger.spring.board.service.BoardService;
- @Controller
- public class BoardController {
- private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
- @Autowired
- BoardService boardService;
- @RequestMapping(value = "/board/insert", method = RequestMethod.POST)
- @ResponseBody
- public int boardInsert(BoardDto dto) {
- logger.debug("/board/insert");
- return boardService.boardInsert(dto);
- }
- @RequestMapping(value = "/board/insertFile", method = RequestMethod.POST)
- @ResponseBody
- public int boardInsertFile(BoardDto dto, MultipartFile file) throws Exception{
- logger.debug("/board/insertFile");
- logger.debug("dto getUserSeq : " + dto.getUserSeq());
- return boardService.boardInsertFile(dto, file);
- }
- @RequestMapping(value = "/board/list", method = RequestMethod.GET)
- @ResponseBody
- public List<BoardDto> boardList(int limit, int offset, String searchWord) {
- logger.debug("/board/list");
- return boardService.boardList(limit, offset, searchWord);
- }
- @RequestMapping(value = "/board/list/totalCnt", method = RequestMethod.GET)
- @ResponseBody
- public int boardListCnt(String searchWord) {
- logger.debug("/board/listTotalCnt");
- return boardService.boardListTotalCnt(searchWord);
- }
- // @RequestMapping(value = "/board/detail", method = RequestMethod.GET)
- // @ResponseBody
- // public BoardDto boardDetail(int boardId) {
- //
- // logger.debug("/board/detail");
- //
- // return boardService.boardDetail(boardId);
- // }
- @RequestMapping(value = "/board/detail", method = RequestMethod.GET)
- @ResponseBody
- public BoardDto boardDetail(int boardId, int userSeq) {
- logger.debug("/board/detail");
- return boardService.boardDetail(boardId, userSeq);
- }
- @RequestMapping(value = "/board/update", method = RequestMethod.POST)
- @ResponseBody
- public int boardUpdate(BoardDto dto) {
- logger.debug("/board/update");
- return boardService.boardUpdate(dto);
- }
- @RequestMapping(value = "/board/updateFile", method = RequestMethod.POST)
- @ResponseBody
- public int boardUpdateFile(BoardDto dto, MultipartFile file) throws Exception{
- logger.debug("/board/updateFile");
- return boardService.boardUpdateFile(dto, file);
- }
- @RequestMapping(value = "/board/delete", method = RequestMethod.POST)
- @ResponseBody
- public int boardDelete(BoardDto dto) {
- logger.debug("/board/delete");
- return boardService.boardDelete(dto);
- }
- //@RequestMapping(value = "/board/test", produces="text/plain;charset=UTF-8", method = RequestMethod.GET)
- @RequestMapping(value = "/board/test", method = RequestMethod.GET)
- @ResponseBody
- public Map<String, Object> boardTest() {
- logger.debug("/board/test");
- String str = "�븞�뀞";
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("msg", str);
- //return "{\"msg\":\"" + str + "\"}";
- return map;
- }
- }
- ★2. BoardDao.java
- package com.finger.spring.board.dao;
- import java.util.List;
- import org.apache.ibatis.annotations.Param;
- import com.finger.spring.board.dto.BoardDto;
- import com.finger.spring.board.dto.BoardFileDto;
- public interface BoardDao {
- public int boardInsert(BoardDto dto);
- public int boardInsertFile(BoardFileDto dto);
- public List<BoardDto> boardList(@Param("limit") int limit, @Param("offset") int offset);
- public int boardListTotalCnt();
- public List<BoardDto> boardListSearchWord(@Param("limit") int limit, @Param("offset") int offset, @Param("searchWord") String searchWord);
- public int boardListSearchWordTotalCnt(@Param("searchWord") String searchWord);
- public BoardDto boardDetail(@Param("boardId") int boardId);
- public List<BoardFileDto> boardDetailFileList(@Param("boardId") int boardId);
- public int boardUpdate(BoardDto dto);
- public List<String> boardDeleteFileUrl(@Param("boardId") int boardId);
- public int boardDelete(BoardDto dto);
- public int boardDeleteFile(@Param("boardId") int boardId);
- public int boardUserReadCnt(@Param("boardId") int boardId, @Param("userSeq") int userSeq);
- public int boardInsertUserRead(@Param("boardId") int boardId, @Param("userSeq") int userSeq);
- public int boardUpdateReadCnt(@Param("boardId") int boardId);
- }
- ★ 3. boardMapper.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.finger.spring.board.dao.BoardDao">
- <insert id="boardInsert" parameterType="com.finger.spring.board.dto.BoardDto" useGeneratedKeys="true" keyProperty="boardId">
- insert into board ( USER_SEQ, TITLE, CONTENT, REG_DT, READ_COUNT )
- values ( #{userSeq}, #{title}, #{content}, now(), 0 );
- </insert>
- <insert id="boardInsertFile" parameterType="com.finger.spring.board.dto.BoardDto">
- insert into board_file ( BOARD_ID, FILE_NAME, FILE_SIZE, FILE_CONTENT_TYPE, FILE_URL )
- values ( #{boardId}, #{fileName}, #{fileSize}, #{fileContentType}, #{fileUrl} );
- </insert>
- <resultMap id="boardMap" type="com.finger.spring.board.dto.BoardDto">
- <result property="boardId" column="board_id" />
- <result property="userSeq" column="user_seq" />
- <result property="userName" column="user_name" />
- <result property="userProfileImageUrl" column="user_profile_image_url" />
- <result property="title" column="title" />
- <result property="content" column="content" />
- <result property="regDt" column="reg_dt" />
- <result property="readCount" column="read_count" />
- </resultMap>
- <select id="boardList" resultMap="boardMap">
- SELECT b.BOARD_ID,
- b.USER_SEQ,
- u.USER_NAME,
- u.USER_PROFILE_IMAGE_URL,
- b.TITLE,
- b.CONTENT,
- b.REG_DT,
- b.READ_COUNT
- FROM board b, user u
- WHERE b.USER_SEQ = u.USER_SEQ
- ORDER BY BOARD_ID DESC
- LIMIT #{limit} OFFSET #{offset}
- </select>
- <select id="boardListSearchWord" resultMap="boardMap">
- SELECT b.BOARD_ID,
- b.USER_SEQ,
- u.USER_NAME,
- u.USER_PROFILE_IMAGE_URL,
- b.TITLE,
- b.CONTENT,
- b.REG_DT,
- b.READ_COUNT
- FROM board b, user u
- WHERE b.USER_SEQ = u.USER_SEQ
- AND TITLE LIKE CONCAT('%', #{searchWord}, '%')
- ORDER BY BOARD_ID DESC
- LIMIT #{limit} OFFSET #{offset}
- </select>
- <select id="boardListTotalCnt" resultType="int">
- SELECT count(*) FROM board
- </select>
- <select id="boardListSearchWordTotalCnt" parameterType="String" resultType="int">
- SELECT count(*) FROM board WHERE TITLE LIKE CONCAT('%', #{searchWord}, '%')
- </select>
- <select id="boardDetail" parameterType="int" resultType="com.finger.spring.board.dto.BoardDto">
- SELECT b.BOARD_ID as boardId,
- b.USER_SEQ as userSeq,
- u.USER_NAME as userName,
- u.USER_PROFILE_IMAGE_URL as userProfileImageUrl,
- b.TITLE as title,
- b.CONTENT as content,
- b.REG_DT as regDt,
- b.READ_COUNT as readCount
- FROM board b, user u
- WHERE b.USER_SEQ = u.USER_SEQ
- AND b.BOARD_ID = #{boardId}
- </select>
- <update id="boardUpdate" parameterType="com.finger.spring.board.dto.BoardDto">
- UPDATE board
- set TITLE = #{title}, CONTENT = #{content}
- WHERE BOARD_ID = #{boardId}
- </update>
- <delete id="boardDeleteFile" parameterType="int">
- DELETE from board_file
- WHERE BOARD_ID = #{boardId}
- </delete>
- <delete id="boardDelete" parameterType="int">
- DELETE from board
- WHERE BOARD_ID = #{boardId}
- </delete>
- <select id="boardUserReadCnt" resultType="int">
- SELECT count(*) FROM board_user_read WHERE board_id = #{boardId} and user_seq = #{userSeq}
- </select>
- <insert id="boardInsertUserRead">
- INSERT INTO board_user_read ( board_id, user_seq ) VALUES ( #{boardId}, #{userSeq} )
- </insert>
- <update id="boardUpdateReadCnt">
- UPDATE board set READ_COUNT = READ_COUNT + 1 WHERE BOARD_ID = #{boardId}
- </update>
- <resultMap id="boardFileMap" type="com.finger.spring.board.dto.BoardFileDto">
- <result property="boardId" column="board_id" />
- <result property="fileId" column="file_id" />
- <result property="fileName" column="file_name" />
- <result property="fileSize" column="file_size" />
- <result property="fileContentType" column="file_content_type" />
- <result property="fileUrl" column="file_url" />
- <result property="regDt" column="reg_dt" />
- </resultMap>
- <select id="boardDetailFileList" resultMap="boardFileMap">
- SELECT BOARD_ID, FILE_ID, FILE_NAME, FILE_SIZE, FILE_CONTENT_TYPE, FILE_URL, REG_DT
- FROM board_file
- WHERE BOARD_ID = #{boardId}
- </select>
- <select id="boardDeleteFileUrl" parameterType="int" resultType="String">
- SELECT file_url
- FROM board_file
- WHERE BOARD_ID = #{boardId}
- </select>
- </mapper>
- ★ 4. BoardDto.java
- package com.finger.spring.board.dto;
- import java.util.Date;
- import java.util.List;
- import com.fasterxml.jackson.annotation.JsonFormat;
- public class BoardDto {
- private int boardId;
- private String userSeq;
- private String userName;
- private String userProfileImageUrl;
- private String title;
- private String content;
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone="Asia/Seoul")
- private Date regDt;
- private int readCount;
- private List<BoardFileDto> fileList;
- public int getBoardId() {
- return boardId;
- }
- public void setBoardId(int boardId) {
- this.boardId = boardId;
- }
- public String getUserSeq() {
- return userSeq;
- }
- public void setUserSeq(String userSeq) {
- this.userSeq = userSeq;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getUserProfileImageUrl() {
- return userProfileImageUrl;
- }
- public void setUserProfileImageUrl(String userProfileImageUrl) {
- if( userProfileImageUrl == null ) {
- this.userProfileImageUrl = "/resources/images/noProfile.png";
- }else {
- this.userProfileImageUrl = userProfileImageUrl;
- }
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getContent() {
- return content;
- }
- public void setContent(String content) {
- this.content = content;
- }
- public Date getRegDt() {
- return regDt;
- }
- public void setRegDt(Date regDt) {
- this.regDt = regDt;
- }
- public int getReadCount() {
- return readCount;
- }
- public void setReadCount(int readCount) {
- this.readCount = readCount;
- }
- public List<BoardFileDto> getFileList() {
- return fileList;
- }
- public void setFileList(List<BoardFileDto> fileList) {
- this.fileList = fileList;
- }
- }
- ★ 5. BoardFileDto.java
- package com.finger.spring.board.dto;
- import java.util.Date;
- public class BoardFileDto {
- private int fileId;
- private int boardId;
- private String fileName;
- private long fileSize;
- private String fileContentType;
- private String fileUrl;
- private Date regDt;
- public int getFileId() {
- return fileId;
- }
- public void setFileId(int fileId) {
- this.fileId = fileId;
- }
- public int getBoardId() {
- return boardId;
- }
- public void setBoardId(int boardId) {
- this.boardId = boardId;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public long getFileSize() {
- return fileSize;
- }
- public void setFileSize(long fileSize) {
- this.fileSize = fileSize;
- }
- public String getFileContentType() {
- return fileContentType;
- }
- public void setFileContentType(String fileContentType) {
- this.fileContentType = fileContentType;
- }
- public String getFileUrl() {
- return fileUrl;
- }
- public void setFileUrl(String fileUrl) {
- this.fileUrl = fileUrl;
- }
- public Date getRegDt() {
- return regDt;
- }
- public void setRegDt(Date regDt) {
- this.regDt = regDt;
- }
- @Override
- public String toString() {
- return "boardFile [fileId=" + fileId + ", boardId=" + boardId + ", fileName=" + fileName
- + ", fileSize=" + fileSize + ", fileContentType=" + fileContentType + "]";
- }
- }
- ★ 6. BoardService.java
- package com.finger.spring.board.service;
- import java.util.List;
- import org.springframework.web.multipart.MultipartFile;
- import com.finger.spring.board.dto.BoardDto;
- public interface BoardService {
- public int boardInsert(BoardDto dto);
- public int boardInsertFile(BoardDto dto, MultipartFile file) throws Exception;
- public List<BoardDto> boardList(int limit, int offset, String searchWord);
- public int boardListTotalCnt(String searchWord);
- //public BoardDto boardDetail(int boardId);
- public BoardDto boardDetail(int boardId, int userSeq);
- public int boardUpdate(BoardDto dto);
- public int boardUpdateFile(BoardDto dto, MultipartFile file) throws Exception;
- public int boardDelete(BoardDto dto);
- public int boardUpdateReadCnt(int boardId);
- }
- ★ 7. BoardServiceImpl.java
- package com.finger.spring.board.service;
- import java.io.File;
- import java.util.Iterator;
- import java.util.List;
- import java.util.UUID;
- import org.apache.commons.io.FilenameUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.web.multipart.MultipartFile;
- import com.finger.spring.board.controller.BoardController;
- import com.finger.spring.board.dao.BoardDao;
- import com.finger.spring.board.dto.BoardDto;
- import com.finger.spring.board.dto.BoardFileDto;
- @Service
- public class BoardServiceImpl implements BoardService{
- private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
- @Autowired
- BoardDao boardDao;
- @Override
- public int boardInsert(BoardDto dto) {
- return boardDao.boardInsert(dto);
- }
- // C:\Users\User\eclipse-workspace\finger\src\main\webapp\resources\boardFiles
- String boardUploadRealPath =
- "C:" + File.separator + "Users" + File.separator + "User" + File.separator +
- "eclipse-workspace" + File.separator + "finger" + File.separator + "src" + File.separator + "main" + File.separator + "webapp" + File.separator +
- "resources" + File.separator + "boardFiles";
- String boardDeleteRealPath =
- "C:" + File.separator + "Users" + File.separator + "User" + File.separator +
- "eclipse-workspace" + File.separator + "finger" + File.separator + "src" + File.separator + "main" + File.separator + "webapp" + File.separator +
- "resources" + File.separator + "boardFiles" ;
- String boardFileFolder = "resources/boardFiles";
- @Override
- @Transactional("txManager")
- public int boardInsertFile(BoardDto dto, MultipartFile file) throws Exception{
- //with jdbcTemplate
- //int boardId = boardDao.boardInsert(dto);
- boardDao.boardInsert(dto);
- int boardId = dto.getBoardId();
- logger.debug("boardId : " + boardId);
- if( file != null ) {
- //Random Fild Id
- UUID uuid = UUID.randomUUID();
- //file extention
- String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // vs FilenameUtils.getBaseName()
- String savingFileName = uuid + "." + extension;
- File saveFile = new File(boardUploadRealPath, savingFileName);
- file.transferTo(saveFile);
- //File Save to folder
- BoardFileDto fileDto = new BoardFileDto();
- fileDto.setFileContentType(file.getContentType());
- logger.debug("fileDto.getFileContentType : " + fileDto.getFileContentType());
- fileDto.setFileName(file.getOriginalFilename());
- fileDto.setFileSize(file.getSize());
- String boardFileUrl = boardFileFolder + "/" + savingFileName;
- fileDto.setFileUrl(boardFileUrl);
- fileDto.setBoardId(boardId);
- boardDao.boardInsertFile(fileDto);
- }
- return boardId;
- }
- @Override
- public List<BoardDto> boardList(int limit, int offset, String searchWord) {
- logger.debug("searchWord : " + searchWord);
- if("".equals(searchWord)) {
- return boardDao.boardList(limit, offset);
- }else {
- return boardDao.boardListSearchWord(limit, offset, searchWord);
- }
- }
- @Override
- public int boardListTotalCnt(String searchWord) {
- if("".equals(searchWord)) {
- return boardDao.boardListTotalCnt();
- }else {
- return boardDao.boardListSearchWordTotalCnt(searchWord);
- }
- }
- // @Override
- // public BoardDto boardDetail(int boardId) {
- //
- // BoardDto dto = boardDao.boardDetail(boardId);
- // List<BoardFileDto> fileList = boardDao.boardDetailFileList(dto.getBoardId());
- // dto.setFileList(fileList);
- // return dto;
- // }
- @Override
- public BoardDto boardDetail(int boardId, int userSeq) {
- //議고쉶�닔 泥섎━
- int viewCnt = boardDao.boardUserReadCnt(boardId, userSeq);
- if( viewCnt == 0 ) {
- boardDao.boardInsertUserRead(boardId, userSeq);
- boardDao.boardUpdateReadCnt(boardId);
- }
- BoardDto dto = boardDao.boardDetail(boardId);
- List<BoardFileDto> fileList = boardDao.boardDetailFileList(dto.getBoardId());
- dto.setFileList(fileList);
- return dto;
- }
- @Override
- public int boardUpdate(BoardDto dto) {
- return boardDao.boardUpdate(dto);
- }
- @Override
- @Transactional("txManager")
- public int boardUpdateFile(BoardDto dto, MultipartFile file) throws Exception{
- int ret = boardDao.boardUpdate(dto);
- if( file != null ) {
- //delete first
- boardDao.boardDeleteFile(dto.getBoardId());
- //Random Fild Id
- UUID uuid = UUID.randomUUID();
- //file extention
- String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // vs FilenameUtils.getBaseName()
- String savingFileName = uuid + "." + extension;
- File saveFile = new File(boardUploadRealPath, savingFileName);
- file.transferTo(saveFile);
- //File Save to folder
- BoardFileDto fileDto = new BoardFileDto();
- fileDto.setFileContentType(file.getContentType());
- logger.debug("fileDto.getFileContentType : " + fileDto.getFileContentType());
- fileDto.setFileName(file.getOriginalFilename());
- fileDto.setFileSize(file.getSize());
- String boardFileUrl = boardFileFolder + "/" + savingFileName;
- fileDto.setFileUrl(boardFileUrl);
- fileDto.setBoardId(dto.getBoardId());
- boardDao.boardInsertFile(fileDto);
- }
- return ret;
- }
- @Override
- @Transactional("txManager")
- public int boardDelete(BoardDto dto) {
- List<String> fileUrlList = boardDao.boardDeleteFileUrl(dto.getBoardId());
- for(String fileUrl : fileUrlList) {
- File file = new File(boardDeleteRealPath, fileUrl);
- logger.debug("file : " + file.getName());
- if(file.exists()) {
- file.delete();
- }
- }
- boardDao.boardDeleteFile(dto.getBoardId());
- int ret = boardDao.boardDelete(dto);
- return ret;
- }
- @Override
- public int boardUpdateReadCnt(int boardId) {
- return boardDao.boardUpdateReadCnt(boardId);
- }
- }
- ★ 8. board.jsp
- <%@ page language="java" contentType="text/html; charset=EUC-KR"
- pageEncoding="EUC-KR"%>
- <%@ page import = "com.finger.spring.user.dto.*" %>
- <%
- UserDto userDto = (UserDto) session.getAttribute("userDto");
- String userName = "";
- if(userDto != null){
- System.out.println(userDto.getUserSeq());
- userName = userDto.getUserName();
- }
- %>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>Bootstrap Example</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
- <script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
- <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>
- <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"/>
- <link rel="stylesheet" href="/resources/css/common.css">
- </head>
- <body>
- <nav class="navbar navbar-expand-sm bg-light">
- <ul class="navbar-nav">
- <li class="nav-item">
- <a class="nav-link" href="/board">게시판</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" href="/logout">logout</a>
- </li>
- </ul>
- </nav>
- <br>
- <div class="container">
- <h2>게시판</h2>
- <div class="input-group mb-3">
- <input id="inputSearchWord" type="text" class="form-control" placeholder="Search">
- <div class="input-group-append">
- <button id="btnSearchWord" class="btn btn-success">Go</button>
- </div>
- </div>
- <table class="table table-hover">
- <thead>
- <tr>
- <th>#</th>
- <th>제목</th>
- <th>작성자</th>
- <th>작성일시</th>
- <th>조회수</th>
- </tr>
- </thead>
- <tbody id="boardTbody">
- </tbody>
- </table>
- <div id="paginationWrapper"></div>
- <button class="btn btn-sm btn-primary" id="btnBoardInsertForm">글쓰기</button>
- </div>
- <!-- Modal insert-->
- <div class="modal fade" id="boardInsertModal">
- <div class="modal-dialog modal-simple">
- <form class="modal-content">
- <!-- Modal Header -->
- <div class="modal-header">
- <h4 class="modal-title">글쓰기</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-xl-12 form-group">
- <input id="titleInsert" type="text" class="form-control" name="title" placeholder="제목">
- </div>
- <div class="col-xl-12 form-group">
- <textarea id="contentInsert" class="form-control" rows="5" placeholder="내용"></textarea>
- </div>
- <div class="col-xl-12 form-group">
- <div class="checkbox-custom checkbox-primary">
- <input type="checkbox" id="chkFileUploadInsert" />
- <label for="chkFileUploadInsert">파일 추가</label>
- </div>
- </div>
- <div class="col-xl-12 form-group" style="display:none;" id="imgFileUploadInsertWrapper">
- <input type="file" id="inputFileUploadInsert">
- <div class="thumbnail-wrapper">
- <img id="imgFileUploadInsert">
- </div>
- </div>
- <div class="col-md-12 float-right">
- <button id="btnBoardInsert" class="btn btn-sm btn-primary btn-outline" data-dismiss="modal" type="button">등록</button>
- </div>
- </div>
- </div>
- </form>
- </div>
- </div>
- <!-- End Modal -->
- <!-- Modal detail-->
- <div class="modal fade" id="boardDetailModal">
- <div class="modal-dialog modal-simple">
- <div class="modal-content">
- <!-- Modal Header -->
- <div class="modal-header">
- <h4 class="modal-title">글 상세</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="example table-responsive">
- <table class="table table-hover">
- <tbody>
- <tr><td>글번호</td><td id="boardIdDetail">#</td></tr>
- <tr><td>제목</td><td id="titleDetail">#</td></tr>
- <tr><td>내용</td><td id="contentDetail">#</td></tr>
- <tr><td>작성자</td><td id="userNameDetail">#</td></tr>
- <tr><td>작성일시</td><td id="regDtDetail">#</td></tr>
- <tr><td>조회수</td><td id="readCountDetail">#</td></tr>
- <tr><td>첨부파일</td><td id="fileListDetail">#</td></tr>
- </tbody>
- </table>
- </div>
- <button id="btnBoardUpdateForm" class="btn btn-sm btn-primary btn-outline" data-dismiss="modal" type="button">글 수정하기</button>
- <button id="btnBoardDeleteConfirm" class="btn btn-sm btn-warning btn-outline" data-dismiss="modal" type="button">글 삭제하기</button>
- </div>
- </div>
- </div>
- </div>
- <!-- End Modal -->
- <!-- Modal update-->
- <div class="modal fade" id="boardUpdateModal">
- <div class="modal-dialog modal-simple">
- <form class="modal-content">
- <!-- Modal Header -->
- <div class="modal-header">
- <h4 class="modal-title">글수정</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-xl-12 form-group">
- <input id="titleUpdate" type="text" class="form-control" name="title" placeholder="제목">
- </div>
- <div class="col-xl-12 form-group">
- <textarea id="contentUpdate" class="form-control" rows="5" placeholder="내용"></textarea>
- </div>
- <div class="col-xl-12 form-group">
- 첨부파일 : <span id="fileListUpdate"></span>
- </div>
- <div class="col-xl-12 form-group">
- <div class="checkbox-custom checkbox-primary">
- <input type="checkbox" id="chkFileUploadUpdate" />
- <label for="chkFileUploadUpdate">파일 변경</label>
- </div>
- </div>
- <div class="col-xl-12 form-group" style="display:none;" id="imgFileUploadUpdateWrapper">
- <input type="file" id="inputFileUploadUpdate">
- <div class="thumbnail-wrapper">
- <img id="imgFileUploadUpdate">
- </div>
- </div>
- <div class="col-md-12 float-right">
- <button id="btnBoardUpdate" class="btn btn-sm btn-primary btn-outline" data-dismiss="modal" type="button">수정</button>
- </div>
- </div>
- </div>
- </form>
- </div>
- </div>
- <!-- End Modal -->
- <script src="/resources/js/util.js"></script>
- <script>
- var LIST_ROW_COUNT = 10; //limit
- var OFFSET = 0;
- var PAGE_COUNT_PER_BLOCK = 10; // pagination link 갯수
- var TOTAL_LIST_ITEM_COUNT = 0;
- var CURRENT_PAGE_INDEX = 1;
- var SEARCH_WORD = "";
- $(document).ready(function() {
- boardList();
- $("#btnBoardInsertForm").click(function(){
- $("#titleInsert").val("");
- $("#contentInsert").val("");
- $("#chkFileUploadInsert").prop("checked", false);
- $("#inputFileUploadInsert").val("");
- $("#imgFileUploadInsert").removeAttr("src");
- //$("#imgFileUploadInsert").attr("src", "");
- $("#imgFileUploadInsertWrapper").hide();
- $("#boardInsertModal").modal("show");
- });
- $("#btnBoardInsert").click(function(){
- if( validateInsert() ){
- boardInsert();
- }
- });
- $("#btnBoardUpdateForm").click(function(){
- var boardId = $("#boardDetailModal").attr("data-boardId");
- $("#boardUpdateModal").attr("data-boardId", boardId);
- $("#titleUpdate").val( $("#titleDetail").html() );
- $("#contentUpdate").val( $("#contentDetail").html() );
- // $("#fileListDetail").append(
- // '<span class="fileName">' + fileName + '</span>');
- var fileName = $("#fileListDetail").find(".fileName").html();
- $("#fileListUpdate").html( '<span class="fileName">' + fileName + '</span>');
- $("#chkFileUploadUpdate").prop("checked", false);
- $("#inputFileUploadUpdate").val("");
- $("#imgFileUploadUpdate").attr("src", "");
- //$("#imgFileUploadUpdate").removeAttr("src");
- $("#imgFileUploadUpdateWrapper").hide();
- $("#boardDetailModal").modal("hide");
- $("#boardUpdateModal").modal("show");
- });
- $("#btnBoardUpdate").click(function(){
- if( validateUpdate() ){
- boardUpdate();
- }
- });
- $("#btnBoardDeleteConfirm").click(function(){
- alertify.confirm('Upwiden', '이 글을 삭제하시겠습니까?',
- function() {
- boardDelete();
- },
- function(){
- console.log('cancel');
- }
- );
- });
- //file upload..
- //Insert
- $("#chkFileUploadInsert").change(function(){
- if( $(this).prop("checked")){
- $("#imgFileUploadInsertWrapper").show();
- }else{
- $("#inputFileUploadInsert").val("");
- $("#imgFileUploadInsert").attr("src", "");
- $("#imgFileUploadInsertWrapper").hide();
- }
- });
- $("#inputFileUploadInsert").change(function(e){
- if( this.files && this.files[0] ){
- var reader = new FileReader();
- reader.onload = function(e){
- $("#imgFileUploadInsert").attr("src", e.target.result);
- }
- reader.readAsDataURL(this.files[0]);
- }
- });
- //Update
- $("#chkFileUploadUpdate").change(function(){
- if( $(this).prop("checked")){
- $("#imgFileUploadUpdateWrapper").show();
- }else{
- $("#inputFileUploadUpdate").val("");
- $("#imgFileUploadUpdate").attr("src", "");
- $("#imgFileUploadUpdateWrapper").hide();
- }
- });
- $("#inputFileUploadUpdate").change(function(e){
- if( this.files && this.files[0] ){
- var reader = new FileReader();
- reader.onload = function(e){
- $("#imgFileUploadUpdate").attr("src", e.target.result);
- }
- reader.readAsDataURL(this.files[0]);
- }
- });
- //Search
- $("#btnSearchWord").click(function(e){
- var searchWord = $("#inputSearchWord").val();
- if( searchWord != "" ){
- SEARCH_WORD = searchWord;
- }else{
- SEARCH_WORD = "";
- }
- boardList();
- });
- });
- function validateInsert(){
- var isTitleInsertValid = false;
- var isContentInsertValid = false;
- var titleInsert = $("#titleInsert").val();
- var titleInsertLength = titleInsert.length;
- if( titleInsertLength > 0 ){
- isTitleInsertValid = true;
- }
- var contentInsertValue = $("#contentInsert").val();
- var contentInsertLength = contentInsertValue.length;
- if( contentInsertLength > 0 ){
- isContentInsertValid = true;
- }
- if( isTitleInsertValid && isContentInsertValid ){
- return true;
- }else{
- return false;
- }
- }
- function boardInsert(){
- var formData = new FormData();
- formData.append("userSeq", '<%=userDto.getUserSeq()%>');
- formData.append("title", $("#titleInsert").val());
- formData.append("content", $("#contentInsert").val());
- formData.append("file", $("#inputFileUploadInsert")[0].files[0]);
- console.log(formData.get('userSeq'));
- console.log(formData.get('title'));
- console.log(formData.get('content'));
- $.ajax(
- {
- type : 'post',
- url : '/board/insertFile',
- dataType : 'json',
- data : formData,
- contentType: false, // forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it
- processData: false, // otherwise, jQuery will try to convert your FormData into a string, which will fail.
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- if( data ){
- alertify.success('글이 등록되었습니다.');
- boardList();
- }
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 등록 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- function validateUpdate(){
- var isTitleUpdateValid = false;
- var isContentUpdateValid = false;
- var titleUpdate = $("#titleUpdate").val();
- var titleUpdateLength = titleUpdate.length;
- if( titleUpdateLength > 0 ){
- isTitleUpdateValid = true;
- }
- var contentUpdateValue = $("#contentUpdate").val();
- var contentUpdateLength = contentUpdateValue.length;
- if( contentUpdateLength > 0 ){
- isContentUpdateValid = true;
- }
- if( isTitleUpdateValid && isContentUpdateValid ){
- return true;
- }else{
- return false;
- }
- }
- function boardUpdate(){
- var formData = new FormData();
- formData.append("boardId", $("#boardUpdateModal").attr("data-boardId"));
- formData.append("userSeq", '<%=userDto.getUserSeq()%>');
- formData.append("title", $("#titleUpdate").val());
- formData.append("content", $("#contentUpdate").val());
- formData.append("file", $("#inputFileUploadUpdate")[0].files[0]);
- $.ajax(
- {
- type : 'post',
- url : '/board/updateFile',
- dataType : 'json',
- data : formData,
- contentType: false, // forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it
- processData: false, // otherwise, jQuery will try to convert your FormData into a string, which will fail.
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- if( data ){
- alertify.success('글이 수정되었습니다.');
- boardList();
- }
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 수정 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- function boardDelete(){
- $.ajax(
- {
- type : 'post',
- url : '/board/delete',
- dataType : 'json',
- data :
- {
- boardId: $("#boardDetailModal").attr("data-boardId")
- },
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- if( data ){
- alertify.success('글이 삭제되었습니다.');
- boardList();
- }
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 삭제 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- function boardList(){
- $.ajax(
- {
- type : 'get',
- url : '/board/list',
- dataType : 'json',
- data :
- {
- limit: LIST_ROW_COUNT,
- offset: OFFSET,
- searchWord: SEARCH_WORD
- },
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- makeListHtml(data);
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 조회 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- function makeListHtml(list){
- $("#boardTbody").html("");
- //var boardArray = JSON.parse(data); ?? @ResponseBody 자동으로 json 변환
- for( var i=0; i<list.length; i++){
- var boardId = list[i].boardId;
- var userName = list[i].userName;
- var title = list[i].title;
- var content = list[i].content;
- var regDt = list[i].regDt;
- var readCount = list[i].readCount;
- var listHtml =
- '<tr style="cursor:pointer" data-boardId=' + boardId +'><td>' + boardId + '</td><td>' + title + '</td><td>' + userName + '</td><td>' + regDt + '</td><td>' + readCount + '</td></tr>';
- $("#boardTbody").append(listHtml);
- }
- makeListHtmlEventHandler();
- boardListTotalCnt();
- }
- function addPagination(){
- makePaginationHtml(LIST_ROW_COUNT, PAGE_COUNT_PER_BLOCK, CURRENT_PAGE_INDEX, TOTAL_LIST_ITEM_COUNT, "paginationWrapper", boardList );
- }
- function movePage(pageIndex){
- OFFSET = (pageIndex - 1) * LIST_ROW_COUNT;
- CURRENT_PAGE_INDEX = pageIndex;
- boardList();
- }
- function boardListTotalCnt(){
- $.ajax(
- {
- type : 'get',
- url : '/board/list/totalCnt',
- dataType : 'json',
- data :
- {
- searchWord: SEARCH_WORD
- },
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- TOTAL_LIST_ITEM_COUNT = data;
- addPagination();
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 전체 갯수 조회 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- // function boardListTotalCnt(){
- // $.ajax(
- // {
- // type : 'get',
- // url : '/board/test',
- // dataType : 'json',
- // beforeSend : function(xhr){
- // //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- // xhr.setRequestHeader("AJAX", true);
- // },
- // success : function(data, status, xhr) {
- // console.log(data);
- // console.log(data.msg);
- // },
- // error: function(jqXHR, textStatus, errorThrown)
- // {
- // if( jqXHR.responseText == "timeout" ){
- // window.location.href = "/login"
- // }else{
- // alertify.notify(
- // 'Opps!! 글 test 에 문제가 생겼습니다.',
- // 'error', //'error','warning','message'
- // 3, //-1
- // function(){
- // console.log(jqXHR.responseText);
- // }
- // );
- // }
- // }
- // });
- // }
- function makeListHtmlEventHandler(){
- $("#boardTbody tr").click(function(){
- var boardId = $(this).attr("data-boardId");
- var userSeq = '<%=userDto.getUserSeq()%>';
- boardDetail(boardId, userSeq);
- //alert(boardId);
- });
- }
- function boardDetail(boardId, userSeq){
- $.ajax(
- {
- type : 'get',
- url : '/board/detail',
- dataType : 'json',
- data :
- {
- boardId: boardId,
- userSeq: userSeq
- },
- beforeSend : function(xhr){
- //xhr.setRequestHeader("ApiKey", "asdfasxdfasdfasdf");
- xhr.setRequestHeader("AJAX", true);
- },
- success : function(data, status, xhr) {
- makeDetailHtml(data);
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- if( jqXHR.responseText == "timeout" ){
- window.location.href = "/login"
- }else{
- alertify.notify(
- 'Opps!! 글 상세 조회 과정에 문제가 생겼습니다.',
- 'error', //'error','warning','message'
- 3, //-1
- function(){
- console.log(jqXHR.responseText);
- }
- );
- }
- }
- });
- }
- function makeDetailHtml(detail){
- var boardId = detail.boardId;
- var userSeq = detail.userSeq;
- var userName = detail.userName;
- var title = detail.title;
- var content = detail.content;
- var regDt = detail.regDt;
- var readCount = detail.readCount;
- var fileList = detail.fileList;
- $("#boardDetailModal").attr("data-boardId", boardId);
- $("#boardIdDetail").html("#" + boardId);
- $("#titleDetail").html(title);
- $("#contentDetail").html(content);
- $("#userNameDetail").html(userName);
- $("#regDtDetail").html(regDt);
- $("#readCountDetail").html(readCount);
- //FileList
- $("#fileListDetail").html("");
- if( fileList.length > 0 ){
- for(var i=0; i<fileList.length; i++){
- var fileId = fileList[i].fileId;
- var fileName = fileList[i].fileName;
- var fileUrl = fileList[i].fileUrl;
- $("#fileListDetail").append(
- '<span class="fileName">' + fileName + '</span>');
- $("#fileListDetail").append(
- ' <a type="button" class="btn btn-outline btn-default btn-xs" ' +
- 'data-fileId="' + fileId + '" ' +
- 'href="' + fileUrl + '" ' +
- 'download="' + fileName + '">내려받기</a>');
- }
- }
- if( userSeq != '<%=userDto.getUserSeq()%>' ){
- $("#btnBoardUpdateForm").hide();
- $("#btnBoardDeleteConfirm").hide();
- }else{
- $("#btnBoardUpdateForm").show();
- $("#btnBoardDeleteConfirm").show();
- }
- $("#boardDetailModal").modal("show");
- makeDetailHtmlEventHandler();
- }
- function makeDetailHtmlEventHandler(){
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment