2024-02-07(43일차) - Spring

민짱·2024년 2월 7일

📅2024. 02.07 43일차


🎬2024_01_Spring_AM

검색 기능 구현

  • 파라미터 값 받아서 구현
@RequestMapping("/usr/article/list")
	public String showList(HttpServletRequest req, Model model, @RequestParam(defaultValue = "1") int boardId,
			@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "title,body") String searchKeywordTypeCode,
			@RequestParam(defaultValue = "") String searchKeyword) {
            
            int articlesCount = articleService.getArticlesCount(boardId, searchKeywordTypeCode, searchKeyword);
            }
  • articleController에 파라미터 받을 수 있게 searchKeywordTypeCode, searchKeyword 추가
@Select("""
			<script>
			SELECT COUNT(*) AS cnt
			FROM article AS A
			WHERE 1
			<if test="boardId != 0">
				AND boardId = #{boardId}
			</if>
			<if test="searchKeyword != ''">
				<choose>
					<when test="searchKeywordTypeCode == 'title'">
						AND A.title LIKE CONCAT('%',#{searchKeyword},'%')
					</when>
					<when test="searchKeywordTypeCode == 'body'">
						AND A.body LIKE CONCAT('%',#{searchKeyword},'%')
					</when>
					<otherwise>
						AND A.title LIKE CONCAT('%',#{searchKeyword},'%')
						OR A.body LIKE CONCAT('%',#{searchKeyword},'%')
					</otherwise>
				</choose>
			</if>
			ORDER BY id DESC
			</script>
			""")
	public int getArticlesCount(int boardId, String searchKeywordTypeCode, String searchKeyword);
  • ArticleRepository에서 쿼리문 수정
  • URL로 검색시 해당 게시글 총 갯수 나옴

보완

  • (갯수말고 1 row 표시)

  • ArticleController의 articleService.getForPrintArticles에 searchKeywordTypeCode,searchKeyword 추가해서 넘겨주기

List<Article> articles = articleService.getForPrintArticles(boardId, itemsInAPage, page, searchKeywordTypeCode,
				searchKeyword);
  • 쿼리문 수정

	@Select("""
			<script>
			SELECT A.*, M.nickname AS extra__writer
			FROM article AS A
			INNER JOIN `member` AS M
			ON A.memberId = M.id
			WHERE 1
			<if test="boardId != 0">
				AND A.boardId = #{boardId}
			</if>
			<if test="searchKeyword != ''">
				<choose>
					<when test="searchKeywordTypeCode == 'title'">
						AND A.title LIKE CONCAT('%',#{searchKeyword},'%')
					</when>
					<when test="searchKeywordTypeCode == 'body'">
						AND A.body LIKE CONCAT('%',#{searchKeyword},'%')
					</when>
					<otherwise>
						AND A.title LIKE CONCAT('%',#{searchKeyword},'%')
						OR A.body LIKE CONCAT('%',#{searchKeyword},'%')
					</otherwise>
				</choose>
			</if>
			ORDER BY A.id DESC
			<if test="limitFrom >= 0 ">
				LIMIT #{limitFrom}, #{limitTake}
			</if>
			</script>
			""")

문제점 발생

  • 페이지를 넘어가면 URL이 풀려버림 어떻게 해야함???

문제점 해결

  • 지금 문제가 생기는 이유는 pagination에서 searchKeywordTypeCodesearchKeyword parameter를 받지 못해서이다. 그럼 넣어주면 끝??
<div class="pagination flex justify-center mt-3">
		<c:set var="paginationLen" value="3" />
		<c:set var="startPage" value="${page -  paginationLen  >= 1 ? page - paginationLen : 1}" />
		<c:set var="endPage" value="${page +  paginationLen  <= pagesCount ? page + paginationLen : pagesCount}" />

		<c:if test="${startPage > 1 }">
			<a class="btn btn-sm" href="?page=1&boardId=${boardId }&searchKeywordTypeCode=${searchKeywordTypeCode}&searchKeyword=${searchKeyword}">1</a>
			<button class="btn btn-sm btn-disabled">...</button>
		</c:if>

		<c:forEach begin="${startPage }" end="${endPage }" var="i">
			<a class="btn btn-sm ${param.page == i ? 'btn-active' : '' }" href="?page=${i }&boardId=${boardId}&searchKeywordTypeCode=${searchKeywordTypeCode}&searchKeyword=${searchKeyword}">${i }</a>
		</c:forEach>

		<c:if test="${endPage < pagesCount }">
			<button class="btn btn-sm btn-disabled">...</button>
			<a class="btn btn-sm" href="?page=${pagesCount }&boardId=${boardId }&searchKeywordTypeCode=${searchKeywordTypeCode}&searchKeyword=${searchKeyword}">${pagesCount }</a>
		</c:if>

	</div>
  • 문제 해결 완료

슨생님_var

  • baseUri에 벨류 넣어서 parameter 값 받기
<div class="pagination flex justify-center mt-3">
		<c:set var="paginationLen" value="3" />
		<c:set var="startPage" value="${page -  paginationLen  >= 1 ? page - paginationLen : 1}" />
		<c:set var="endPage" value="${page +  paginationLen  <= pagesCount ? page + paginationLen : pagesCount}" />

		<c:set var="baseUri" value="?boardId=${boardId }" />
		<c:set var="baseUri" value="${baseUri }&searchKeywordTypeCode=${searchKeywordTypeCode}" />
		<c:set var="baseUri" value="${baseUri }&searchKeyword=${searchKeyword}" />

		<c:if test="${startPage > 1 }">
			<a class="btn btn-sm" href="${baseUri }&page=1">1</a>
			<button class="btn btn-sm btn-disabled">...</button>
		</c:if>

		<c:forEach begin="${startPage }" end="${endPage }" var="i">
			<a class="btn btn-sm ${param.page == i ? 'btn-active' : '' }" href="${baseUri }&page=${i }">${i }</a>
		</c:forEach>

		<c:if test="${endPage < pagesCount }">
			<button class="btn btn-sm btn-disabled">...</button>
			<a class="btn btn-sm" href="${baseUri }&page=${pagesCount }">${pagesCount }</a>
		</c:if>

	</div>

검색기능 구현

  • 검색 폼 구현
<form action="">
	<input type="hidden" name="boardId" value="${param.boardId }" />
	<select data-value="${param.searchKeywordTypeCode }" class="select select-bordered select-sm w-full max-w-xs"name="searchKeywordTypeCode">
			<option value="title">title</option>
			<option value="body">body</option>
			<option value="title,body">title+body</option>
	</select>
	<input value="${param.searchKeyword }" name="searchKeyword" type="text" placeholder="What is your searchKeyword?"class="input-sm input input-bordered w-48 max-w-xs" />
	<button class="btn btn-ghost btn-sm" type="submit">검색</button>
</form>

개념정리

jq each

  • jQuery를 사용해 배열을 관리하고자 할 때 each() 메서드를 사용할 수 있다.

  • each() 메서드는 매개 변수로 받은 것을 사용해 for in 반복문과 같이 배열이나 객체의 요소를 검사할 수 있는 메서드이다.

  • each() 메서드 두 가지 타입

// jQuery 유틸리티 메서드
$.each(object, function(index, item){

});

// jQuery 일반 메서드
$(selector).each(function(index, item){

})
  • $.each() 메서드는 object 와 배열 모두에서 사용할 수 있는 일반적인 반복 함수이다.
  • 배열과 length 속성을 갖는 배열과 유사 배열 객체들을 index를 기준으로 반복할 수 있다.
  • jQuery의 each() 메서드는 배열, Map, 그리고 객체를 매개변수로 받아, 마치 반복문처럼 그 요소들을 검사하고 반복할수 있도록 하는 함수이다.

jq attr

  • .attr()은 요소(element)의 속성(attribute)의 값을 가져오거나 속성을 추가한다.

jq val

  • .val()은 양식(form)의 값을 가져오거나 값을 설정하는 메소드이다.

0개의 댓글