본문 바로가기

카테고리 없음

IBatis - PRODLIST 동기방식, 비동기방식

https://velog.io/@daybreak/%EB%8F%99%EA%B8%B0-%EB%B9%84%EB%8F%99%EA%B8%B0-%EC%B2%98%EB%A6%AC

 

동기, 비동기 처리

데이터를 처리하는 방식인 동기, 비동기 처리에 대해 많은 글이 있지만 정확하게 와닿지가 않았다. 최대한 내가 이해한 방식대로 서술해 보려고 한다. 동기 (Synchronous)는 요청과 동시에 일어난다

velog.io


1. 동기방식

prodList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!-- 테이블 태그를 이용하여 상품(상품코드, 상품명, 분류명, 거래처명, 입고일, 구매가, 판매가, 마일리지) 목록 랜더링. -->
<table class="table table-bordered">
	<thead>
		<tr>
			<th>일련번호</th>
			<th>상품명</th>
			<th>상품분류</th>
			<th>거래처</th>
			<th>입고일</th>
			<th>구매가</th>
			<th>판매가</th>
			<th>마일리지</th>
		</tr>
	</thead>
	<tbody>
		<c:set var="prodList" value="${pagingVO.dataList }" />
		<c:choose>
			<c:when test="${not empty prodList }">
				<c:forEach items="${prodList }" var="prod">
					<tr>
						<td>${prod.rnum }</td>
						<td>
							<c:url value="/prod/prodView.do" var="prodViewURL">
								<c:param name="what" value="${prod.prodId }" />
							</c:url>
							<a href="${prodViewURL }">${prod.prodName }</a>
						</td>
						<td>${prod.lprodNm }</td>
						<td>${prod.buyer.buyerName }</td>
						<td>${prod.prodInsdate }</td>
						<td>${prod.prodCost }</td>
						<td>${prod.prodPrice }</td>
						<td>${prod.prodMileage }</td>
					</tr>
				</c:forEach>
			</c:when>
			<c:otherwise>
				<tr>
					<td colspan="7">상품이 없음.</td>
				</tr>
			</c:otherwise>
		</c:choose>
	</tbody>
	<tfoot>
		<tr>
			<td colspan="7">
				<div class="d-flex justify-content-center pagingArea">
					${pagingVO.pagingHTMLBS }
				</div>
				<div id="searchUI" class="d-flex justify-content-center">
					<select name="prodLgu">
						<option value>상품분류</option>
						<c:forEach items="${lprodList }" var="lprod">
							<option value="${lprod['lprodGu'] }">${lprod.lprodNm }</option>
						</c:forEach>
					</select>
					<select name="prodBuyer">
						<option value>상품거래처</option>
						<c:forEach items="${buyerList }" var="buyer">
							<option value="${buyer.buyerId }" class="${buyer.buyerLgu }">${buyer.buyerName }</option>
						</c:forEach>
					</select>
					<input type="text" name="prodName" placeholder="상품명"/>
					<input id="searchBtn" type="button" value="검색" class="btn btn-success"/>
					<input type="button" value="신규등록" class="btn btn-secondary linkBtn"
						data-href="${cPath }/prod/prodInsert.do"
					/>
				</div>
			</td>
		</tr>
	</tfoot>
</table>
<form id="searchForm" action="${cPath }/prod/prodList.do">
	<input type="text" name="prodLgu" placeholder="상품분류"/>
	<input type="text" name="prodBuyer" placeholder="거래처"/>
	<input type="text" name="prodName" placeholder="상품명"/>
	<input type="text" name="page" placeholder="page">
</form>
<script>
	$(".linkBtn").on("click", function(){
		let href = $(this).data("href");
		location.href = href;
	});
	$("[name=prodBuyer]").val("${pagingVO.detailCondition.prodBuyer}");
	$("[name=prodLgu]").on("change", function(event){
		let selectedLgu = $(this).val();
		let options = $(this).siblings("[name=prodBuyer]").find("option");
		$.each(options, function(idx, opt){
			if(!selectedLgu||idx==0 || $(this).hasClass(selectedLgu)){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
// 		prodBuyerTag.find("option:first");
// 		options[0]
		
	}).val("${pagingVO.detailCondition.prodLgu}").trigger("change");
	
	$("[name=prodName]").val("${pagingVO.detailCondition.prodName}");
	
	$(".pagingArea").on("click", "a", function(event){
		let page = $(this).data("page");
		searchForm.find("[name=page]").val(page);
		searchForm.submit();
	});
	
	let searchUI = $("#searchUI");
	let searchForm = $("#searchForm");
	$("#searchBtn").on("click", function(event){
		let inputs = searchUI.find(":input[name]");
		$(inputs).each(function(idx, input){
			let name = $(this).attr("name");
			let value = $(this).val();
			searchForm.find("[name="+name+"]").val(value);
		});
		searchForm.submit();
	});
</script>
package kr.or.ddit.prod.web;


@WebServlet("/prod/prodList.do")
public class ProdListServlet extends HttpServlet{
	ProdService service = new ProdServiceImpl();
	OthersDAO othersDAO = new OthersDAOImpl();
			
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String pageParam = req.getParameter("page");
//		String searchType = req.getParameter("searchType");
//		String searchWord = req.getParameter("searchWord");
//		SimpleSearchCondition searchVO = new SimpleSearchCondition(searchType, searchWord);
		
//		req.getParameter("prodLgu");
//		req.getParameter("prodBuyer");
//		req.getParameter("prodName");
		ProdVO detailCondition = new ProdVO();
		try {
			BeanUtils.populate(detailCondition, req.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
		
		int currentPage = 1;
		if(StringUtils.isNumeric(pageParam)) {
			currentPage = Integer.parseInt(pageParam);
		}
		PagingVO<ProdVO> pagingVO = new PagingVO<>(3,2);
		pagingVO.setCurrentPage(currentPage);
//		pagingVO.setSimpleCondition(searchVO);
		pagingVO.setDetailCondition(detailCondition);
		
		service.retrieveProdList(pagingVO);
		
		req.setAttribute("pagingVO", pagingVO);
		req.setAttribute("lprodList", othersDAO.selectLprodList());
		req.setAttribute("buyerList", othersDAO.selectBuyerList());
		
		String viewName = "/prod/prodList.tiles";
		new DelegatingViewResolver().viewResolve(viewName, req, resp);
	}
}

 

2. 비동기방식

 

<%@page import="kr.or.ddit.vo.ProdVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- -- 테이블 태그를 이용하여 상품(상품코드, 상품명, 분류명, 거래처명, 구매가, 판매가, 마일리지)목록 렌더링 -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- 전체, 상품분류명, 거래처명 상품명 -->
<h4>상품목록조회</h4>
<table class="table table-bordered">
  <thead>
	<tr>
		<th>일련번호</th>
		<th>상품코드</th>
		<th>상품명</th>
		<th>분류명</th>
		<th>거래처명</th>
		<th>구매가</th>
		<th>판매가</th>
		<th>마일리지</th>
		<th>입고일</th>
	</tr>
  </thead>
  <tbody id="listBody">
  </tbody>
  <tfoot id="Listfoot">
  	<tr>
  		<td colspan="7">
  			<div class="d-flex justify-content-center pagingArea">
			${pagingVO.pagingHTMLBS }
			</div>
				<div id="searchUI" class="d-flex justify-content-center searchArea">
					<select name="prodLgu">
						<option value>상품분류</option>
					<c:forEach items="${lprodList }" var="lprod">
						<option value="${lprod['lprodGu'] }">${lprod.lprodNm }</option>
					</c:forEach>
					</select>	
					
					 <select name="prodBuyer">
						<option value>상품거래처</option>
					 <c:forEach items="${buyerList }" var="buyer">
						<option value="${buyer.buyerId }" class="${buyer.buyerLgu }">${buyer.buyerName }</option>
					 </c:forEach>
					</select>
<!-- 					<input type="text" name="prodLgu" placeholder="상품분류" /> -->
<!-- 					 <input type="text" name="prodBuyer" placeholder="거래처" />  -->
					 <input type="text" name="prodName" placeholder="상품명" />
<!-- 					이렇게하면 3개의검색을 동시에 할수있음 -->
					<input id="searchBtn" type="button" value="검색" class="btn btn-success" />
				</div>
				<div>
					<button id="insertProd" onclick="location.href='${cPath}/prod/prodInsert.do'">상품등록</button>
				</div>
			</td>
			
  	</tr>
  </tfoot>
</table>

<form id="searchForm" action="${cPath }/prod/prodList.do">
   <input type="text" name="page" placeholder="page"/>
   <input type="text" name="prodLgu" placeholder="상품분류"/>         
   <input type="text" name="prodBuyer" placeholder="거래처"/>         
   <input type="text" name="prodName" placeholder="상품명"/> 
</form>


<script>
    $("[name='prodBuyer']").val("${pagingVO.detailCondition.prodBuyer}");
	$("[name='prodLgu']").on("change", function(event){
		let selectedLgu = $(this).val();
		let options = $(this).siblings("[name=prodBuyer]").find("option");
		$.each(options, function(idx, opt){
			if(idx==0 || $(this).hasClass(selectedLgu)){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
// 		prodBuyerTag.find("option:first");

		
	}).val("${pagingVO.detailCondition.prodLgu}").trigger("change");
	
	$("[name='prodName']").val("${pagingVO.detailCondition.prodName}");
	
	$(".pagingArea").on("click", "a", function(event){//event target this -> a이다.
		let page = $(this).data("page");
		//a태그 대신해서 요청을 발생시키는 구조가 필요 
// 		location.href = "?page="+page; /form형태로 바꿔서 ..? 
		searchForm.find("[name=page]").val(page);
		searchForm.submit();
		
	});
	
	let listBody= $("#listBody"); // 	tbody태그불러냄
	let listFott =$("#listFoot");
	let pagingArea = $(".pagingArea");//검색태그 select
	let searchUI = $("#searchUI");
	let searchForm = $("#searchForm");
	<c:url value ="/prod/prodView.do" var="viewURL">
	  	<c:param name="what" value="prodId"></c:param>
	</c:url>
	const VIEWURL = "${viewURL}"
	let makeSingleTr = function(index, prod){
		let aTag= $("<a>").attr({
				"href":VIEWURL.replace("prodId", prod.prodId)
				}).text(prod.prodName);
		return $("<tr>").append(
				$("<td>").html(prod.rnum)
				, $("<td>").html(prod.prodId)
				, $("<td>").html(aTag)
				, $("<td>").html(prod.lprodNm)		
				, $("<td>").html(prod.buyer.buyerName)
				, $("<td>").html(prod.prodCost)
				, $("<td>").html(prod.prodPrice)
				, $("<td>").html(prod.prodMileage)
				, $("<td>").html(prod.prodInsdate)
				
		);
	}
	
	
	$("#searchForm").on("submit", function(event){
		event.preventDefault();
		let url = this.action;
		let method = this.method;
		let data = $(this).serialize();
		$.ajax({
			url : url,
			data : data,
			method : method,
			dataType : "json" // text, html, json, xml, script -> main type : text, 파일 업로드 처리를 비동기로? (FormData)
			,
			success : function(resp, status, jqXHR) {
				let pagingVO = resp.pagingVO;
				let prodList = pagingVO.dataList;
				console.log(prodList);
				let trTags = [];
				if(prodList && prodList.length > 0){
					$(prodList).each(function(index, prod){
						trTags.push(makeSingleTr(index, prod));
					});
				}else{
					let trTag =$("<tr>").html(
									$("<td>").attr("colspan","5")
											 .html("회원정보가 없습니다.")
						
						);
					trTags.push(trTag);
				}
				listBody.html(trTags);
				pagingArea.html(pagingVO.pagingHTMLBS);
			},
			error : function(jqXHR, status, error) {
				console.log(jqXHR);
				console.log(status);
				console.log(error);
			}
		});
		return false;
	}).submit();
	

	$("#searchBtn").on("click", function(event){
		searchForm.get(0).reset();
		let inputs = searchUI.find(":input[name]");
		$(inputs).each(function(idx, input){
			let name = $(this).attr("name");//search type, searchword가져옴
			let value = $(this).val();
			searchForm.find("[name="+name+"]").val(value);//value 넣음
		});
		searchForm.submit();
	});
	

</script>

ProdListServlet

package kr.or.ddit.prod.web;

@WebServlet("/prod/prodList.do")
public class ProdListServlet extends HttpServlet{
	
	ProdServiceImpl service =new ProdServiceImpl();
	OthersDAO othersDAO = new OtherDaoImpl();

	private void processHTML(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		DelegatingViewResolver resolver = new DelegatingViewResolver();
		String viewName = "/prod/prodList.tiles";
		List<BuyerVO> buyerList = othersDAO.selectBuyerList();
		List<Map<String, Object>> lprodList = othersDAO.selectLprodList();
		
		req.setAttribute("lprodList", lprodList);
		req.setAttribute("buyerList", buyerList);
		resolver.viewResolve(viewName, req, resp);
		
	}
	
	private void processJsonData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String pageParam = req.getParameter("page");
		
		ProdVO detailCondition = new ProdVO();
		try {
			BeanUtils.populate(detailCondition, req.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			
			throw new RuntimeException(e);
		}
		
		int currentPage = 1;
		if(StringUtils.isNumeric(pageParam)) {
			currentPage = Integer.parseInt(pageParam);
		}
		
		PagingVO<ProdVO> pagingVO = new PagingVO<>(3,2);//tatal, current screnn block, 이거 안써줫 by zero에러가 터짐 
		pagingVO.setCurrentPage(currentPage);
//		pagingVO.setSimpleCondition(searchVO);
		pagingVO.setDetailCondition(detailCondition);
		
		service.retrieveProdList(pagingVO);

		req.setAttribute("pagingVO", pagingVO);

		
		DelegatingViewResolver resolver = new DelegatingViewResolver();
		String viewName = "forward:/jsonView.do";
		resolver.viewResolve(viewName, req, resp);
		

	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String accept = req.getHeader("accept");
		
		if(StringUtils.containsIgnoreCase(accept, "json")) {//containsIgnoreCase - 대소문자 구별안하는거 
			processJsonData(req, resp);
		}else {
			processHTML(req, resp);
		}

	}
}