⁂ MyBatis Framework/: 기본 익히기

[MyBatis3] #4-4 파일 업로드 및 댓글 게시판 만들기 : 상품 등록 페이지

김갱환 2022. 11. 11. 10:20

 

1. Model

 * 짚고 넘어갈 뽀인트

-  xml에 sql문 구현(MyBatis 활용) : #{변수명}들은 DAO에서 넘어옴.

 

1) product.xml

<insert id="insert">
    INSERT INTO product(product_code, product_name, description, price, filename, filesize)
    VALUES (product_seq.nextval, #{product_name}, #{description}, #{price}, #{filename}, #{filesize})
</insert>

 

2) productDAO.java

public void insert(Map<String, Object> map) {
    sqlSession.insert("product.insert", map);
} // insert() end

 

 

 

2. View

 * 짚고 넘어갈 뽀인트

- 코드를 잘 살펴보기만 하면 될듯!

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>write.jsp</title>
	<link href="../css/main.css" rel="stylesheet" type="text/css">
</head>
<body>
	<h3>상품 등록</h3>
	<p>
		<button type="button" onclick="location.href='list'">상품전체목록</button>
	</p>
	
	<form name="form1" method="post" action="insert" enctype="multipart/form-data">
	<table border="1">
	<tr>
		<td>상품명</td>
		<td><input type="text" name="product_name"></td>
	</tr>
	<tr>
		<td>상품가격</td>
		<td><input type="number" name="price"></td>
	</tr>
	<tr>
		<td>상품설명</td>
		<td>
			<textarea rows="5" cols="60" name="description"></textarea>
		</td>
	</tr>
	<tr>
		<td>상품사진</td>
		<td><input type="file" name="img"></td>
	</tr>
	<tr>
		<td colspan="2" align="center">
			<input type="submit" value="상품등록">
		</td>
	</tr>
	</table>
	</form>
	
</body>
</html>

 

 

3. Controller

 * 짚고 넘어갈 뽀인트

- write 명령어 생성(product/write.jsp 연결)

- insert 명렁어 생성(안에서 선언되는 매개변수를 잘 살펴보자!, 만약 DTO를 만들어 사용한다면 @ModelAttribute productDTO dto 를 매개변수로 사용했을 것이다).

- 파일 처리에 대해선 코드를 잘 익숙해져야할 것이다.

// 결과 확인 http://localhost:9095/product/write
// 상품 업로드 시 리네임이 되지 않기 때문에 동일한 파일명은 업로드하면 안된다
@RequestMapping("/write")
public String write() {
    return "product/write";
} // write() end

@RequestMapping("/insert")
public String insert(@RequestParam Map<String, Object> map
                    ,@RequestParam MultipartFile img
                    ,HttpServletRequest req) {

    String filename = "-";
    long filesize = 0;
    if(img != null && !img.isEmpty()) {
        filename = img.getOriginalFilename();
        filesize = img.getSize();
        try {
            ServletContext application = req.getSession().getServletContext();
            String path = application.getRealPath("/storage");
            img.transferTo(new File(path+"\\"+filename));
        } catch (Exception e) {
            System.out.print("파일 등록 실패 : ");
            e.printStackTrace(); // 에러 출력 메서드
        } // try end			
    } // if end

    map.put("filename", filename);
    map.put("filesize", filesize);
    productDao.insert(map);
    return "redirect:/product/list";
} // insert() end