고래씌
[SpringBoot] 1-2. 필터링하여 메뉴 목록 조회 - GET 방식 본문
1. 필터링하여 메뉴 목록 조회
▶ index.jsp
=> 추가
- index.jsp 전체코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="jakarta.tags.core"%>
<!-- contextPath 보관 -->
<c:set var="contextPath" value="${pageContext.request.contextPath }" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- bootstrap js: jquery load 이후에 작성할것.-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<!-- bootstrap css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link rel="stylesheet" href="${contextPath }/resources/css/style.css" />
</head>
<body>
<div id="container">
<header>
<div id="header-container">
<h2>Menu</h2>
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
<img src="${pageContext.request.contextPath }/resources/images/logo-spring.png" alt="스프링로고" width="50px" />
</a>
<!-- 반응형으로 width 줄어들경우, collapse버튼관련 -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
</div>
</nav>
</header>
<section id='content'>
<div id='menu-container' class='text-center'>
<div class='menu-test'>
<h4>전체메뉴조회기능(GET)</h4>
<input type='button' class='btn btn-block btn-outline-success btn-send'
id='btn-menus' value="전송">
</div>
<div id="menus-result" class='result'></div>
<script>
function displayResultTable(id, data){
const container = $("#" +id);
let html = "<table class='table'>";
html += "<tr><th>번호</th><th>음식점</th><th>메뉴</th>" +
"<th>가격</th><th>타입</th><th>맛</th></tr>";
if(data.length > 0) { // 데이터가 있다면
$(data).each((index, menu) => { // menu라는 변수 사용. js객체로 받은 menu객체일것
const {id, restaurant, name, price, type, taste} = menu;
html += `<tr>
<td>\${id}</td>
<td>\${restaurant}</td>
<td>\${name}</td>
<td>\${price}</td>
<td>\${type}</td>
<td>\${taste}</td>
</tr>`;
})
}else{
html += "<tr><td colspan='6'>검색결과가 없습니다.</td></tr>";
}
html += "</table>"; // 열어놨던 table 태그 닫음
container.html(html);
}
$("#btn-menus").click(() => {
$.ajax({
url : '${contextPath}/menus',
method : "get",
success : (data) => {
displayResultTable("menus-result", data);
},
error : (error, req, res) => {
console.log(error, req, res)
}
})
})
</script>
<!-- 2. GET /menus/kr, /menus/jsp, /menus/ch -->
<div class="menu-test">
<h4>추천메뉴(GET)</h4>
<form id="menuRecommendationFrm">
<div class="form-check form-check-inline">
<input type="radio" class="form-check-input" name="type" id="get-no-type" value="all" checked>
<label for="get-no-type" class="form-check-label">모두</label>
<input type="radio" class="form-check-input" name="type" id="get-kr" value="kr">
<label for="get-kr" class="form-check-label">한식</label>
<input type="radio" class="form-check-input" name="type" id="get-ch" value="ch">
<label for="get-ch" class="form-check-label">중식</label>
<input type="radio" class="form-check-input" name="type" id="get-jp" value="jp">
<label for="get-jp" class="form-check-label">일식</label>
</div>
<br />
<div class="form-check form-check-inline">
<input type="radio" class="form-check-input" name="taste" id="get-no-taste" value="all" checked>
<label for="get-no-taste" class="form-check-label">모두</label>
<input type="radio" class="form-check-input" name="taste" id="get-hot" value="hot">
<label for="get-hot" class="form-check-label">매운맛</label>
<input type="radio" class="form-check-input" name="taste" id="get-mild" value="mild">
<label for="get-mild" class="form-check-label">순한맛</label>
</div>
<br />
<input type="submit" class="btn btn-block btn-outline-success btn-send" value="전송" >
</form>
</div>
<div class="result" id="menuRecommendation-result"></div>
<script>
$("#menuRecommendationFrm").submit(function(e){
e.preventDefault();
const $frm = $(e.target);
const type = $frm.find("[name=type]:checked").val(); // 체크된 요소들 // jp. ch..
const taste = $frm.find("[name=taste]:checked").val();
// EL 표현식으로 해석이 돼서 앞에 \ 를 추가해줘야함
$.ajax({
url : `${contextPath}/menus/\${type}/\${taste}`,
success : function(data){
displayResultTable("menuRecommendation-result", data);
}
})
})
</script>
</div>
</section>
</div>
</body>
</html>
▶ MenuController.java
// 타입 선택에 따른 메뉴 조회
@GetMapping("/menus/{type}/{taste}")
public List<Menu> menus(@PathVariable String type,
@PathVariable String taste) {
Map<String, Object> param = new HashMap();
param.put("type", type);
param.put("taste", taste);
List<Menu> list = menuService.selectMenusByTypeAndTaste(param);
return list;
}
▶ MenuService.java
// 타입에 따른 메뉴 목록 조회
List<Menu> selectMenusByTypeAndTaste(Map<String, Object> param);
▶ MenuServiceImpl.java
// 타입 선택에 따른 메뉴 목록 조회
@Override
public List<Menu> selectMenusByTypeAndTaste(Map<String, Object> param) {
return menuDao.selectMenusByTypeAndTaste(param);
}
▶ MenuDao.java
// 타입에 따른 메뉴목록 조회
public List<Menu> selectMenusByTypeAndTaste(Map<String, Object> param) {
return session.selectList("menuMapper.selectMenusByTypeAndTaste", param);
}
▶ menuMapper.xml
=> where 태그가 실제 WHERE 조건절을 만들어줌
<!-- 타입에 따른 메뉴 목록 조회 -->
<!-- where 태그가 실제 WHERE 조건절을 만들어줌 -->
<select id="selectMenusByTypeAndTaste" parameterType="hashmap" resultMap="menuMap">
SELECT *
FROM MENU
<where>
<if test="type != 'all'">
TYPE= #{type}
</if>
<if test="taste != 'all'">
AND TASTE = #{taste}
</if>
</where>
ORDER BY ID DESC
</select>
▶ 결과
=> 필터링되어 결과가 보여지는 것을 확인
'Server > SpringBoot' 카테고리의 다른 글
[SpringBoot] 1-5. 메뉴 삭제 - DELETE (0) | 2024.02.02 |
---|---|
[SpringBoot] 1-4. 메뉴 검색, 메뉴 수정 - PUT 방식 (0) | 2024.02.02 |
[SpringBoot] 1-3. 메뉴 추가(insert) - POST 방식 (0) | 2024.02.02 |
[SpringBoot] 1-1. 전체 메뉴 목록 조회 (0) | 2024.02.02 |
[SpringBoot] 0. 스프링부트 환경설정(sts4) (0) | 2024.02.02 |