코딩기록
Day - 43 [Spring] 08_photoBoard 본문
설정
web.xml (한글 깨짐 방지 설정)

web.xml (에러 코드 페이지 설정)

servlet - context.xml 위치 변경


css
공통css 설정


적용 css 링크 태그를 jsp 에 삽입
<link rel="stylesheet" href="resources/css/commons.css" type="text/css">

error 페이지 설정
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<style></style>
</head>
<body>
<h2>ERROR CODE : ${code}</h2>
<h3>${msg}</h3>
</body>
<script></script>
</html>
controller
package kr.co.gudi.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ErrorController {
Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value="/error/404")
public String notFound(Model model) {
model.addAttribute("code", "404");
model.addAttribute("msg", "원하시는 요청 또는 페이지가 없습니다.");
return "error";
}
@RequestMapping(value="/error/500")
public String serverError(Model model) {
model.addAttribute("code", "500");
model.addAttribute("msg", "서버처리중 문제가 발생 했습니다.");
return "error";
}
@RequestMapping(value="/error/IOException")
public String ioException(Model model) {
model.addAttribute("code", "500");
model.addAttribute("msg", "데이터 입출력중 문제 발생!");
return "error";
}
}

controller
package kr.co.gudi.controller;
@Controller
public class BoardController {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired BoardService service;
@RequestMapping(value={"/","/list.do"})
public String list(Model model) {
logger.info("list call");
ArrayList<BoardDTO> list = service.list();
logger.info("list cnt : "+list.size());
model.addAttribute("list", list);
return "list";
}
@RequestMapping(value="/write.go")
public String writeForm() {
logger.info("write page 이동");
return "writeForm";
}
@RequestMapping(value="/write.do", method = RequestMethod.POST)
public String write(MultipartFile photo,
@RequestParam HashMap<String, String> params) {
logger.info("params : "+params);
return service.write(photo, params);
}
@RequestMapping(value="/detail.do")
public String detail(Model model, @RequestParam String idx) {
logger.info("detail : "+idx);
String page = "redirect:/list.do";
BoardDTO dto = service.detail(idx,"detail");
if(dto != null) {
page = "detail";
model.addAttribute("dto", dto);
}
return page;
}
@RequestMapping(value="/delete.do")
public String delete(@RequestParam String idx) {
service.delete(idx);
return "redirect:/list.do";
}
@RequestMapping(value="/update.go")
public String updateForm(Model model, @RequestParam String idx) {
logger.info("detail : "+idx);
String page = "redirect:/list.do";
BoardDTO dto = service.detail(idx,"update");
if(dto != null) {
page = "updateForm";
model.addAttribute("dto", dto);
}
return page;
}
@RequestMapping(value="/update.do", method = RequestMethod.POST)
public String update(MultipartFile photo,
@RequestParam HashMap<String, String> params) {
logger.info("params : "+params);
return service.update(photo, params);
}
}
service
package kr.co.gudi.service;
@Service
public class BoardService {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired BoardInter dao;
public ArrayList<BoardDTO> list() {
return dao.list();
}
public String write(MultipartFile photo, HashMap<String, String> params) {
String page = "redirect:/list.do";
// 1. 게시글만 작성한 경우
// 방금 insert 한 값의 key 를 반환 받는 방법
// 조건 1. 파라메터를 DTO 로 보내야 한다.
BoardDTO dto = new BoardDTO();
dto.setSubject(params.get("subject"));
dto.setUser_name(params.get("user_name"));
dto.setContent(params.get("content"));
int row = dao.write(dto);
logger.info("update row : "+row);
// 조건 3. 받아온 키는 파라메터 DTO 에서 뺀다.
int idx = dto.getIdx();
logger.info("방금 insert 한 idx : "+idx);
page = "redirect:/detail.do?idx="+idx;
// 2. 파일도 업로드 한 경우
if(!photo.getOriginalFilename().equals("")) {
logger.info("파일 업로드 작업");
fileSave(idx, photo);
}
return page;
}
private void fileSave(int idx, MultipartFile file) {
// 1. 파일을 C:/img/upload/ 에 저장
//1-1. 원본 이름 추출
String oriFileName = file.getOriginalFilename();
//1-2. 확장자 추출
String ext = oriFileName.substring(oriFileName.lastIndexOf("."));
//1-3. 새이름 생성 + 확장자
String newFileName = System.currentTimeMillis()+ext;
logger.info(oriFileName+" => "+newFileName);
try {
byte[] bytes = file.getBytes();//1-4. 바이트 추출
//1-5. 추출한 바이트 저장
Path path = Paths.get("C:/img/upload/"+newFileName);
Files.write(path, bytes);
logger.info(newFileName+" save OK");
// 2. 저장 정보를 DB 에 저장
//2-1. 가져온 idx, oriFileName, newFileName insert
dao.fileWrite(idx,oriFileName,newFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
public BoardDTO detail(String idx, String flag) {
if(flag.equals("detail")) {
dao.upHit(idx); // 조회수 증가
}
return dao.detail(idx);
}
public void delete(String idx) {
// 1. photo 에 해당 idx 값이 있는지?
String newFileName = dao.findFile(idx);
logger.info("file name : "+newFileName);
// 2. 없다면?
int row = dao.delete(idx);
logger.info("delete data : "+row);
if(newFileName != null && row >0) {// 3. 있다면? AND bbs 와 photo 가 확실히 삭제 되었는지?
File file = new File("C:/img/upload/"+newFileName);
if(file.exists()) {// 2. 해당 파일이 존재 하는지?
file.delete();// 3. 삭제
}
}
}
public String update(MultipartFile photo, HashMap<String, String> params) {
int idx = Integer.parseInt(params.get("idx"));
int row = dao.update(params);// 1. update 실행
// 2. photo 에 파일명이 존재 한다면?
if(!photo.getOriginalFilename().equals("")) {
fileSave(idx, photo);
}
String page = row>0 ? "redirect:/detail.do?idx="+idx : "redirect:/list.do";
logger.info("update => "+page);
return page;
}
}
JSP
list
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<link rel="stylesheet" href="resources/css/commons.css" type="text/css">
<style></style>
</head>
<body>
<button onclick="location.href='write.go'">글쓰기</button>
<table>
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
<th>조회수</th>
<th>작성일</th>
<th>삭제</th>
</tr>
</thead>
<tbody>
<c:if test="${list eq null}">
<tr>
<th colspan="6">등록된 글이 없습니다.</th>
</tr>
</c:if>
<c:forEach items="${list}" var="bbs">
<tr>
<td>${bbs.idx}</td>
<td><a href="detail.do?idx=${bbs.idx}">${bbs.subject}</a></td>
<td>${bbs.user_name}</td>
<td>${bbs.bHit}</td>
<td>${bbs.reg_date}</td>
<td><a href="delete.do?idx=${bbs.idx}">삭제</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
<script>
</script>
</html>
writeForm
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<link rel="stylesheet" href="resources/css/commons.css">
<style></style>
</head>
<body>
<form action="write.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<th>제목</th>
<td><input type="text" name="subject"/></td>
</tr>
<tr>
<th>작성자</th>
<td><input type="text" name="user_name"/></td>
</tr>
<tr>
<th>내용</th>
<td><textarea name="content"></textarea></td>
</tr>
<tr>
<th>사진</th>
<td>
<input type="file" name="photo"/>
</td>
</tr>
<tr>
<th colspan="2">
<input type="button" onclick="location.href='./list.do'" value="리스트"/>
<button>저장</button>
</th>
</tr>
</table>
</form>
</body>
<script></script>
</html>
detail
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<link rel="stylesheet" href="resources/css/commons.css">
<style></style>
</head>
<body>
<table>
<tr>
<th>제목</th>
<td>${dto.subject}</td>
</tr>
<tr>
<th>작성자</th>
<td>${dto.user_name}</td>
</tr>
<tr>
<th>작성일</th>
<td>${dto.reg_date}</td>
</tr>
<tr>
<th>내용</th>
<td>${dto.content}</td>
</tr>
<c:if test="${dto.newFileName ne null}">
<tr>
<th>사진</th>
<td><img width="500" src="/photo/${dto.newFileName}"/></td>
</tr>
</c:if>
<tr>
<th colspan="2">
<input type="button" onclick="location.href='./list.do'" value="리스트"/>
<input type="button" onclick="location.href='./update.go?idx=${dto.idx}'" value="수정"/>
</th>
</tr>
</table>
</body>
<script></script>
</html>
UpdateForm
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<link rel="stylesheet" href="resources/css/commons.css">
<style></style>
</head>
<body>
<form action="update.do" method="post" enctype="multipart/form-data">
<input type="hidden" name="idx" value="${dto.idx}"/>
<table>
<tr>
<th>제목</th>
<td><input type="text" name="subject" value="${dto.subject}"/></td>
</tr>
<tr>
<th>작성자</th>
<td><input type="text" name="user_name" value="${dto.user_name}"/></td>
</tr>
<tr>
<th>내용</th>
<td><textarea name="content">${dto.content}</textarea></td>
</tr>
<tr>
<th>사진</th>
<td>
<c:if test="${dto.newFileName eq null}">
<input type="file" name="photo"/>
</c:if>
<c:if test="${dto.newFileName ne null }">
<img src="/photo/${dto.newFileName}"/>
</c:if>
</td>
</tr>
<tr>
<th colspan="2">
<input type="button" onclick="location.href='./list.do'" value="리스트"/>
<button>저장</button>
</th>
</tr>
</table>
</form>
</body>
<script></script>
</html>'study' 카테고리의 다른 글
| Day - 44 [Spring] mybatis 다시 (0) | 2023.04.05 |
|---|---|
| Day - 44 [Spring] File Service - AJAX (0) | 2023.04.05 |
| Day - 39,40 [SPRING] 설정 (0) | 2023.03.30 |
| Day - 35 [Maria DB] View (0) | 2023.03.22 |
| Day - 35 [Maria DB] IN _ EXISTS _ ANY _ ALL (0) | 2023.03.22 |