[Spring] 13. 게시판 - 검색개발자가 되기까지 (2023.08.16~2024.04.15)/[Spring] Basic Web2024. 1. 17. 15:05
Table of Contents
PagingVO.java
package com.basicWeb.www.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString
@Setter
@Getter
public class PagingVO {
// ... (기존 코드)
private String type;
private String keyword;
// ... (기존 코드)
public String[] getTypeToArray() {
return this.type == null ?
new String[] {} : this.type.split("");
}
}
TypeToArry() Methd는 type이 null 이라면 배열로 생성해주고,
null이 아니라면 한글자씩 따서 String 배열에 넣어준다.
앞에 get을 붙여준 이유는 SQL에서 사용하기 위해서 붙여주었다.
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../layout/header.jsp"></jsp:include>
<jsp:include page="../layout/nav.jsp"></jsp:include>
<div class="container-md">
<!-- search line -->
<br>
<div class="col-sm-12 col-md-6">
<form action="/board/list" method="get">
<div class="input-group mb-3">
<c:set value="${ph.pgvo.type }" var="typed"></c:set>
<select class="form-select" name="type" id="inputGroupSelect01">
<option ${typed eq null ? 'selected' : '' }>선택</option>
<option value ="t" ${typed eq 't' ? 'selected' : '' }>제목</option>
<option value ="c" ${typed eq 'c' ? 'selected' : '' }>내용</option>
<option value ="w" ${typed eq 'w' ? 'selected' : '' }>작성자</option>
<option value ="wc" ${typed eq 'wc' ? 'selected' : '' }>제목&내용</option>
<option value ="twc" ${typed eq 'twc' ? 'selected' : '' }>전체</option>
</select>
<input type="hidden" name="pageNo" value="1">
<input type="hidden" name="qty" value="${ph.pgvo.qty }">
<input type="search" name="keyword" value="${ph.pgvo.keyword }"
class="form-control me-2" placeholder="검색">
<button type="submit" class="btn btn-outline-success">검색
<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
${ph.totalCount }
<span class="visually-hidden">unread messages</span>
</span>
</button>
</div>
</form>
</div>
<table class="table">
<!-- ... (기존 코드) -->
</table>
<!-- 페이징 라인 -->
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item ${(ph.prev eq false) ? 'disabled' : '' }">
<a class="page-link"
href="/board/list?pageNo=${ph.startPage-1 }&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}"
aria-label="Previous"><span aria-hidden="true">«</span></a>
</li>
<c:forEach begin="${ph.startPage }" end="${ph.endPage }" var="i">
<li class="page-item">
<a class="page-link"
href="/board/list?pageNo=${i }&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}">${i}</a>
</li>
</c:forEach>
<li class="page-item ${(ph.next eq false) ? 'disabled' : '' }">
<a class="page-link" href="/board/list?pageNo=${ph.endPage+1 }&qty=${ph.pgvo.qty}&type=${ph.pgvo.type}&keyword=${ph.pgvo.keyword}" aria-label="Next"><span aria-hidden="true">»</span></a>
</li>
</ul>
</nav>
</div>
<jsp:include page="../layout/footer.jsp"></jsp:include>
검색 라인을 작성하고 페이징 라인에 검색 했을 때, 검색 중인 상태가 유지될 수 있도록
<a>태그의 href를 수정했다.
boardMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.basicWeb.www.repository.BoardDAO">
<!-- ... (기존 코드) -->
<select id="getList" resultType="com.basicWeb.www.domain.BoardVO">
SELECT * FROM board
<include refid="search"></include>
ORDER BY bno desc
LIMIT #{startPage}, #{qty}
</select>
<select id="totalCount" resultType="int">
SELECT COUNT(bno) FROM board
<include refid="search"></include>
</select>
<!-- ... (기존 코드) -->
<sql id="search">
<if test="type != null">
<trim prefix="WHERE (" suffix=")" prefixOverrides="or">
<foreach collection="typeToArray" item="type">
<trim prefix="or">
<choose>
<when test="type == 't'.toString()">
title like concat('%',#{keyword}, '%')
</when>
<when test="type == 'w'.toString()">
writer like concat('%', #{keyword}, '%')
</when>
<when test="type == 'c'.toString()">
content like concat('%', #{keyword}, '%')
</when>
</choose>
</trim>
</foreach>
</trim>
</if>
</sql>
</mapper>
예비구문으로 사용된 동적 SQL에 대한 설명이 필요하다면
https://rlog0918.tistory.com/185
https://rlog0918.tistory.com/184
두 링크를 참고한다.
BoardController.java
package com.basicWeb.www.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.basicWeb.www.domain.BoardVO;
import com.basicWeb.www.domain.PagingVO;
import com.basicWeb.www.handler.PagingHandler;
import com.basicWeb.www.service.BoardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequestMapping("/board/*")
@RequiredArgsConstructor
@Controller
public class BoardController {
private final BoardService bsv;
// ... (기존 코드)
@GetMapping("/list")
public void list (Model m, PagingVO pgvo) {
log.info(">>> pgvo >>> {}", pgvo);
List<BoardVO> list = bsv.getList(pgvo);
int totalCount = bsv.totalCount(pgvo);
PagingHandler ph = new PagingHandler(pgvo, totalCount);
m.addAttribute("list", list);
m.addAttribute("ph", ph);
}
// ... (기존 코드)
}
검색을 했을 때, 검색에 따른 게시물 수도 표시하기 위해서 totalCount() Method에 pgvo 매개변수를 주었다.
BoardService.interface
package com.basicWeb.www.service;
import java.util.List;
import com.basicWeb.www.domain.BoardVO;
import com.basicWeb.www.domain.PagingVO;
public interface BoardService {
// ... (기존 코드)
int totalCount(PagingVO pgvo);
}
BoardServiceImpl.java
package com.basicWeb.www.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.basicWeb.www.domain.BoardVO;
import com.basicWeb.www.domain.PagingVO;
import com.basicWeb.www.repository.BoardDAO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
@Service
public class BoardServiceImpl implements BoardService{
private final BoardDAO bdao;
// ... (기존 코드)
@Override
public int totalCount(PagingVO pgvo) {
// TODO Auto-generated method stub
return bdao.totalCount(pgvo);
}
}
BoardDAO.interface
package com.basicWeb.www.repository;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.basicWeb.www.domain.BoardVO;
import com.basicWeb.www.domain.PagingVO;
public interface BoardDAO {
// ... (기존 코드)
int totalCount(PagingVO pgvo);
}
<검색 화면>
<검색이 유지중인 화면>
[Spring] 13. 게시판 - 검색
(다음 게시물 예고편)
[Spring] 14. 단위 테스트 (JUnit)
728x90
@rlozlr :: 얼렁뚱땅 개발자
얼렁뚱땅 주니어 개발자
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!