66. 검색창 수정하기

hanahana·2022년 9월 15일
0

Spring 학원수강

목록 보기
21/45
post-thumbnail

해당 검색어 없을 때 데이터 없음 페이지 띄우기

jsp수정하기

<!-- 게시물 리스트 출력시 리스트 반환값이 있을때/없을때 if문 -->
		<!-- 반환값 있을때 -->
		<c:if test="${!empty bList }">
			<c:forEach items="${bList }" var="board" varStatus="i">
				<tr>
					<td>${i.count }</td>

					<c:if test="${searchValue eq null }">
						<td><a href="/board/detail.kh?boardNo=${board.boardNo }">${board.boardTitle }</td>
					</c:if>

					<c:if test="${searchValue ne null }">
						<td><a
							href="/board/detail.kh?boardNo=${board.boardNo }&searchCondition=${searchCondition }&searchValue=${searchValue}">${board.boardTitle }</td>
					</c:if>

					<td>${board.boardWirter }</td>
					<td>${board.bCreateDate }</td>
					<td>${board.boardCount }</td>
					<c:if test="${!empty board.boardFile }">
						<td>O</td>
					</c:if>
					<c:if test="${empty board.boardFile }">
						<td>X</td>
					</c:if>
				</tr>
			</c:forEach>
		</c:if>

		<!-- 반환값 없을때 -->
		<c:if test="${empty bList }">
			<tr>
				<td colspan="6" rowspan = "2" align="center">데이터가 존재하지 않습니다</td>
			</tr>
		</c:if>

		<!-- 리스트 if문 종료 -->
  • 해당 검색어가 없었을떄 Controller에서는 bList의 반환값을 null로 할것이기에 c:if문에서 반환값이 비어있을때와 비어있지 않을때를 구분하였다.
    • 반환값이 없을때는 데이터가 존재하지 않습니다, 라는 글자만 띄우게 된다.
    • c:if문을 쓰기 위해서는 web-inf\lib 경로에 tablibs 자바파일이 4개 필요하다.
    • jsp상단에 <%@ taglib prefix="c" uri="[http://java.sun.com/jsp/jstl/core](http://java.sun.com/jsp/jstl/core)"%>를 입력해주어야 한다.
    • 잊어버릴까봐 한번 더 체크해봤음

Controller수정하기

/**
	 * 게시물 검색
	 * @param mv
	 * @param searchCondition
	 * @param searchValue
	 * @return
	 */
	@RequestMapping (value="/board/search.kh", method = RequestMethod.GET)
	public ModelAndView boardSearchList(ModelAndView mv,
			@RequestParam("searchCondition") String searchCondition,
			@RequestParam(value="page", required=false) Integer page, //페이징을 위한 매개변수
			@RequestParam("searchValue") String searchValue,
			HttpSession session) {
		try {
			session.removeAttribute("pageNow");
		
			
			/////////////////////////////////페이징시작//////////////////////////////
			int currentPage = (page != null) ? page: 1;
			int boardLimit = 10; //한 화면에 출력할 게시물 수
			/////페이징용////
		
		List<Board> bList = bService.printAllByValue(searchCondition, searchValue, currentPage, boardLimit);
		
		if(!bList.isEmpty()) {
	
			mv.addObject("bList",bList);
			
		}else {
			mv.addObject("bList",null);
			
		}
		
		/////페이징용////
		int totalCount = bService.getTotalCount(searchCondition, searchValue);
		
		int naviLimit = 5; //한 화면에 출력할 게시판 페이지 수
		int maxPage; //게시판의 총 페이지 수
		int startNavi; //한 화면에 출력되는 게시판 페이지의 처음 수
		int endNavi;//한 화면에 출력되는 게시판 페이지의 마지막 수
		
		maxPage =(int)((double)totalCount/boardLimit+0.9);
		startNavi = ((int)((double)currentPage/naviLimit+0.9)-1)*naviLimit+1;
		endNavi=startNavi+naviLimit-1;
		
		//endNavi가 maxNavi보다 커지는 오류방지
		if(maxPage<endNavi) {
			endNavi = maxPage;
		}
		
		mv.addObject("urlVal","search");
		mv.addObject("startNavi",startNavi);
		mv.addObject("endNavi", endNavi);
		mv.addObject("maxPage",  maxPage);
		////////////////////////////////페이징종료///////////////////////////////////
		
		session.setAttribute("pageNow", page);
		mv.addObject("searchValue",searchValue);
		mv.addObject("searchCondition",searchCondition);
		mv.setViewName("board/listView");
		
		
		}catch (Exception e) {
			
			mv.addObject("msg",e.getMessage()).setViewName("/common/errorPage");
	
		
		}
		
		
		return mv;
	}
  • 검색컨트롤러에서 List의 반환값이 있을때와 없을때를 구분하여 넘겨준다.
  • 약간 주석으로 지저분하게됐다, 처음부터 구성했다면 좀더 깔끔하게 했을텐데..
  • 바뀐 부분은
    		List<Board> bList = bService.printAllByValue(searchCondition, searchValue, currentPage, boardLimit);
    		
    		if(!bList.isEmpty()) {
    	
    			mv.addObject("bList",bList);
    			
    		}else {
    			mv.addObject("bList",null);
    			
    		}
    딱 이부분 뿐이다, if문을 활용하여 반환값이 있을때는 반환값을 없을때는 null을 반환했다. 나머지는 페이징에 필요한 코드이기때문에 if문 밖에 배치했다.
  • 이제 검색에 해당하는 데이터가 없을때는 데이터가 없다는 페이지가 출력된다.

검색했을때 검색창에 내가 검색한 카테고리, 검색어 유지하기

jsp에서 폼에 값 넣어주기


		<tr>
			<td colspan="4" align="center">
				<form action="/board/search.kh" method="get">
			//2		
						<select name="searchCondition">
						<option value="all" <c:if test="${searchCondition eq 'all' }"> selected </c:if>>전체</option>
						<option value="writer" <c:if test="${searchCondition eq 'writer' }"> selected </c:if> >작성자</option>
						<option value="title" <c:if test="${searchCondition eq 'title' }"> selected </c:if> >제목</option>
						<option value="contents" <c:if test="${searchCondition eq 'contents' }"> selected </c:if> >내용</option>
					</select> 
					
				//1	
					<input type="text" size="25" name="searchValue"	required="required" value="${searchValue }"> 
					<input type="submit" value="검색">
				</form>
			</td>
			<td colspan="2" align="center">
				<button onclick="location.href='/board/writeView.kh';">글쓰기</button>
			</td>
		</tr>
	</table>

</body>

<script>

</script>
</html>
  1. 검색어를 쓰는 검색창에 value값으로 ${searchValue }를 선언했다. 검색어가 없다면 아무것도 출력되지 않을것이다.
  2. <option value="all" <c:if test="${searchCondition eq 'all' }"> selected </c:if>>전체</option>
    1. c:if문을 활용하여 카테고리의 value와 현재 카테고리가 일치하면 selected가 선언되도록 설정하였다.
    2. 설정된 카테고리가 없다면 따로 선택되지 않고 기본값으로 유지될것이다.
profile
hello world

0개의 댓글