[싱글이의 영수증] 수정하기
업데이트:
싱글이의 영수증 수정하기
- 출력화면
수정화면 이동 Script
<script>
$("#updateBtn").on("click",function(){
location.href= "${contextPath}/review/${review.boardNo}/update";
});
</script>
화면 전환 Controller
@RequestMapping("{boardNo}/update")
public String update(@PathVariable("boardNo") int boardNo, Model model) {
Review review = service.selectReview(boardNo);
model.addAttribute("review", review);
return "review/reviewUpdate";
}
CSS
<style>
.container {
border: 1px solid;
padding: 19px 27px 15px;
box-sizing: border-box;
border-radius: 2px;
border-color: #efefef;
}
/* 셀렉트 박스 */
/* 제목 입력 */
.titleArea {
width: 100%;
font-size: 23px;
border: none;
}
.titleArea:focus {
outline: none;
}
.note-editor {
width: 100% !important;
}
</style>
JSP
<!-- summernote 사용 시 필요한 js 파일 추가 -->
<script src="${contextPath }/resources/summernote/js/summernote-lite.js"></script>
<!-- 이 코드가 있어야 섬머노트 사용 가능 -->
<script src="${contextPath }/resources/summernote/js/summernote-ko-KR.js"></script>
<!-- 한글 패치 -->
<script src="${contextPath }/resources/summernote/js/mySummernote.js"></script>
<!-- 개인이 만든 js -->
<div class="container" style="margin-bottom: 5px;">
<div class="row ">
<div class="col-md-12">
<form action="updateAction" enctype="multipart/form-data" method="post" role="form" onsubmit="return validate();">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<select class="form-control div small" id="category" name="categoryCode" style="width: 150px;">
<option value="21">가구</option>
<option value="22">생활용품</option>
<option value="23">전자기기</option>
<option value="24">기타</option>
</select>
</div>
<div class="col-md-12 py-2">
<input class="titleArea" name="boardTitle" placeholder="제목을 적어주세요." autocomplete="off" value="${review.boardTitle }">
<hr>
</div>
</div>
<!-- 내용 -->
<div class="form-group">
<textarea class="form-control" name="boardContent" id="summernote" rows="10" style="resize: none;">${review.boardContent }</textarea>
</div>
<div class="text-center" style="margin-bottom: 10px;">
<button type="submit" class="btn btn-success">수정</button>
<a class="btn btn-success" href="${header.referer}">취소</a>
</div>
</div>
</form>
</div>
</div>
</div>
- 기존에 등록된 카테고리 선택
게시글 등록시 선택한 카테고리를 유지하기 위해 옵션태그를 반복적으로 접근해 일치하는 옵션에 selected true속성을 추가해준다.
<script>
$.each($("#category > option"), function(index, item){
if($(item).text() == "${review.categoryName}"){
$(item).prop("selected", "true");
}
});
</script>
- 유효성 검사
function validate(){
if($(".titleArea").val().trim().length ==0){
alert("제목을 입력해 주세요.");
$(".titleArea").focus();
return false;
}
if($("#summernote").val().trim().length ==0){
alert("내용을 입력해 주세요.");
$(".summernote").focus();
return false;
}
}
- 수정 Controller
변경된 게시글 정보를 데이터베이스에 update 진행
update가 성공적으로 완료 된 후, 파일에 대한 update 진행
섬머노트에 작성된 내용 중 img태그의 src속성의 값을 검사하여 매칭되는 값을 matcher객체에 저장, matcher객체에 저장된 값에 반복 접근하여 값이 있을 경우 이름을 저장한다.
기존에 등록 되어있던 파일들이 있다면 모두 delete를 수행해서 삭제
현재 새로 등록된 파일들을 attachment객체로 만들어 insert 구문을 진행
@RequestMapping("{boardNo}/updateAction")
public String updateAction(@PathVariable("boardNo") int boardNo, @ModelAttribute Review updateReview, Model model,
RedirectAttributes ra, HttpServletRequest request) {
updateReview.setBoardNo(boardNo);
// 파일 저장 경로 얻어오기
String savePath = request.getSession().getServletContext().getRealPath("resources/reviewBoardImages");
int result = service.updateReview(updateReview, savePath);
String url = null;
if(result>0) {
swalIcon = "success";
swalTitle = "게시글 수정 성공";
url = "redirect:../"+boardNo;
}else {
swalIcon = "error";
swalTitle = "게시글 수정 실패";
url = "redirect:" + request.getHeader("referer");
}
ra.addFlashAttribute("swalIcon", swalIcon);
ra.addFlashAttribute("swalTitle", swalTitle);
return url;
}
- 수정하기
Service
int updateReview(Review updateReview, String savePath);
ServiceImpl
@Transactional(rollbackFor = Exception.class)
@Override
public int updateReview(Review updateReview, String savePath) {
int result = dao.updateReview(updateReview);
if (result > 0) {
// 수정 전 파일을 모아두는 list
List<ReviewAttachment> oldFiles = dao.selectAttachmentList(updateReview.getBoardNo());
// DB에 저장할 웹 상 이미지 접근 경로
String filePath = "/resources/reviewBoardImages";
Pattern pattern = Pattern.compile("<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>");
Matcher matcher = pattern.matcher(updateReview.getBoardContent());
List<String> fileNameList = new ArrayList<String>();
String src = null;
String fileName = null;
while (matcher.find()) {
src = matcher.group(1);
fileName = src.substring(src.lastIndexOf("/") + 1);
fileNameList.add(fileName);
}
// DB에 새로 추가할 이미지파일 정보를 모아둘 List생성
List<ReviewAttachment> newAttachmentList = new ArrayList<ReviewAttachment>();
// DB에서 삭제할 이미지파일 번호를 모아둘 List 생성
List<Integer> deleteFileNoList = new ArrayList<Integer>();
// 기존에 올려둔 파일 전부 삭제
for(ReviewAttachment oldAt : oldFiles) {
deleteFileNoList.add(oldAt.getFileNo());
}
if(!deleteFileNoList.isEmpty()) { // 삭제할 이미지가 있다면
result = dao.deleteAttachmentList(deleteFileNoList);
if(result != deleteFileNoList.size()) {
throw new InsertAttachmentFailException("파일 수정 실패(파일 정보 삭제 중 오류 발생)");
}
}
// 새로운 파일 전부 등록
// 파일 레벨
int fileLevel = 1;
for (String fName : fileNameList) {
ReviewAttachment at = new ReviewAttachment(filePath, fName, fileLevel, updateReview.getBoardNo());
newAttachmentList.add(at);
fileLevel++;
}
if(!newAttachmentList.isEmpty()) {
result = dao.insertAttachmentList(newAttachmentList);
if(result != newAttachmentList.size()) {
throw new InsertAttachmentFailException("파일 수정 실패(파일 정보 삽입 중 오류 발생)");
}
}
}
return result;
}
- 게시글 수정
DAO
public int updateReview(Review updateReview) {
return sqlSession.update("reviewMapper.updateReview", updateReview);
}
Mapper
<update id="updateReview" parameterType="Review">
UPDATE BOARD SET
BOARD_TITLE = #{boardTitle},
BOARD_CONTENT = #{boardContent},
CATEGORY_CD = #{categoryCode}
WHERE BOARD_NO = #{boardNo}
</update>
- 기존 파일 정보 조회
DAO
public List<ReviewAttachment> selectAttachmentList(int boardNo) {
return sqlSession.selectList("reviewMapper.selectAttachmentList", boardNo);
}
Mapper
<select id="selectAttachmentList" parameterType="_int"
resultMap="attachment_rm">
SELECT * FROM BOARD_FILE
WHERE PARENT_BOARD_NO = ${boardNo}
ORDER BY FILE_LEVEL
</select>
- 기존에 업로드된 이미지 삭제
DAO
public int deleteAttachmentList(List<Integer> deleteFileNoList) {
return sqlSession.delete("reviewMapper.deleteAttachmentList", deleteFileNoList);
}
Mapper
<delete id="deleteAttachmentList" parameterType="list">
DELETE FROM BOARD_FILE
WHERE FILE_NO IN
<foreach collection="list" item="fileNo" open="(" close=")"
separator=",">
${fileNo}
</foreach>
</delete>
- 새로운 파일 등록
DAO
public int insertAttachmentList(List<ReviewAttachment> uploadImages) {
return sqlSession.insert("reviewMapper.insertAttachmentList", uploadImages);
}
Mapper
<insert id="insertAttachmentList" parameterType="list">
INSERT INTO BOARD_FILE
SELECT SEQ_FNO.NEXTVAL, A.* FROM (
<foreach collection="list" item="item" separator="UNION ALL">
SELECT #{item.filePath} FILE_PATH,
#{item.fileName} FILE_NM,
#{item.parentBoardNo} PARENT_BOARD_NO,
#{item.fileLevel} FILE_LEVEL
FROM DUAL
</foreach>
)A
</insert>
공유하기
Twitter Google+ LinkedIn
댓글남기기