본문 바로가기

데이터 분석/Spring

Martin's Bookshelf_Part 5 : BOOK CRUD(Create)

book_list.jsp 페이지에서 CRUD 작업을 수행할 수 있게 하는 로그인/아웃 기능을 구현했다. 이제 새로운 책을 추가하는 기능을 구현할 순서이다.

  1. JSP 파일에 새로운 책 정보를 등록하기 전 로그인 여부를 확인 하는 JS function 추가

  2. BookController에 새로운 책 책 정보를 입력할 Form을 띄우는 리퀘스트 코딩(insert_form.do)

  3. book_insert_form.jsp 작업
    1. 파일 업로드를 위해 Post로 Method 설정
    2. 새로운 책 정보 입력 Form 구성
    3. 신규 정보 등록 / 취소(메인 페이지로 돌아가기) 기능 버튼 구현
    4. 신규 정보 등록 이전 파일 첨부 여부를 확인하는 JS function

  4. BookController 에서 insert.do 리퀘스트 코딩 (상세작업은 첨부한 코딩의 주석으로 해설)

  5. BookDao 에서 insert method 코딩

  6. Mapper에서 SQL문 코딩

 


Step 1: 새로운 책 정보를 등록하기 전 로그인 여부를 확인 하는 JS function 추가

 

<Step 2: BookController에 새로운 책 책 정보를 입력할 Form을 띄우는 리퀘스트 코딩(insert_form.do)>

더보기
	@RequestMapping("/book/insert_form.do")
	public String insert_form() {		
		
		return "book/book_insert_form";
	}

 

<Step 3: book_insert_form.jsp 작업>

더보기

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add New Book</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">

#box{
	width: 800px;
	margin: auto;
	margin-top: 100px;
}

textarea {
	width: 98%;
	height: 100px;
}

input[type='button']{
	width: 100px;
	margin-top: 10px;
}

</style>

<script type="text/javascript">

	function send(f){
		
		var b_photo		= f.b_photo.value;
				
		if(b_photo==""){
			alert("책 표지 사진을 첨부해주세요");
			return;
		}
		
		f.action = "insert.do";
		f.submit();
		
	}


</script>


</head>
<body>

<form method="POST" enctype="multipart/form-data">
<input type="hidden" value="${ sessionScope.user.m_idx }">
	<div id="box">
		<div class="panel panel-primary">
		    <div class="panel-heading">Add New Book</div>
		    <div class="panel-body">
		    	<table class="table">
		    		<tr>
		    			<th>분류</th>
		    			<td><input type="text" name="b_category" required="required"></td>
		    			
		    			<th>완독일</th>
		    			<td><input type="text" name="b_readdate"></td>		    			
		    		</tr>
		    	
		    		<tr>
		    			<th>제목</th>
		    			<td><input type="text" name="b_title" required="required"></td>
		    			
		    			<th>부제</th>
		    			<td><input type="text" name="b_subtitle"></td>
		    		</tr>	    		
		    		
		    		<tr>
		    			<th>작가</th>
		    			<td><input type="text" name="b_author" required="required"></td>
		    			
		    			<th>쪽수</th>
		    			<td><input type="text" name="b_pages"></td>
		    		</tr>
		    				    		
		    		<tr>
		    			<th>출판사</th>
		    			<td><input type="text" name="b_publisher" required="required"></td>
		    			
		    			<th>출판일</th>
		    			<td><input type="text" name="b_published"></td>
		    		</tr>
		    			    				    		
		    		<tr>
		    			<th>책 설명</th>
		    			<td colspan="3"><textarea name="b_desc">간단한 감상문</textarea></td>
		    		</tr>
		    		
		    		<tr>
		    			<th>표지</th>
		    			<td colspan="3">
		    			<input type="file" name="b_photo">
		    			</td>
		    		</tr>
		    		
		    		<tr>
		    			<td colspan="2" align="center">
		    				<input class="btn btn-primary" type="button" value="Upload" onclick="send(this.form);">
		    				<input class="btn btn-danger" type="button" value="Cancle" onclick="location.href='list.do'">
		    			</td>
		    		</tr>
		    	
		    	</table>
		    </div>
	    </div>	
	</div>
</form>


</body>
</html>

 

<Step 4: BookController 에서 insert.do 리퀘스트 코딩>

더보기
@Autowired
	ServletContext application;
	
	@Autowired
	HttpSession session;
	
	@Autowired
	HttpServletRequest request;
	
	@RequestMapping("/book/insert.do")
	public String insert(BookVo vo, @RequestParam MultipartFile b_photo, Model model ) throws Exception {
		
		// 파일명 지역변수 생성
		String b_filename = "fail_upload";
		
		// b_photo가 첨부 되었다면 
		if (!b_photo.isEmpty()) {
			
			// 파일이 업로드 되는 웹경로 -> 절대 경로화
			String web_path = "/resources/upload/";
			String abs_path = application.getRealPath(web_path);
			
			// 업로드 되는 b_photo의 본래 파일명을 b_filename에 저장
			b_filename = b_photo.getOriginalFilename();
			
			// 파일을 관리하는 객체 f 생성 (저장 경로, 파일 이름)
			File f = new File(abs_path, b_filename);
			
			// 저장 경로에 해당 파일명을 가진 중복된 파일이 있을 경우
			if (f.exists()) {
				long tm = System.currentTimeMillis();
				b_filename = String.format("%d_%s", tm , b_filename);
				f = new File(abs_path, b_filename);
			}
			
			// 모든 파일처리 과정을 끝냄
			b_photo.transferTo(f);	
			
		}
		
		// 최종적으로 결정된 파일명을 VO에 저장
		vo.setB_filename(b_filename);
		
		// SessionScope에 있는 user의 정보를 활용하여 m_idx 정보 획득
		MemberVo user = (MemberVo) session.getAttribute("user"); 
		int m_idx = user.getM_idx();
		vo.setM_idx(m_idx);
		
		String b_ip = request.getRemoteAddr();
		vo.setB_ip(b_ip);
		
		int res = book_dao.insert(vo);		
		
		return "redirect:/book/list.do";
	}

 

<Step 5: BookDao 에서 insert method 코딩 & Mapper에서 SQL문 코딩>

 


잘 작동한다.