본문 바로가기
ICIA 수업일지

2021.09.06 수업일지(Mysql, Servlet, JSTL)

by 주성씨 2021. 9. 6.

- new arrival 라고 하여 새로 추가된 상품들을 슬라이더로 보여주는 작업을 하겠다.

 

- productdao.java

- 최신상품 목록 출력 메서드 생성

	// 4. 최신상품 목록 리스트 메서드
	public JSONArray newList(){
		JSONArray array = new JSONArray();
		
		try {
			String sql = "select * from product order by prod_id desc limit 0,10";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				JSONObject object = new JSONObject();
				object.put("prod_name", rs.getString("prod_name"));
				object.put("image", rs.getString("image"));
				array.add(object);
			}
		} catch (Exception e) {
			System.out.println("ProductDAO newList : " +e.toString());
		}
		
		return array;
	}

 

- prodrestservlet.java

- 새로운 제품 리스트를 출력할 json 데이터를 만들기 위한 servlet을 지정한다.

@WebServlet(value={"/new_product.json","/mall_search.json","/product.json"})
public class ProdRESTServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ProductDAO dao = new ProductDAO();
	MallDAO mdao = new MallDAO();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		switch (request.getServletPath()) {
		case "/new_product.json":
			out.println(dao.newList());
			break;
		case "/mall

 

출력물

 

- 핸들바를 이용해서 리스트가 슬라이드 형식으로 나오는 출력물을 만들어보겠다.

- about.jsp

<h1>New Arrival</h1>
<div id="slider">
	<div id="items"></div>
</div>
<script id="tempSlider" type="text/x-handlebars-template">
   {{#each .}}
   <div class="new" style="border:1px solid gray;">
      <img src="/image/product/{{image}}"/>
      <div class="name">{{prod_name}}</div>
   </div>
   {{/each}}
</script>

 

$.ajax({
		type : "get",
		url : "/new_product.json",
		dataType : "json",
		success : function(data) {
			var temp = Handlebars.compile($("#tempSlider").html());
			$("#items").html(temp(data));
		}
	});

	setInterval(function(){
	      $('#items .new:first').animate({ marginLeft:-110 }, 300, function(){
	            $(this).appendTo($('#items')).css({marginLeft:10});
	        });
	   }, 2500);

 

#slider {
	position: relative;
	overflow: hidden;
	width: 810px;
	height: 150px;
	margin: 0px auto;
}

#items {
	position: absolute;
	width: 1620px;
	overflow: hidden;
	margin-left: -162px;
}

#items .new {
	width: 150px;
	float: left;
	margin-left: 10px;
	heigth: 150px;
}

#items .new img {
	width: 150px;
}

#items .new .name {
	width: 150px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	font-size: 10px;
	margin-top: 10px;
	padding: 5px;
}

 

출력물

 

- 업체목록 페이지를 만들어보도록 하겠다.

- main.jsp

		<div id="center">
			<div id="menu">
				<h4>
					<a href="">Home</a>
				</h4>
				<h4>
					<a href="/mall/list">업체목록</a>
				</h4>
				<h4>
					<a href="">상품목록</a>
				</h4>

 

- create new controller\MallServlet.java

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = { "/mall/list", "/mall/insert", "/mall/update", "/mall/read", "/mall/delete" })
public class MallServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		switch (request.getServletPath()) {
		case "/mall/list":
			request.setAttribute("pageName", "/mall/list.jsp");
			RequestDispatcher dis = request.getRequestDispatcher("/main.jsp");
			dis.forward(request, response);
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

 

- create new mall\list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h1>업체목록</h1>

 

- search가 아닌 list 메서드를 만들도록 하겠다.

- MallDAO.java

	// 2. 업체 목록 출력
	public JSONObject list(SqlVO vo) {
		JSONObject object = new JSONObject();

		try {
			String sql = "call list(?,?,?,?,?,?,?)";
			CallableStatement cs = Database.CON.prepareCall(sql);
			cs.setString(1, vo.getTable());
			cs.setString(2, vo.getKey());
			cs.setString(3, vo.getWord());
			cs.setString(4, vo.getOrder());
			cs.setString(5, vo.getDesc());
			cs.setInt(6, vo.getPage());
			cs.setInt(7, vo.getPerPage());
			cs.execute();

			ResultSet rs = cs.getResultSet();
			JSONArray array = new JSONArray();
			while (rs.next()) {
				JSONObject obj = new JSONObject();
				obj.put("mall_id", rs.getString("mall_id"));
				obj.put("mall_name", rs.getString("mall_name"));
				obj.put("address", rs.getString("address"));
				obj.put("tel", rs.getString("tel"));
				obj.put("email", rs.getString("email"));
				array.add(obj);
			}
			object.put("array", array);

			cs.getMoreResults();
			rs = cs.getResultSet();
			if (rs.next()) {
				object.put("total", rs.getInt("count(*)"));
			}
		} catch (Exception e) {
			System.out.println("MallDAO list : " + e.toString());
		}

		return object;
	}

 

- create new controller\MallRESTServlet.java

package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MallDAO;
import model.ProductDAO;
import model.SqlVO;

@WebServlet(value = { "/mall.json" })
public class MallRESTServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ProductDAO dao = new ProductDAO();
	MallDAO mdao = new MallDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		switch (request.getServletPath()) {
		case "/mall.json":
			SqlVO vo = new SqlVO();
			vo.setTable("mall");
			vo.setKey("mall_id");
			vo.setWord("");
			vo.setOrder("mall_id");
			vo.setDesc("");
			vo.setPage(1);
			vo.setPerPage(2);
			out.println(mdao.list(vo));
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

 

출력물

 

- json으로 받아온 데이터를 template을 이용하여 list.jsp에 출력할 수 있도록 하겠다.

- list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<style>
table {
	border-collapse: collapse;
	margin: 0px auto;
	margin-bottom: 10px;
}

th {
	background: rgb(242, 242, 242);
	color: black;
}

th, td {
	border: 1px solid black;
	padding: 10px;
}
.row:hover{
	cursor: pointer;
	background: rgb(242, 242, 242);
	color: black;
}
</style>
<h1>업체목록</h1>
<div id="condition">
	<select id="key">
		<option value="mall_id">업체번호</option>
		<option value="mall_name">업체명</option>
		<option value="address">업체주소</option>
		<option value="tel">전화번호</option>
	</select> <input type="text" id="word" placeholder="검색어 입력" /> <select
		id="perPage">
		<option value=2>2개</option>
		<option value=4>4개</option>
		<option value=8>8개</option>
		<option value=12>12개</option>
	</select> 검색수 : <span id="total"></span> <select id="desc" style="float: right;">
		<option value="">오름차순</option>
		<option value="desc" selected>내림차순</option>
	</select> <select id="order" style="float: right; margin-right: 5px;">
		<option value="mall_id">업체번호</option>
		<option value="mall_name">업체명</option>
		<option value="address">업체주소</option>
		<option value="tel">전화번호</option>
	</select>
</div>

<table id="tbl"></table>
<div id="pagination">
	<button id="prev">&lt;</button>
	<span id="page"></span>
	<button id="next">&gt;</button>
</div>
<script id="temp" type="text/x-handlebars-template">
	<tr class="title">
		<th width=100>업체코드</th>
		<th width=100>업체명</th>
		<th width=300>주소</th>
		<th width=150>전화번호</th>
		<th width=150>이메일</th>
	</tr>
   {{#each array}}
	<tr class="row">
		<td>{{mall_id}}</td>
		<td>{{mall_name}}</td>
		<td>{{address}}</td>
		<td>{{tel}}</td>
		<td>{{email}}</td>
	</tr>
   {{/each}}
</script>

<script>
	var page = 1;
	
	$("#prev").on("click", function() {
		page--;
		getNewList();
	});
	$("#next").on("click", function() {
		page++;
		getNewList();
	})
	$("#word").on("keypress", function(e) {
		if (e.keyCode == 13) {
			page = 1;
			getNewList();
		}
	});
	$("#perPage, #order, #desc").on("change", function() {
		page = 1;
		getNewList();
	});
	
	getNewList();
	function getNewList() {
		var key = $('#key').val();
		var word = $('#word').val();
		var perPage = $('#perPage').val();
		var order = $('#order').val();
		var desc = $('#desc').val();
		$.ajax({
			type : 'get',
			url : '/mall.json',
			dataType : 'json',
			data : {
				"key" : key,
				"word" : word,
				"page" : page,
				"perPage" : perPage,
				"order" : order,
				"desc" : desc
			},
			success : function(data) {
				var temp = Handlebars.compile($('#temp').html());
				$('#tbl').html(temp(data));
				$('#total').html(data.total);
				var lastPage = Math.ceil(data.total / perPage)
				$('#page').html("[ " + page + "/" + lastPage + " ]");
				if (page == 1) {
					$('#prev').attr('disabled', true);
					$('#prev').css('background', 'gray')
				} else {
					$('#prev').attr('disabled', false);
					$('#prev').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
				if (page == lastPage) {
					$('#next').attr('disabled', true);
					$('#next').css('background', 'gray');
				} else {
					$('#next').attr('disabled', false);
					$('#next').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
			}
		})
	}
</script>

 

출력물

 

- 상품목록을 출력하는 페이지를 만들도록 하겠다.

- main.jsp

				<h4>
					<a href="/mall/list">업체목록</a>
				</h4>
				<h4>
					<a href="/product/list">상품목록</a>
				</h4>
				<h4>
					<a href="/product/insert">상품등록</a>
				</h4>

 

- create new product\list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h1>상품목록</h1>

 

- productServlet.java

@WebServlet(value = { "/product/list","/product/insert", "/product/read", "/product/update", "/product/delete" })
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProductDAO dao = new ProductDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		switch (request.getServletPath()) {
		
		case "/product/list":
			request.setAttribute("pagaName", "/product/list.jsp");
			break;

 

- list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<style>
table {
	border-collapse: collapse;
	margin: 0px auto;
	margin-bottom: 10px;
}

th {
	background: rgb(242, 242, 242);
	color: black;
}

th, td {
	border: 1px solid black;
	padding: 10px;
}
.row:hover{
	cursor: pointer;
	background: rgb(242, 242, 242);
	color: black;
}
</style>

<h1>상품목록</h1>

<div id="condition">
	<select id="key">
		<option value="prod_id">상품코드</option>
		<option value="prod_name">상품이름</option>
		<option value="mall_name">업체명</option>
	</select> <input type="text" id="word" placeholder="검색어 입력" /> <select
		id="perPage">
		<option value=4>4개</option>
		<option value=8>8개</option>
		<option value=12>12개</option>
		<option value=16>16개</option>
	</select> 검색수 : <span id="total"></span> <select id="desc" style="float: right;">
		<option value="">오름차순</option>
		<option value="desc" selected>내림차순</option>
	</select> <select id="order" style="float: right; margin-right: 5px;">
		<option value="prod_id">상품코드</option>
		<option value="prod_name">상품이름</option>
		<option value="mall_name">업체명</option>
	</select>
</div>

<table id="tbl"></table>
<div id="pagination">
	<button id="prev">&lt;</button>
	<span id="page"></span>
	<button id="next">&gt;</button>
</div>
<script id="temp" type="text/x-handlebars-template">
	<tr class="title">
		<th width=50>코드</th>
		<th width=350>상품명</th>
		<th width=200>업체명</th>
		<th width=100>제조사</th>
		<th width=100>일반가</th>
		<th width=100>판매가</th>
		<th width=100>장바구니</th>
		<th width=100>상품번호</th>
	</tr>
   {{#each array}}
	<tr class="row">
		<td>{{prod_id}}</td>
		<td>{{prod_name}}</td>
		<td>{{mall_name}}</td>
		<td>{{company}}</td>
		<td>{{price2}}</td>
		<td>{{price}}</td>
		<td><button>장바구니</button></td>
		<td><button>상품정보</button></td>
	</tr>
   {{/each}}
</script>

<script>
	var page = 1;
	
	$("#prev").on("click", function() {
		page--;
		getList();
	});
	$("#next").on("click", function() {
		page++;
		getList();
	})
	$("#word").on("keypress", function(e) {
		if (e.keyCode == 13) {
			page = 1;
			getList();
		}
	});
	$("#perPage, #order, #desc").on("change", function() {
		page = 1;
		getList();
	});
	
	getList();
	function getList() {
		var key = $('#key').val();
		var word = $('#word').val();
		var perPage = $('#perPage').val();
		var order = $('#order').val();
		var desc = $('#desc').val();
		$.ajax({
			type : 'get',
			url : '/product.json',
			dataType : 'json',
			data : {
				"key" : key,
				"word" : word,
				"page" : page,
				"perPage" : perPage,
				"order" : order,
				"desc" : desc
			},
			success : function(data) {
				var temp = Handlebars.compile($('#temp').html());
				$('#tbl').html(temp(data));
				$('#total').html(data.total);
				var lastPage = Math.ceil(data.total / perPage)
				$('#page').html("[ " + page + "/" + lastPage + " ]");
				if (page == 1) {
					$('#prev').attr('disabled', true);
					$('#prev').css('background', 'gray')
				} else {
					$('#prev').attr('disabled', false);
					$('#prev').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
				if (page == lastPage) {
					$('#next').attr('disabled', true);
					$('#next').css('background', 'gray');
				} else {
					$('#next').attr('disabled', false);
					$('#next').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
			}
		})
	}
</script>

 

- sql

- product 테이블에는 mall_name이 없으므로 view_product라는 이름의 view를 새로 만들겠다.

create view view_product as
select p.*,m.mall_name
from product p, mall m
where p.mall_id=m.mall_id;

select * from view_product;

 

- ProdRESTServlet.java

		case "/product.json": // renew
			SqlVO vo = new SqlVO();
			vo.setTable("view_product");
			vo.setKey(request.getParameter("key"));
			vo.setWord(request.getParameter("word"));
			vo.setOrder(request.getParameter("order"));
			vo.setDesc(request.getParameter("desc"));
			vo.setPage(Integer.parseInt(request.getParameter("page")));
			vo.setPerPage(Integer.parseInt(request.getParameter("perPage")));
			out.println(dao.list(vo));
			break;
		}

 

- ProductDAO에서 list 메서드를 사용하는데 기존에는 이미지, 상품코드, 상품아이디만 배열에 담았으니 상품목록 출력에 필요한 값들도 담아주도록 한다.

- ProductDAO.java

	// 1. 상품목록 출력 메서드
	public JSONObject list(SqlVO vo) {
		JSONObject object = new JSONObject();
		try {
			String sql = "call list(?,?,?,?,?,?,?)";
			CallableStatement cs = Database.CON.prepareCall(sql);
			cs.setString(1, vo.getTable());
			cs.setString(2, vo.getKey());
			cs.setString(3, vo.getWord());
			cs.setString(4, vo.getOrder());
			cs.setString(5, vo.getDesc());
			cs.setInt(6, vo.getPage());
			cs.setInt(7, vo.getPerPage());
			cs.execute();

			ResultSet rs = cs.getResultSet();
			JSONArray array = new JSONArray();
			while (rs.next()) {
				JSONObject obj = new JSONObject();
				obj.put("image", rs.getString("image"));
				obj.put("prod_id", rs.getString("prod_id"));
				obj.put("prod_name", rs.getString("prod_name"));
				obj.put("mall_name", rs.getString("mall_name"));
				obj.put("company", rs.getString("company"));
				DecimalFormat df = new DecimalFormat("#,###");
				String price = df.format(rs.getInt("price1"));
				obj.put("price", price);
				obj.put("price2", df.format(rs.getInt("price2")));
				array.add(obj);
			}
			object.put("array", array);

			cs.getMoreResults();
			rs = cs.getResultSet();
			if (rs.next()) {
				object.put("total", rs.getInt("count(*)"));
			}
			;

		} catch (Exception e) {
			System.out.println("ProductDAO list : " + e.toString());
		}
		return object;
	}

 

출력물

 

- 상품목록에서 상품정보를 보고 수정하는 작업을 하도록 하겠다.

- list.jsp

   {{#each array}}
	<tr class="row">
		<td>{{prod_id}}</td>
		<td>{{prod_name}}</td>
		<td>{{mall_name}}</td>
		<td>{{company}}</td>
		<td>{{price2}}</td>
		<td>{{price}}</td>
		<td><button>장바구니</button></td>
		<td><button onClick="location.href='/product/read?prod_id={{prod_id}}'">상품정보</button></td>
	</tr>
   {{/each}}

 

- ProductServlet.java

@WebServlet(value = { "/product/list","/product/insert", "/product/read", "/product/update", "/product/delete" })
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProductDAO dao = new ProductDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		switch (request.getServletPath()) {
		case "/product/read":
			request.setAttribute("pageName", "/product/read.jsp");
			break;

 

- product\insert.jsp를 복사해서 read.jsp를 만들도록 하겠다.

- create new product\read.jsp

- 변경전

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<style>
table {
	border-collapse: collapse;
	margin: 0px auto;
	margin-bottom: 10px;
}

.title {
	background: rgb(246, 246, 246);
	color: dark-gray;
	text-align: center;
}

tr, td {
	border: 1px solid black;
	padding: 10px;
}

.btnbox input {
	padding: 10px 40px 10px 40px;
	font-size: 15px;
	font-weight: bold;
	color: black;
	border-radius: 5px 5px 5px 5px;
}
</style>
<h1>상품정보</h1>
<form name="frm" enctype="multipart/form-data">
	<table>
		<tr>
			<td class="title" width=100>상품코드</td>
			<td width=120><input type="text" name="prod_id" value="${code}"
				readonly /></td>
			<td class="title" width=100>제조원/수입원</td>
			<td width=120><input type="text" name="company"
				placeholder="제조사를 입력하세요." /></td>
			<td class="title" width=100>판매가격</td>
			<td width=120><input type="text" name="price1" value=0 /></td>
		</tr>
		<tr>
			<td class="title">업체코드</td>
			<td colspan=3><input type="text" name="mall_id"
				placeholder="코드를 입력하세요." />&nbsp; <input type="text"
				name="mall_name" placeholder="판매자를 입력하세요." /></td>
			<td class="title">일반가격</td>
			<td><input type="text" name="price2" value=0 /></td>
		</tr>
		<tr>
			<td class="title">상품이름</td>
			<td colspan=5><input type="text" name="prod_name"
				placeholder="상품이름을 입력하세요." size=100% /></td>
		</tr>
		<tr>
			<td class="title">상품이미지</td>
			<td colspan=5><img src="http://placehold.it/200/200" id="image" />
				<input type="file" name="image" style="visibility: hidden;"
				accept="image/*" width=300px/></td>
		</tr>
		<tr>
			<td class="title">상품설명</td>
			<td colspan=5><textarea rows="15" cols="110" id="editor"
					name="detail"></textarea></td>
		</tr>
	</table>
	<div style="text-align: center;" class="btnbox">
		<input type="submit" value="상품등록" /> <input type="reset" value="등록취소" />
	</div>
</form>
<script>
	// submit을 클릭했을 경우
	$(frm).on('submit',function(e){
		e.preventDefault();
		var prod_name=$(frm.prod_name).val();
		var mall_id=$(frm.mall_id).val();
		var image=$(frm.image).val();
		var company=$(frm.company).val();
		
		if(company==""){
			alert("제조업체를 입력하세요.");
			$(frm.company).focus();
			return;
		}
		if(prod_name==""){
			alert("상품 이름을 입력하세요.");
			$(frm.prod_name).focus();
			return;
		}
		if(mall_id==""){
			alert("업체 크드를 등록하세요.");
			$(frm.mall_id).focus();
			return;
		}
		if(image==""){
			alert("상품 이미지를 등록하세요.");
			$(frm.image).focus();
			return;
		}
		if(!confirm("해당 상품을 등록하시겠습니까?")) return;

		frm.action = "/product/insert";
		frm.method = "post";
		frm.submit();
		
	})

	// frm mall_id click
	$(frm.mall_id).on(
			'click',
			function() {
				window.open('/mall/search.jsp', 'mall',
						'width=400,height=300,top=200,left=900');
			})

	// 이미지 클릭했을때
	$('#image').on('click', function() {
		$(frm.image).click();
	})

	// 미리보기
	$(frm.image).on('change', function() {
		var reader = new FileReader();
		reader.onload = function(e) {
			$("#image").attr("src", e.target.result);
		}
		reader.readAsDataURL(this.files[0]);
	});

	var ckeditor_config = {
		resize_enable : false, //editor 사이즈를 변경하지 못한다.
		enterMode : CKEDITOR.ENTER_BR,
		shiftEnterMode : CKEDITOR.ENTER_P,
		filebrowserUploadUrl : "/ckupload",
		height : 300
	};
	CKEDITOR.replace('editor', ckeditor_config)
</script>

 

- create new model\MallVO.java

package model;

public class MallVO {
	private String mall_id;
	private String mall_name;
	private String manager;
	private String address;
	private String tel;
	private String email;
	private String detail;

 

- ProductVO.java

- mall_name이 필요하므로 mallVO 상속

package model;

public class ProductVO extends MallVO{
	private String prod_id;
	private String prod_name;
	private String mall_id;
	private String company;
	private int price1;
	private int price2;
	private String detail;
	private String image;
	private String prod_del;

 

- ProductDAO.java

	// 5. 상품정보 읽기 메서드
	public ProductVO read(String prod_id){
		ProductVO vo = new ProductVO();
		try {
			String sql = "select * from view_product where prod_id=?";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ps.setString(1, prod_id);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				vo.setProd_id(rs.getString("prod_id"));
				vo.setProd_name(rs.getString("prod_name"));
				vo.setCompany(rs.getString("company"));
				vo.setPrice1(rs.getInt("price1"));
				vo.setPrice2(rs.getInt("price2"));
				vo.setImage(rs.getString("image"));
				vo.setDetail(rs.getString("detail"));
				vo.setMall_id(rs.getString("mall_id"));
				vo.setMall_name(rs.getString("mall_name"));
				vo.setProd_del(rs.getString("prod_del"));
			}
		} catch (Exception e) {
			System.out.println("ProductDAO read : "+e.toString());
		}
		return vo;
	}

 

- ProductServlet.java

@WebServlet(value = { "/product/list","/product/insert", "/product/read", "/product/update", "/product/delete" })
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProductDAO dao = new ProductDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		switch (request.getServletPath()) {
		case "/product/read":
			request.setAttribute("vo", dao.read(request.getParameter("prod_id"))); // new
			request.setAttribute("pageName", "/product/read.jsp");
			break;

 

- read.jsp

- 변경후

<h1>상품정보</h1>
<form name="frm" enctype="multipart/form-data">
	<table>
		<tr>
			<td class="title" width=100>상품코드</td>
			<td width=120><input type="text" name="prod_id" value="${vo.prod_id}"
				readonly /></td>
			<td class="title" width=100>제조원/수입원</td>
			<td width=120><input type="text" name="company" value="${vo.company }"
				placeholder="제조사를 입력하세요." /></td>
			<td class="title" width=100>판매가격</td>
			<td width=120><input type="text" name="price1" value="${vo.price1}" /></td>
		</tr>
		<tr>
			<td class="title">업체코드</td>
			<td colspan=3><input type="text" name="mall_id"
				value="${vo.mall_id}" />&nbsp; <input type="text"
				name="mall_name" value="${vo.mall_name}" /></td>
			<td class="title">일반가격</td>
			<td><input type="text" name="price2" value="${vo.price2}" /></td>
		</tr>
		<tr>
			<td class="title">상품이름</td>
			<td colspan=5><input type="text" name="prod_name"
				value="${vo.prod_name}" size=100% /></td>
		</tr>
		<tr>
			<td class="title">상품이미지</td>
			<td colspan=5><img src="/image/product/${vo.image}" id="image" />
				<input type="file" name="image" style="visibility: hidden;"
				accept="image/*" width=300px/></td>
		</tr>
		<tr>
			<td class="title">상품설명</td>
			<td colspan=5><textarea rows="15" cols="110" id="editor"
					name="detail">${vo.detail}</textarea></td>
		</tr>
	</table>
	<div style="text-align: center;" class="btnbox">
		<input type="submit" value="상품수정" /> <input type="reset" value="수정취소" />
	</div>
</form>

 

출력물

 

- c 태그 라이브러리를 이용해서 삼항연산자를 사용해 DB에서 prod_del의 값에 따라 판매중지 유무를 checkbox에서 표시할 수 있도록 하겠다.

- c 테그 라이브러리 추가

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 

		<tr>
			<td class="title">상품이미지</td>
			<td colspan=5><img src="/image/product/${vo.image}" id="image" />
				<input type="file" name="image" style="visibility: hidden;"
				accept="image/*" width=300px/></td>
		</tr>

ㄴ 추가

 

update product set detail='<h1>상세설명</h1>' where prod_id='P112';
update product set prod_del=1 where prod_id='P112';

ㄴ sql 수정

 

출력물

 

- 수정할 경우의 서블릿을 지정해주겠다.

- read.jsp

		var prod_del =$(frm.prod_del).prop(":checked")?1:0; // new
		
		$(frm.prod_del).val(prod_del); // new
		
		if(!confirm("해당 상품을 등록하시겠습니까?")) return;
		frm.action = "/product/update";
		frm.method = "post";
		frm.submit();

 

- productServlet.java

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MultipartRequest multi = new MultipartRequest(request, "c:/image/product", 1000 * 1000 * 10, "UTF-8",
				new DefaultFileRenamePolicy());
		String strImage = multi.getFilesystemName("image");

		ProductVO vo = new ProductVO();
		vo.setProd_id(multi.getParameter("prod_id"));
		vo.setProd_name(multi.getParameter("prod_name"));
		vo.setCompany(multi.getParameter("company"));
		vo.setMall_id(multi.getParameter("mall_id"));
		vo.setDetail(multi.getParameter("detail"));
		vo.setPrice1(Integer.parseInt(multi.getParameter("price1")));
		vo.setPrice2(Integer.parseInt(multi.getParameter("price2")));
		vo.setImage(strImage);

		switch (request.getServletPath()) {
		case "/product/insert":
			dao.insert(vo);
			break;
		case "/product/update": // new
			String prod_del = multi.getParameter("prod_del")==null?"0":"1";
			vo.setProd_del(prod_del);
			System.out.println(vo.toString());
			break;
		}

		response.sendRedirect("/product/list");
	}

 

확인

 

- 이미지가 null인 경우를 방지하기 위해서 oldImage라는 name의 input tag를 만들어보자.

- 이미지가 변경된 경우에는 새로운 파일명이 들어가지만 그렇지 않은 경우는 기존 이미지의 파일명이 들어가도록 하겠다.

- read.jsp

		<tr>
			<td class="title">상품이미지</td>
			<td colspan=5>
			<img src="/image/product/${vo.image}" id="image" />
            <!-- new -->
			<input type="text" name="oldImage" value="${vo.image}" />
			<input type="file" name="image" style="visibility: hidden;" accept="image/*" width=300px/></td>
		</tr>

 

- productServlet.java - doPost

		case "/product/update": // new
			String prod_del = multi.getParameter("prod_del") == null ? "0" : "1";
			vo.setProd_del(prod_del);
			if (vo.getImage() == null)
				vo.setImage(multi.getParameter("oldImage"));
			System.out.println(vo.toString());
			break;
		}

 

 

- 업데이트 메서드를 만들어서 db에 반영하도록 하겠다.

- productdao.java

	// 6. 상품정보 업데이트 메서드
	public void update(ProductVO vo) {
		try {
			String sql = "update product set prod_name=?, company=?,image=?, mall_id=?, price1=?, price2=?, detail=?, prod_del=? where prod_id=?";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ps.setString(1, vo.getProd_name());
			ps.setString(2, vo.getCompany());
			ps.setString(3, vo.getImage());
			ps.setString(4, vo.getMall_id());
			ps.setInt(5, vo.getPrice1());
			ps.setInt(6, vo.getPrice2());
			ps.setString(7, vo.getDetail());
			ps.setString(8, vo.getProd_del());
			ps.setString(9, vo.getProd_id());
			ps.execute();
		} catch (Exception e) {
			System.out.println("ProductDAO update : " + e.toString());
		}
	}

 

- 새로운 이미지가 들어간다면 기존 이미지를 디스크에서 삭제해주도록 하겠다.

- ProductServlet.java

		case "/product/update": // new
			String prod_del = multi.getParameter("prod_del") == null ? "0" : "1";
			vo.setProd_del(prod_del);
			if (vo.getImage() == null) {
				vo.setImage(multi.getParameter("oldImage"));
			} else {
				// 옛날이미지 삭제
				File file =new File("c:/image/product"+multi.getParameter("oldImage"));
				file.delete();
			}
			dao.update(vo);
			break;
		}

출력물

 

- 주문목록 페이지가 나오도록 하겠다.

- main.jsp

				<h4>
					<a href="/product/insert">상품등록</a>
				</h4>
				<h4>
					<a href="/purchase/list">주문목록</a> <!-- new -->
				</h4>
				<h4>
					<a href="">장바구니</a>
				</h4>

 

- create new model\PurchaseDAO.java

- 주문 목록 출력을 위한 메서드 생성

package model;

import java.sql.CallableStatement;
import java.sql.ResultSet;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class PurchaseDAO {
	// 1. 구매목록 출력 메서드
	public JSONObject list(SqlVO vo) {
		JSONObject object = new JSONObject();

		try {
			String sql = "call list(?,?,?,?,?,?,?)";
			CallableStatement cs = Database.CON.prepareCall(sql);
			cs.setString(1, vo.getTable());
			cs.setString(2, vo.getKey());
			cs.setString(3, vo.getWord());
			cs.setString(4, vo.getOrder());
			cs.setString(5, vo.getDesc());
			cs.setInt(6, vo.getPage());
			cs.setInt(7, vo.getPerPage());
			cs.execute();

			ResultSet rs = cs.getResultSet();
			JSONArray array = new JSONArray();
			while (rs.next()) {
				JSONObject obj = new JSONObject();
				obj.put("order_id", rs.getString("order_id"));
				obj.put("name", rs.getString("name"));
				obj.put("address", rs.getString("address"));
				obj.put("email", rs.getString("email"));
				obj.put("tel", rs.getString("tel"));
				// obj.put("pdate", rs.getString("pdate"));
				// obj.put("payType", rs.getString("payType"));
				// obj.put("status", rs.getString("status"));
				array.add(obj);
			}
			object.put("array", array);

			cs.getMoreResults();
			rs = cs.getResultSet();
			if (rs.next()) {
				object.put("total", rs.getInt("count(*)"));
			}
		} catch (Exception e) {
			System.out.println("PurchaseDAO list : " + e.toString());
		}

		return object;
	}

}

 

- create new controller\PurchaseRESTServlet.java

package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MallDAO;
import model.ProductDAO;
import model.PurchaseDAO;
import model.SqlVO;

@WebServlet(value = { "/purchase.json" })
public class PurchaseRESTServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ProductDAO dao = new ProductDAO();
	PurchaseDAO pdao = new PurchaseDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		switch (request.getServletPath()) {
		case "/purchase.json":
			SqlVO vo = new SqlVO();
			vo.setTable("purchase");
			vo.setKey(request.getParameter("key"));
			vo.setWord(request.getParameter("word"));
			vo.setOrder(request.getParameter("order"));
			vo.setDesc(request.getParameter("desc"));
			vo.setPage(Integer.parseInt(request.getParameter("page")));
			vo.setPerPage(Integer.parseInt(request.getParameter("perPage")));
			out.println(pdao.list(vo));
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

 

- create new PurchaseServlet.java

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = { "/purchase/list" })
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		switch (request.getServletPath()) {
		case "/purchase/list":
			request.setAttribute("pageName", "/purchase/list.jsp");
			break;
		}
		RequestDispatcher dis = request.getRequestDispatcher("/main.jsp");
		dis.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

 

- create new folder purchase

- create new purchase\list.jsp

- mall\list.jsp를 복사해서 수정

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<style>
table {
	border-collapse: collapse;
	margin: 0px auto;
	margin-bottom: 10px;
}

th {
	background: rgb(242, 242, 242);
	color: black;
}

th, td {
	border: 1px solid black;
	padding: 10px;
}
.row:hover{
	cursor: pointer;
	background: rgb(242, 242, 242);
	color: black;
}
</style>
<h1>주문목록</h1>
<div id="condition">
	<select id="key">
		<option value="order_id">주문번호</option>
		<option value="name">주문자명</option>
		<option value="address">주문자주소</option>
		<option value="tel">주문자전화번호</option>
	</select> <input type="text" id="word" placeholder="검색어 입력" /> <select
		id="perPage">
		<option value=2>2개</option>
		<option value=4>4개</option>
		<option value=8>8개</option>
		<option value=12>12개</option>
	</select> 검색수 : <span id="total"></span> <select id="desc" style="float: right;">
		<option value="">오름차순</option>
		<option value="desc" selected>내림차순</option>
	</select> <select id="order" style="float: right; margin-right: 5px;">
		<option value="order_id">주문번호</option>
		<option value="name">주문자명</option>
		<option value="address">주문자주소</option>
		<option value="tel">주문자전화번호</option>
	</select>
</div>

<table id="tbl"></table>
<div id="pagination">
	<button id="prev">&lt;</button>
	<span id="page"></span>
	<button id="next">&gt;</button>
</div>
<script id="temp" type="text/x-handlebars-template">
	<tr class="title">
		<th width=100>주문번호</th>
		<th width=100>주문자명</th>
		<th width=500>주소</th>
		<th width=200>전화번호</th>
		<th width=200>구매정보</th>
	</tr>
   {{#each array}}
	<tr class="row">
		<td>{{order_id}}</td>
		<td>{{name}}</td>
		<td>{{address}}</td>
		<td>{{tel}}</td>
		<td><button>구매정보</button></td>
	</tr>
   {{/each}}
</script>

<script>
	var page = 1;
	
	$("#prev").on("click", function() {
		page--;
		getNewList();
	});
	$("#next").on("click", function() {
		page++;
		getNewList();
	})
	$("#word").on("keypress", function(e) {
		if (e.keyCode == 13) {
			page = 1;
			getNewList();
		}
	});
	$("#perPage, #order, #desc").on("change", function() {
		page = 1;
		getNewList();
	});
	
	getNewList();
	function getNewList() {
		var key = $('#key').val();
		var word = $('#word').val();
		var perPage = $('#perPage').val();
		var order = $('#order').val();
		var desc = $('#desc').val();
		$.ajax({
			type : 'get',
			url : '/purchase.json',
			dataType : 'json',
			data : {
				"key" : key,
				"word" : word,
				"page" : page,
				"perPage" : perPage,
				"order" : order,
				"desc" : desc
			},
			success : function(data) {
				var temp = Handlebars.compile($('#temp').html());
				$('#tbl').html(temp(data));
				$('#total').html(data.total);
				var lastPage = Math.ceil(data.total / perPage)
				$('#page').html("[ " + page + "/" + lastPage + " ]");
				if (page == 1) {
					$('#prev').attr('disabled', true);
					$('#prev').css('background', 'gray')
				} else {
					$('#prev').attr('disabled', false);
					$('#prev').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
				if (page == lastPage) {
					$('#next').attr('disabled', true);
					$('#next').css('background', 'gray');
				} else {
					$('#next').attr('disabled', false);
					$('#next').css({
						'background' : 'rgb(246, 246, 246)',
						'color' : 'black'
					});
				}
			}
		})
	}
</script>

 

출력물

 

checkpoint

 

- 구매정보를 누르면 구매자 상세 정보와 구매리스트를 뜨게하겠다.

- PurchaseDAO.java

	// 2. 구매상세정보 출력 메서드
	public JSONObject read(String order_id) {
		JSONObject object = new JSONObject();

		try {
			String sql = "select * from purchase where order_id=?";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ps.setString(1, order_id);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				object.put("name", rs.getString("name"));
				object.put("address", rs.getString("address"));
				object.put("email", rs.getString("email"));
				object.put("tel", rs.getString("tel"));

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				object.put("pdate", sdf.format(rs.getDate("pdate")));

				String payType = rs.getString("payType").equals("0") ? "무통장" : "카드";
				object.put("payType", payType);
				
				String status = rs.getString("status").equals("0") ? "처리중" : "처리완료";
				object.put("status", status);
			}
		} catch (Exception e) {
			System.out.println("PurchaseDAO read : " + e.toString());
		}

		return object;
	}

 

- PurchaseRESTServlet.java

@WebServlet(value = { "/purchase_read.json", "/purchase.json" })
public class PurchaseRESTServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ProductDAO dao = new ProductDAO();
	PurchaseDAO pdao = new PurchaseDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		switch (request.getServletPath()) {
		case "/purchase_read.json": // new
			out.println(pdao.read(request.getParameter("order_id")));
			break;

 

출력물

 

- 주문목록 리스트에서 구매정보 버튼을 눌렀을때 해당 order_id가 넘어가게 하고 클릭할 경우에만 정보가 보이도록 하겠다. 정보는 template를 이용해서 출력한다.

- purchase\list.jsp

<script id="temp" type="text/x-handlebars-template">
	<tr class="title">
		<th width=100>주문번호</th>
		<th width=100>주문자명</th>
		<th width=500>주소</th>
		<th width=200>전화번호</th>
		<th width=200>구매정보</th>
	</tr>
   {{#each array}}
	<tr class="row">
		<td>{{order_id}}</td>
		<td>{{name}}</td>
		<td>{{address}}</td>
		<td>{{tel}}</td>
		<td><button order_id={{order_id}}>구매정보</button></td> <!-- 확인 -->
	</tr>
   {{/each}}
</script>
<!-- 구매정보출력 new -->
<div id="info">
	<table id="tblinfo"></table>
	<script id="tempinfo" type="text/x-handlebars-template">
<tr>
	<td class="title" width=50px>이름</td>
	<td width=50>{{name}}</td>
	<td class="title" width=100>전화번호</td>
	<td width=150>{{tel}}</td>
	<td class="title" width=50>이메일</td>
	<td width=150>{{email}}</td>
	<td class="title" width=50>구매일</td>
	<td width=200>{{pdate}}</td>
</tr>
<tr>
	<td class="title">주소</td>
	<td colspan=3>{{address}}</td>
	<td class="title">결제</td>
	<td>{{payType}}</td>
	<td class="title">상태</td>
	<td>{{status}}</td>
</tr>
	</script>
	// 구매정보 버튼을 눌렀을때 구매상세 정보가 나오게
	$("#tbl").on("click",".row button",function(){
		var order_id=$(this).attr("order_id");
		$.ajax({
			type:'get',
			url:'/purchase_read.json',
			data:{"order_id":order_id},
			dataType:'json',
			success:function(data){
				var temp = Handlebars.compile($('#tempinfo').html());
				$('#tblinfo').html(temp(data));
			}
		})
	})

 

출력물

 

- 구매 상세 정보 하단에 해당 order_id로 구매한 구매 상세 목록을 출력하도록 하겠다.

- mysql

- 제품명, 제조사, 판매사의 정보가 출력될 수 있게 view_orders라는 이름의 view를 생성하겠다.

create view view_orders as
select o.*, p.prod_name, p.company, mall_name
from orders o,product p, mall m
where o.prod_id=p.prod_id and p.mall_id=m.mall_id;

select * from view_orders;

 

확인

 

- PurchaseDAO.java

- 구매상세정보에서 구매상품 정보 목록 출력 메서드

	// 3. 구매상세정보에서 구매상품 정보 목록 출력 메서드
	public JSONObject purchaseProduct(String order_id) {
		JSONObject object = new JSONObject();
		try {
			String sql = "select *,price*quantity sum from view_orders where order_id=?";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ps.setString(1, order_id);
			ResultSet rs = ps.executeQuery();
			JSONArray array = new JSONArray();
			DecimalFormat df = new DecimalFormat("#,###");
			while (rs.next()) {
				JSONObject obj = new JSONObject();
				obj.put("prod_id", rs.getString("prod_id"));
				obj.put("prod_name", rs.getString("prod_name"));
				obj.put("mall_name", rs.getString("mall_name"));
				obj.put("price", df.format(rs.getInt("price")));
				obj.put("quantity", df.format(rs.getInt("quantity")));

				obj.put("sum", df.format(rs.getInt("sum")));
				array.add(obj);
			}
			object.put("array", array);

			sql = "select sum(price*quantity) total from view_orders where order_id=?";
			ps = Database.CON.prepareStatement(sql);
			ps.setString(1, order_id);
			rs = ps.executeQuery();
			if (rs.next()) {
				object.put("total", df.format(rs.getInt("total")));
			}
		} catch (Exception e) {
			System.out.println("PurchaseDAO purchaseProduct : " + e.toString());
		}
		return object;
	}

 

- PurchaseRESTServlet.java

@WebServlet(value = { "/purchase_read.json", "/purchase.json","/purchase_product.json" })
public class PurchaseRESTServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ProductDAO dao = new ProductDAO();
	PurchaseDAO pdao = new PurchaseDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		switch (request.getServletPath()) {
		case "/purchase_product.json": // new
			out.println(pdao.purchaseProduct(request.getParameter("order_id")));
			break;

 

출력물

 

- 이제 상세정보를 list.jsp에 출력하도록 하겠다.

- purchase\list.jsp

<!-- 구매상품 상세 정보 출력 -->
<div id="purpro_info">
	<table id="purpro_tblinfo"></table>
	<script id="purpro_tempinfo" type="text/x-handlebars-template">
<tr>
	<th class="title" width=100>상품코드</th>
	<th class="title" width=350>상품명</th>
	<th class="title" width=200>제조사</th>
	<th class="title" width=100>가격</th>
	<th class="title" width=50>수량</th>
	<th class="title" width=100>합계</th>
</tr>
   {{#each array}}
<tr>
	<td>{{prod_id}}</td>
	<td>{{prod_name}}</td>
	<td>{{mall_name}}</td>
	<td>{{price}}</td>
	<td>{{quantity}}</td>
	<td>{{sum}}</td>
</tr>
   {{/each}}
<tr>
	<td class="title">총합계</td>
	<td colspan=5 style="text-align:right;">{{total}}원</td>
</tr>
	</script>
</div>
	// 구매정보 버튼을 눌렀을때 구매상세 정보가 나오게
	$("#tbl").on("click", ".row button", function() {
		var order_id = $(this).attr("order_id");
		$.ajax({
			type : 'get',
			url : '/purchase_read.json',
			data : {
				"order_id" : order_id
			},
			dataType : 'json',
			success : function(data) {
				var temp = Handlebars.compile($('#tempinfo').html());
				$('#tblinfo').html(temp(data));
			}
		})
		$.ajax({
			type : 'get',
			url : '/purchase_product.json',
			data : {
				"order_id" : order_id
			},
			dataType : 'json',
			success : function(data) {
				var temp = Handlebars.compile($('#purpro_tempinfo').html());
				$('#purpro_tblinfo').html(temp(data));
			}
		})
	})

 

출력물

 

- 관리자가 주문상세정보에서 주문상태([처리중 | 처리완료]를 선택하여 DB에 update 할 수 있도록 하겠다.

- purchase\list.jsp

<!-- 구매정보출력 -->
<div id="info" style="display: none;">
	<h1>주문상세정보</h1>
	<table id="tblinfo"></table>
	<script id="tempinfo" type="text/x-handlebars-template">
<tr>
	<td class="title" width=50px>이름</td>
	<td width=50>{{name}}</td>
	<td class="title" width=100>전화번호</td>
	<td width=150>{{tel}}</td>
	<td class="title" width=50>이메일</td>
	<td width=150>{{email}}</td>
	<td class="title" width=50>구매일</td>
	<td width=200>{{pdate}}</td>
</tr>
<tr>
	<td class="title">주소</td>
	<td colspan=3>{{address}}</td>
	<td class="title">결제</td>
	<td>{{payType}}</td>`
	<td class="title">상태</td>
	<td order_id="{{order_id}}">
		<input type="radio" name="status" id="inProgress" {{printCheck0 status}}/>처리중
		<input type="radio" name="status" id="progComplete" {{printCheck1 status}}/>처리완료
	</td>
</tr>
	</script>

 

- template에서는 c tag lib를 못쓰니 registerHelper를 사용하도록 하겠다.

	<td order_id="{{order_id}}">
		<input type="radio" name="status" id="inProgress" {{printCheck0 status}}/>처리중
		<input type="radio" name="status" id="progComplete" {{printCheck1 status}}/>처리완료
	</td>
</tr>
	</script>
	<script>
		Handlebars.registerHelper("printCheck0", function(status) {
			if (status == "0")
				return "checked";
		})
		Handlebars.registerHelper("printCheck1", function(status) {
			if (status == "1")
				return "checked";
		})
	</script>
</div>

 

<script>
	var page = 1;

	$('#tblinfo').on('click', 'tr input[name=status]', function() {
		var status;
		var order_id = $(this).parent("td").attr("order_id");
		alert(order_id);
		if ($('#inProgress').is(":checked")) {
			status = 0;
		} else if($('#progComplete').is(":checked")) {
			status = 1;
		}
		$.ajax({
			type : 'get',
			url : '/update_status',
			data : {
				"order_id" : order_id,
				"status" : status
			},
			success : function() {
				alert("처리상태가 변경됩니다.")
			}
		})

	})

 

- PurchaseDAO.java

- #tblinfo로 order_id를 가지고 오기위해서 2. 구매상세출력 메서드에서 rs 에서 order_id를 가지고 오도록 한다.

			if (rs.next()) {
				object.put("order_id", rs.getString("order_id")); // new
				object.put("name", rs.getString("name"));

 

- DB에 처리상태를 변경하기 위한 메서드를 생성한다.

	// 4. 처리상태 변경 메서드
	public void updateStatus(String status, String order_id){
		try {
			String sql = "update purchase set status=? where order_id=?";
			PreparedStatement ps = Database.CON.prepareStatement(sql);
			ps.setString(1, status);
			ps.setString(2, order_id);
			ps.execute();
		} catch (Exception e) {
			System.out.println("PurchaseDAO updateStatus : "+e.toString());
		}
	}

 

출력물

 

shop_ver0906.zip
1.12MB