오봉이와 함께하는 개발 블로그
Spring - 간단한 예제 + 중복 체크 + 검색 본문
728x90
상품 검색 예제
추가
- https://5bong2-develop.tistory.com/156
- https://5bong2-develop.tistory.com/157
- https://5bong2-develop.tistory.com/158
- 이전 내용들
방법 1. Ajax / @ResponseBody 사용
ProductService
@Override
public ArrayList<ProductVo> productSearch(HashMap<String, Object> map) {
return dao.productSearch(map);
}
IProductService
ArrayList<ProductVo> productSearch(HashMap<String, Object> map); // 상품 검색
IProductDAO
ArrayList<ProductVo> productSearch(HashMap<String, Object> map); // 상품 검색
ProductController
// 상품 검색 폼 이동
@RequestMapping("/product/productSearchForm")
public String productSearchForm() {
return "product/productSearchForm";
}
// 상품 검색 폼 검색
@ResponseBody
@RequestMapping("/product/productSearch")
// public ArrayList<ProductVO> productSearch(@RequestParam("type") String type,
// @RequestParam("keyword") String keyword) {
public ArrayList<ProductVo> productSearch(@RequestParam HashMap<String, Object> param,
Model model){
System.out.println("a");
ArrayList<ProductVo> prdList = service.productSearch(param);
model.addAttribute("prdList", prdList);
// prdList로 제대로 반화되었는지 확인하기 위한 코드
for(int i =0; i < prdList.size(); i++) {
ProductVo prd = (ProductVo) prdList.get(i);
System.out.println(prd.getPrdNo());
}
return prdList;
}
ProductMapper
<!-- 상품 검색 -->
<select id="productSearch" resultMap="prdResult" parameterType="hashmap">
SELECT * FROM product WHERE
<choose>
<when test="type != null and type.equals('prdName')">
prdName LIKE CONCAT('%', #{keyword}, '%')
</when>
<when test="type != null and type.equals('prdCompany')">
prdCompany LIKE CONCAT('%', #{keyword}, '%')
</when>
</choose>
</select>
productSearchForm.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>상품 검색</title>
<script src="<c:url value='/js/jquery-3.6.0.min.js/' />"></script>
<script src="<c:url value='/js/productSearchForm.js/' />"></script>
</head>
<body>
<h3>상품 검색</h3>
<form id="prdSearchFrm">
<select id="type" name="type">
<option value="">검색 조건 선택</option>
<option value="prdName">상품명</option>
<option value="prdCompany">제조회사</option>
</select>
<input type="text" name="keyword">
<input type="submit" value="검색">
</form>
<div id="searchResultBox"></div>
</body>
</html>
productSearchForm.js
/**
* productSearch.js
상품 검색
*/
$(document).ready(function(){
$('#prdSearchFrm').on('submit', function(){
event.preventDefault();
var formData = $(this).serialize();
// serialize() : 폼에 입력한 값을 쿼리 스트링 방식의 데이터로 변환
//type=prdName&keyword=노트북
$.ajax({
type:"post",
url:"productSearch",
data:formData,
success:function(result){ // 컨트롤러에서 반환한 prdList를 result가 받음
//alert(result.length);
// 반환된 결과(ArrayList<ProductVO>)를 searchResultBox에 테이블 형태로 출력
$('#searchResultBox').empty();
$('#searchResultBox').append('<table id="resultTable" border="1" width="600">' +
'<tr><th>상품번호</th><th>상품명</th><th>가격</th>' +
'<th>제조사</th><th>재고</th><th>사진</th></tr>');
if(result == ""){
$('#resultTable').append('<tr align="center"><td colspan="6">찾는 상품이 없습니다 </td></tr>');
}else{
for(var i=0; i <result.length; i++){
$('#resultTable').append('<tr><td>' + result[i].prdNo + '</td><td>' +
result[i].prdName + '</td><td>' +
result[i].prdPrice+ '</td><td>' +
result[i].prdCompany + '</td><td>' +
result[i].prdStock + '</td><td>' +
'<img src="/mybatis/images/' + result[i].prdNo + '.jpg" width="30" height="20"></td></tr>');
}
}
$('#searchResultBox').append('</table>');
},
error:function(data, textStatus){
alert("전송 실패");
}
});
});
});
방법 2. @ResponseBody 없이 뷰 페이지 리턴 후, Ajax에서 현재 페이지에 결과 뷰 페이지를 삽입
ProductService
@Override
public ArrayList<ProductVo> productSearch(HashMap<String, Object> map) {
return dao.productSearch(map);
}
IProductService
ArrayList<ProductVo> productSearch(HashMap<String, Object> map); // 상품 검색
IProductDAO
ArrayList<ProductVo> productSearch(HashMap<String, Object> map); // 상품 검색
ProductController
// 상품 검색 폼2 이동
@RequestMapping("/product/productSearchForm2")
public String productSearchForm2() {
return "product/productSearchForm2";
}
// 상품 검색 폼2 검색
@RequestMapping("/product/productSearch2")
// public ArrayList<ProductVO> productSearch(@RequestParam("type") String type,
// @RequestParam("keyword") String keyword) {
public String productSearch2(@RequestParam HashMap<String, Object> param,
Model model){
ArrayList<ProductVo> prdList = service.productSearch(param);
model.addAttribute("prdList", prdList);
return "product/productSearchResultView";
}
ProductMapper
<!-- 상품 검색 -->
<select id="productSearch" resultMap="prdResult" parameterType="hashmap">
SELECT * FROM product WHERE
<choose>
<when test="type != null and type.equals('prdName')">
prdName LIKE CONCAT('%', #{keyword}, '%')
</when>
<when test="type != null and type.equals('prdCompany')">
prdCompany LIKE CONCAT('%', #{keyword}, '%')
</when>
</choose>
</select>
productSearchForm2.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>상품 검색2</title>
<script src="<c:url value='/js/jquery-3.6.0.min.js/' />"></script>
<script src="<c:url value='/js/productSearchForm2.js/' />"></script>
</head>
<body>
<h3>상품 검색</h3>
<form id="prdSearchFrm2">
<select id="type" name="type">
<option value="">검색 조건 선택</option>
<option value="prdName">상품명</option>
<option value="prdCompany">제조회사</option>
</select>
<input type="text" name="keyword">
<input type="submit" value="검색">
</form>
<div id="searchResultBox"></div>
</body>
</html>
productSearchForm2.js
/**
* productSearch.js
상품 검색
*/
$(document).ready(function(){
$('#prdSearchFrm2').on('submit', function(){
event.preventDefault();
var formData = $(this).serialize();
// serialize() : 폼에 입력한 값을 쿼리 스트링 방식의 데이터로 변환
//type=prdName&keyword=노트북
$.ajax({
type:"post",
url:"productSearch2",
data:formData,
success:function(result){
$('#searchResultBox').html(result);
},
error:function(data, textStatus){
alert("전송 실패");
}
});
});
});
productSearchResultView.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>상품 검색 결과</title>
</head>
<body>
<h3>상품 검색 결과2</h3>
<table border="1" width="600">
<tr><th>상품번호</th><th>상품명</th><th>가격</th><th>제조사</th><th>재고</th><th>사진</th></tr>
<c:choose>
<c:when test="${empty prdList}">
<tr align="center"><td colspan="6">찾는 상품이 없습니다.</td></tr>
</c:when>
<c:otherwise>
<c:forEach items="${prdList }" var="prd">
<tr><td><a href="<c:url value='/product/detailViewProduct/${prd.prdNo}'/>">${prd.prdNo }</a></td>
<td>${prd.prdName }</td>
<td>${prd.prdPrice }</td>
<td>${prd.prdCompany }</td>
<td>${prd.prdStock }</td>
<td><img src="c:url value='/images/${prd.prdNo}.jpg' />" width="30" height="20"/></td></tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
<br>
<a href="<c:url value='/' />">메인 화면으로 이동</a>
</body>
</html>
728x90
'BE > Spring' 카테고리의 다른 글
Spring - SpringBoot 기초 (0) | 2022.01.12 |
---|---|
Spring - RESTController (0) | 2022.01.12 |
Spring - 간단한 예제 + 중복 체크 (0) | 2022.01.11 |
Spring - REST & Ajax (0) | 2022.01.11 |
Spring - 간단한 예제 (0) | 2022.01.11 |
Comments