오늘은 지난시간까지 진행했던 '주문내역 확인'부분부터 구현 & 확인해보고자 한다.
주문내역은 마이페이지의 네번째 메뉴에서 확인이 가능하며, 테이블뷰를 이용하여 총 3가지의 테이블을 합쳐서
사진과 같이 상품과 상품을 구매하는데 필요한 정보들을 한번에 확인 가능하도록 구성하였다.
<table class="table">
<thead>
<tr>
<th scope="col">주문번호</th>
<th scope="col">물품번호</th>
<th scope="col">물품이름</th>
<th scope="col">주문수량</th>
<th scope="col">주문자명</th>
<th scope="col">총 가격</th>
<th scope="col">주문날짜</th>
</tr>
</thead>
<tbody>
<c:set var="total" value="${0}" />
<c:forEach var="obj" items="${list}">
<tr>
<th scope="row"><input type="checkbox" value="${obj.purchaseno}" /> ${obj.purchaseno}</th>
<td>${obj.itemno}</td>
<td>${obj.itemname}</td>
<td>${obj.cnt}</td>
<td>${obj.name}</td>
<td>${obj.totalpirce}원</td>
<td>${obj.purchRegdate}</td>
<c:set var="total" value="${total + obj.totalpirce}" />
</tr>
</c:forEach>
<tr>
<th colspan="8">합계</th>
<td>${total}</td>
</tr>
</tbody>
</table>
위의 JSP 문법 중 이번에 처음배우는 생소한 문법이 하나 있는데, 바로 <c:set>
이다.
쉽게말하자면 빈 객체를 생성하는 문법이다. (int A = 0; 과 같은 느낌.)
이를 사용해서 빈 객체에 가격 데이터를 누적시켜 합계를 구함으로써 total값을 구해낼 수 있는 것이다.
DB에서 직접 처리를 해서 와도 되지만, JSP에서 tag를 추가하여 fmt태그를 사용해서 하는 방법도 있다. 먼저 아래의 taglib을 상단에 추가해주자.
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
그 다음으로는
<fmt:formatNumber value="${변경해주고자 하는 값}" pattern="#,###" />
위의 코드를 입력해주면 되는데, value
에는 모든 숫자값들을 대입해줄 수 있다.
그리하여 아래와 같이 JSP를 수정하였다.
물건당 가격과 합계가격에 콤마를 적용하여 좀더 확인이 용이하도록 해주었다.
이번에는 주문 번호들을 선택하여 삭제하는 기능들을 추가해보도록 하겠다.
@Delete( value = {
"<script>",
" DELETE FROM purchase ",
" WHERE customerid = #{map.id} AND no IN( ",
" <foreach collection='map.chk' item='tmp' separator=','> ",
" #{tmp} ",
" </foreach> ",
" ) ",
"</script>"
} )
// DELETE FROM 테이블명 WHERE customerid='a' AND no(1,2,3,4);
public int deletePurchase(@Param("map") Map<String, Object>map);
package customerController;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import config.MyBatisContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmapper.PurchaseMapper;
// 127.00.1:8080/web01/customer/home.do
@WebServlet(urlPatterns = { "/customer/deletepurchase.do" })
public class CustomerDeletePurchase extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] chk = request.getParameterValues("chk[]");
String id = (String) request.getSession().getAttribute("UID");
Map<String, Object> map = new HashMap<>();
map.put("chk",chk);
map.put("id",id);
MyBatisContext.getSqlSession().getMapper(PurchaseMapper.class).deletePurchase(map);
response.sendRedirect("mypage.do?menu=4");
}
}
<c:forEach var="obj" items="${list}">
<tr>
<th scope="row"><input type="checkbox" name="chk[]" value="${obj.purchaseno}" /> ${obj.purchaseno}</th>
<td>${obj.itemno}</td>
<td>${obj.itemname}</td>
<td>${obj.cnt}</td>
<td>${obj.name}</td>
<td><fmt:formatNumber value="${obj.totalpirce}" pattern="#,###" />원</td>
<td>${obj.purchRegdate}</td>
<c:set var="total" value="${total + obj.totalpirce}" />
</tr>
</c:forEach>
jsp의 체크박스와 세션에 등록된 유저의 ID정보를 이용하여 DB에 저장된 주문 내역을 삭제할 수 있도록 기능을 추가했다.
추가로 판매자가 유저들의 주문 수량을 그래프로 확인할 수 있는 기능도 추가해주었다.
@Select( value = {
" SELECT customerid, SUM(cnt) cnt ",
" FROM purchase GROUP BY customerid "
} )
public List<Map<String, Object>>seletMemberGroup();
package restcontroller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import config.MyBatisContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import webmapper.PurchaseMapper;
//127.0.0.1:8080/web01/api/purchase/member.json
@WebServlet(urlPatterns = { "/api/purchase/member.json" })
public class RestPurchasememberController extends HttpServlet {
private static final long serialVersionUID = 1L;
private Gson gson = new Gson();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// mapper를 이용해 회원별 주문수량 합계
// SELECT customerid, SUM(cnt) cnt FROM purchase GROUP BY customerid;
response.setContentType("application/json");
List<Map<String, Object>> list = MyBatisContext.getSqlSession()
.getMapper(PurchaseMapper.class).seletMemberGroup();
String jsonString = gson.toJson(list);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
}
}
package purchaseController;
import java.io.IOException;
import java.util.List;
import config.MyBatisContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webdto.Purchase;
import webdto.PurchaseView;
import webmapper.PurchaseMapper;
// 127.0.0.1:8080/web01/purchase/select.do
@WebServlet(urlPatterns = { "/purchase/select.do" })
public class CustomerPurchase extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String menu = request.getParameter("menu");
if (menu==null) {
response.sendRedirect("select.do?menu=1");
return; // 메소드 종료
}
request.getRequestDispatcher("/WEB-INF/purchase/purchase_select.jsp").forward(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>주문관리</title>
<!-- bootstrap -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<a href="select.do?menu=1" class="btn btn-sm btn-success">전체 주문목록</a>
<a href="select.do?menu=2" class="btn btn-sm btn-success">회원별 주문사항</a>
<a href="select.do?menu=3" class="btn btn-sm btn-success">물품별 주문사항</a>
<a href="select.do?menu=4" class="btn btn-sm btn-success">시간대별 주문목록</a>
<hr />
<c:if test="${param.menu == 1}">
<jsp:include page="../purchase_menu/menu1.jsp"></jsp:include>
</c:if>
<c:if test="${param.menu == 2}">
<jsp:include page="../purchase_menu/menu2.jsp"></jsp:include>
</c:if>
<c:if test="${param.menu == 3}">
<jsp:include page="../purchase_menu/menu3.jsp"></jsp:include>
</c:if>
<c:if test="${param.menu == 4}">
<jsp:include page="../purchase_menu/menu4.jsp"></jsp:include>
</c:if>
</div>
<!-- sweetalert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- jQuery -->
<script src="${pageContext.request.contextPath}/resources/js/jquery-3.6.4.min.js"></script>
<!-- axios -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<div>
<h3>회원별 주문수량</h3>
<div style="width: 700px; border: 1px; solid #cccccc; padding: 50px;">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script></script>
<script>
const ctx = document.getElementById("myChart").getContext("2d");
const config = {
type : 'bar',
data : {
labels : [ 'a', 'b', 'c' ],
datasets : [ {
label : '테스트',
data : [ 10, 20, 30 ]
} ]
}
}
const chart = new Chart(ctx, config);
async function changeChart() {
const url = '${pageContext.request.contextPath}/api/purchase/member.json'
const headers = {"Content-Type":"application/json"}
const { data } = await axios.get(url, {headers});
console.log(data); // [{...}, {...}]
let label = []; // 빈 배열 생성
let cnt = []; // 빈 배열 생성
for(let tmp of data) {
console.log(tmp);
label.push( tmp.CUSTOMERID ); // 아이디만 선별하여 label 변수에 추가
cnt.push(tmp.CNT); // 주문수량만 선별하여 cnt변수에 추가
}
// data값을 config변수로 변경.
config.data.labels = label;
config.data.datasets[0].label = "회원별 주문수량";
config.data.datasets[0].data = cnt; // 데이터 시트의 배열을 변수로 변경
chart.update();
}
changeChart();
</script>