웹개발 교육/Spring

[74~5일] Spring (19) - MyBatis 프로젝트 (쓰기)

ewok 2022. 11. 11. 11:33

product 쓰기

 

ProductCont.java

	@RequestMapping("/write")
	public String write() {
		return "product/write";
	}//write() end

 

 

write.jsp

<%@ 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>

 

 

ProductCont.java

	@RequestMapping("/insert")
	public String insert(@RequestParam Map<String, Object> map
					   , @RequestParam MultipartFile img
					   , HttpServletRequest req) {
		
		//주의사항 : 파일 업로드 할 때 리네임 되지 않음
		
		//업로드된 파일을 /storage 폴더에 저장		
		String filename = "-";
		long filesize = 0;        //테이블에 filesize칼럼 추가하면 된다.
		if(img != null && !img.isEmpty()) {
			filename = img.getOriginalFilename();
			filesize = img.getSize();
			try {
				
				ServletContext application = req.getSession().getServletContext();
				String path = application.getRealPath("/storage");
				//System.out.println(path);
				//I:\java202207\workspace_spring\spring07_myshop\src\main\webapp\storage
				img.transferTo(new File(path+"\\"+filename));
				
			} catch (Exception e) {
				e.printStackTrace(); //System.out.println(e);
			}//try end
		}//if end
		
		map.put("filename", filename);
		map.put("filesize", filesize);
		productDao.insert(map);
		return "redirect:/product/list";
	}//insert() end

melon 프로젝트에서는 DTO에 담았다

 

 

ProductDAO.java

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

 

 

product.xml

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

Map을 사용했기 때문에 key값을 통해 바인딩을 한다.