TIL(Today I Learned)
2023.07.26. TIL
jjonse
2023. 7. 26. 18:56
(1) mybatis
- #{} -> 알아서 따옴표 붙여줌
- ${} -> 따옴포 붙이고 싶을 때 사용
검색 기능을 적용한 sql query
<select id="selectBoardList" resultType="BoardVo">
SELECT *
FROM BOARD
WHERE STATUS = 'O'
<if test="searchType != null and searchType != '' and searchValue != null and searchValue != ''">
AND ${searchType} LIKE '%${searchValue}%'
</if>
</select>
- 카운트 세는 QUERY
<select id="getBoardCnt" resultType="int">
SELECT COUNT(NO)
FROM BOARD
WHERE STATUS = 'O'
<if test="searchType != null and searchType != '' and searchValue != null and searchValue != ''">
AND ${searchType} LIKE '%${searchValue}%'
</if>
</select>
- CONTROLLER
//게시글 목록 -> board/list
@GetMapping("list")
public String list(@RequestParam(defaultValue = "1") int p, Model model, @RequestParam Map<String, String> paramMap) {
//검색 결과에 따른 페이징 처리 수정
int listCount = service.getBoardCnt(paramMap);
int currentPage = p;
int pageLimit = KhConstPool.PAGE_LIMIT;
int boardLimit = KhConstPool.BOARD_LIMIT;
PageVo pv = new PageVo(listCount, currentPage, pageLimit, boardLimit);
List<BoardVo> voList = service.list(pv, paramMap);
model.addAttribute("voList", voList);
model.addAttribute("paramMap", paramMap);
return "board/list";
}
JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시물 목록</title>
</head>
<body>
<div id="wrap">
<%@ include file="/WEB-INF/views/common/header.jsp" %>
<main>
<h1>게시물 목록</h1>
<form action="${root}/board/list" method="get">
<select name="searchType">
<option value="title">제목</option>
<option value="content" >내용</option>
</select>
<input type="search" name="searchValue" placeholder="검색" value="">
<input type="submit" value="검색">
</form>
<hr>
<c:forEach items="${voList}" var="vo">
<h3>${vo.no} / ${vo.title} / ${vo.content}</h3>
</c:forEach>
</main>
</div>
<script type="text/javascript">
const searchValueTag = document.querySelector("input[name=searchValue]");
//이 부분은 jasper가 관여해서 저장소 중에서 저장소를 뒤져서 paramMap 뒤져서 searchValue를 꺼내옴
//문서 자체는 서버 측에서 실행되고 있다.(jsp) jsp는 servlet인데, 요청 들어올 때 servlet으로 바꿔서 어떤 작업을 수행해줌.
//스크립트 태그가 있던, 알람 때우는 코드가 있던 jasper에 의해서 tomcat내부에 있는 서버 파일일 뿐이다.
//뭐가 있든 상관없이 단순히 문자열에 불과할 뿐인 것이다.
//서버측에서 paramMap.searchValue를 해석해서 보내주고,
//클라이언트 측에서는 해석된 문자열이 담긴 것을 그대로 받는다.
searchValueTag.value = '${paramMap.searchValue}';
const searchTypeTagArr = document.querySelectorAll("select[name=searchType] > option");
const x = '${paramMap.searchType}';
if(x == 'title') {
searchTypeTagArr[0].selected = true;
} else if(x == 'content') {
searchTypeTagArr[1].selected = true;
}
</script>
</body>
</html>