개인 프로젝트

게시판 만들기

무너지지않는 젠가 2024. 7. 8. 11:21

기능 설명

 게시판 만들기를 할때, 로그인 - 로그인 구현(1, 2, 3) 이후 User 상세 정보에서 글쓰기를 클릭하면 해당 User가 게시글을 작성할 수 있도록 하고 단, User가 일치하지 않으면 글을 수정하거나, 삭제할 수 없게 하였다.

 

로그인 구현(1)  : https://won-coding-051.tistory.com/25

 

 

전체적인 순서도(로그인 ~ 게시판)

 

BoardControler.java

@RequestMapping("/boardList.do")

public String boardList(@RequestParam(value = "userid", required = false) String userid,

@RequestParam(value = "password", required = false) String password, Model model, HttpSession session) {

 

String sessionId = (String) session.getAttribute("userid");

if (sessionId == null) {

return "login/login";

}

 

List<BoardForm> boardform = boardService.boardList();

if (boardform == null) {

return "error/error";

}

UserInfo userinfo = userService.getuserinfo(userid);

model.addAttribute("sessionId", sessionId);

model.addAttribute("userinfo", userinfo);

model.addAttribute("boardList", boardform);

 

return "board/boardList";

}

 

/**

*

* @param userid

* @param model

* @param session

* @return 페이지

*/

@RequestMapping("/boardWriteView.do")

public String boardWriteView(@RequestParam("userid") String userid, Model model, HttpSession session) {

 

String sessionId = (String) session.getAttribute("userid");

if (sessionId == null) {

return "login/login";

}

 

UserInfo userinfo = userService.getuserinfo(userid);

 

model.addAttribute("userinfo", userinfo);

 

return "board/boardWrite";

}

 

@RequestMapping("/excerciseBook.do")

public String excerciseBook(@RequestParam("userid") String userid, Model model, HttpSession session) {

 

String sessionId = (String) session.getAttribute("userid");

if (sessionId == null) {

return "login/login";

}

 

UserInfo userinfo = userService.getuserinfo(userid);

 

model.addAttribute("userinfo", userinfo);

 

return "excercise/excersice";

}

 

/**

*

* @param form

* @param model

* @param session

* @param redirectAttributes

* @return 페이지

*/

 

@RequestMapping("boardWrite.do")

public String boardWrite(@ModelAttribute("boardForm") BoardForm form, Model model, HttpSession session,

RedirectAttributes redirectAttributes, HttpServletRequest request,

@RequestParam(value = "files", required = false) List<MultipartFile> multipartFile) {

 

System.out.println("file : :: " + multipartFile);

 

String sessionId = (String) session.getAttribute("userid");

if (sessionId == null) {

return "login/login";

}

 

if (multipartFile == null) {

int isSucess = boardService.boardWrite(form);

} else {

//저장할 파일경로 정하기.

String fileRoot;

String contextRoot = request.getSession().getServletContext().getRealPath("/");

fileRoot = contextRoot + "resources/upload/";

 

// 파일 디렉토리가 없을 경우 생성

File dir = new File(fileRoot);

if (!dir.exists()) {

dir.mkdirs();

}

 

try {

for (MultipartFile file : multipartFile) {

if (!file.isEmpty()) {

 

System.out.println(fileRoot);

 

String originalFileName = file.getOriginalFilename();// 오리지날 파일명

String extension = originalFileName.substring(originalFileName.lastIndexOf(".")); // 파일 확장자

String savedFileName = UUID.randomUUID() + extension; // 저장될 파일 명

 

// 파일 목적지

File targetFile = new File(fileRoot + savedFileName);

 

// 저장할 타겟 파일 디렉토리

file.transferTo(targetFile);

form.setFile_path(fileRoot + savedFileName);

int isSucess = boardService.boardWrite(form);

// You can save file details in the database here if needed (e.g., file name,

// path, etc.)

}

}

 

} catch (Exception e) {

e.printStackTrace();

return "error/error";

}

 

}

redirectAttributes.addAttribute("userid", form.getUserid());

return "redirect:/board/boardList.do";

}

 

/**

*

* @param seq

* @param model

* @param session

* @return 페이지

*/

 

@RequestMapping("boardView.do")

public String boardView(@RequestParam("seq") int seq, Model model, HttpSession session) {

String sessionId = (String) session.getAttribute("userid");

if (sessionId == null) {

return "login/login";

}

 

// 조회수 update

int success = boardService.boardViews(seq);

BoardForm boardform = boardService.boardView(seq);

model.addAttribute("sessionId", sessionId);

model.addAttribute("board", boardform);

 

if (success == 0) {

return "error/error";

}

 

if (boardform == null) {

return "error/error";

}

return "board/boardView";

}

 

// 비동기 처리

 

/**

*

* @param form

* @param session

* @param model

* @return JSONObject

*/

 

@ResponseBody

@PostMapping("/boardUpdate.do")

public JSONObject boardUpdate(@RequestBody BoardForm form, HttpSession session, Model model) {

String sessionId = (String) session.getAttribute("userid");

 

JSONObject jsonObject = new JSONObject();

 

if (sessionId == null) {

session.invalidate();

jsonObject.put("sessionReset", "0");

jsonObject.put("message", "세션이 종료되었습니다. \n로그인이 필요합니다.");

 

return jsonObject;

} else if (!sessionId.equals(form.getUserid())) {

jsonObject.put("message", "작성자가 일치하지 않습니다.");

return jsonObject;

} else {

try {

int success = boardService.boardUpdate(form);

 

jsonObject.put("message", "게시글이 성공적으로 업데이트되었습니다.");

return jsonObject;

} catch (Exception e) {

Log.error("Update Error{}", e);

jsonObject.put("message", "게시글 업데이트 중 오류가 발생했습니다.");

return jsonObject;

}

}

}

 

/**

*

* @param userid

* @param seq

* @param session

* @param model

* @return JSONObject

*/

@ResponseBody

@PostMapping("/boardDelete.do")

public JSONObject boardDelete(@RequestParam("userid") String userid, @RequestParam("seq") String seq,

HttpSession session, Model model) {

String sessionId = (String) session.getAttribute("userid");

 

JSONObject jsonObject = new JSONObject();

 

if (sessionId == null) {

session.invalidate();

jsonObject.put("sessionReset", "0");

jsonObject.put("message", "세션이 종료되었습니다. \n로그인이 필요합니다.");

 

return jsonObject;

} else if (!sessionId.equals(userid)) {

jsonObject.put("message", "작성자가 일치하지 않습니다.");

return jsonObject;

} else {

try {

int success = boardService.boardDelete(userid, seq);

 

jsonObject.put("message", "게시글이 성공적으로 삭제되었습니다.");

return jsonObject;

} catch (Exception e) {

Log.error("Update Error{}", e);

jsonObject.put("message", "게시글 삭제 중 오류가 발생했습니다.");

return jsonObject;

}

}

}

 

 

board.js

/delete board

function delete_board(userid, seq) {

 

$.ajax({

url: "/board/boardDelete.do",

type: "POST",

data: {

userid: userid,

seq: seq

},

dataType: "json",

success: function(response) {

 

if (response.sessionReset === '0') {

alert(response.message);

return window.location.href = "/login/login.do";

}

 

alert(response.message);

window.location.reload();

 

},

error: function(status, error) {

console.log("status : : :" + status);

console.log("error : : :" + error);

alert(response.message);

return window.location.href = "/error/error.do";

}

})

 

}

$(document).ready(function() {

$("#editbutton").on("click", function() {

 

document.getElementById('showcontent').style.visibility = 'hidden';

var boardContent = $('#boardContent').val();

// jQuery로 동적 textarea 생성

//$("#content-div").append("<textarea id='content' name='content'rows='10' required></textarea>");

let newContent = $('<textarea>', {

id: 'content',

name: 'content',

rows: '10',

required: true,

text: boardContent

});

$('#content-div').append(newContent);

 

 

document.getElementById('BoardTitle').style.display = 'none';

let title = document.getElementById('title');

title.classList.remove('hidden-input');

title.classList.add('visible-input');

title.focus();

 

//자바스크립트로 동적 submit 버튼 생성

let newSubmit = document.createElement('input');

newSubmit.type = 'button';

newSubmit.id = 'button';

newSubmit.value = '저장';

newSubmit.className = 'btn-create';

 

newSubmit.addEventListener('click', function() {

//Ajax로 처리해보기

 

let content = document.getElementById('content').value;

let userid = document.getElementById('userid').value;

let seq = document.getElementById('seq').value;

let title = document.getElementById('title').value;

 

/*@RequestBody로 서버에서 받을 때 */

 

$.ajax({

url: "/board/boardUpdate.do",

type: "POST",

contentType: "application/json",

data: JSON.stringify({

content: content,

userid: userid,

seq: seq,

title: title

}),

dataType: "json",

success: function(response) {

 

if (response.sessionReset === '0') {

alert(response.message);

return window.location.href = "/login/login.do";

}

 

alert(response.message);

window.location.reload();

 

},

error: function(status, error) {

console.log("status : : :" + status);

console.log("error : : :" + error);

alert(response.message);

return window.location.href = "/error/error.do";

}

})

/* RequestParam으로 서버에서 받을 때

 

$.ajax({

url: "/board/boardUpdate.do",

type: "POST",

data: {

content: content,

userid: userid,

seq : seq,

title: title

},

dataType: "json",

success: function(data, status) {

alert("완료되었습니다");

window.reload();

}

 

})*/

 

});

let editButton = document.getElementById('editbutton');

editButton.parentNode.insertBefore(newSubmit, editButton.nextSibling);

editButton.style.display = 'none';

 

/* var newSubmit = document.createElement('input');

newSubmit.setAttribute("button","button")

newSubmit.setAttribute ='submit';

button.setAttribute ='Submit';

button.setAttribute = 'btn-btn-create';

*/

});

});

 

 

boardList.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>게시판</title>

<link rel="stylesheet" type="text/css"

href="${pageContext.request.contextPath}/css/board.css">

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="${pageContext.request.contextPath}/js/board.js"></script>

</head>

<body>

<div class="container">

<h1>게시판</h1>

<a href="/board/boardWriteView.do?userid=${sessionId}"

class="btn-create">글 작성</a>

<div class="table-container">

 

 

<table>

<thead>

<tr>

<th style="text-align: center;">번호</th>

<th style="text-align: center;">제목</th>

<th style="text-align: center;">작성자</th>

<th style="text-align: center;">작성일</th>

<th style="text-align: center;">조회수</th>

<th style="text-align: center;">글관리</th>

 

</tr>

</thead>

<tbody>

<c:forEach var="boardList" items="${boardList}">

<tr>

<td style="text-align: center;">${boardList.seq}</td>

 

<td style="text-align: center;"><a

href="/board/boardView.do?seq=${boardList.seq}">${boardList.title}</a></td>

<td style="text-align: center;">${boardList.userid}</td>

 

<td style="text-align: center;">${boardList.write_date}</td>

<td style="text-align: center;">${boardList.view_cnt}</td>

<td style="text-align: center;">

<c:choose>

<c:when test="${sessionId eq boardList.userid}">

<a href="/board/boardView.do?seq=${boardList.seq}"

class="btn-edit">수정</a>

<a href="javascript:delete_board('${boardList.userid}','${boardList.seq}');" class="btn-delete">삭제</a>

</c:when>

<c:otherwise>

<p>수정과 삭제는 작성자와 로그인 사용자가 동일할때, 가능합니다.</p>

</c:otherwise>

</c:choose>

 

</td>

</tr>

</c:forEach>

</tbody>

</table>

</div>

<a href="javascript:window.history.back();" class="btn-back">뒤로가기</a>

</div>

</body>

</html>

 

 

ps. 위에 적힌 코드로는 동작하지 않는다. 기본적인 뼈대 소스만 알고가면 좋을 듯 하다.

혹시나 더 나은 코드가 있다면, 피드백 해주시면 감사하겠습니다. 

 

아래는 개인프로젝트 깃허브 주소이고 전체를 확인할 수 있다.

https://github.com/TechWonLee/MvcProject

 

GitHub - TechWonLee/MvcProject

Contribute to TechWonLee/MvcProject development by creating an account on GitHub.

github.com

 

감사합니다.