Spring
230208 Spring myweb 기능구현 다음글-이전글
주영재
2023. 2. 8. 20:06
다음글, 이전글
MySQL limit함수
limit 1이면 조회된 데이터에서 제일 첫번째, 10이면 상위 10개.
서브쿼리는 ()를 친다.
TripMapper.xml에서(xml이나 html에서) 부등호 <,>를 태그로 인식해버린다.
따라서, <![CDATA[]]>로 문자열을 감싸야 순수한 문자열로 인식한다.
=> <![CDATA[sql문]]>으로 만들어줘야 한다.
=>대소비교를 할 때 <![CDATA[]]>를 무조건 사용한다.
이전글 다음글을 화면에 출력하려면 고려해야 할 사항이 많다!
MySQL
-- where tno any(다중값)
select tno from trip where tno=4;
select tno from trip where tno <4 order by tno desc limit 1;
select tno from trip where tno>4 limit 1;
select *from trip
where tno in (
(select tno from trip where tno <4 order by tno desc limit 1),
(select tno from trip where tno>4 limit 1)
)order by tno desc;
Controller
//상세페이지
@RequestMapping("/notice_view")
public String notice_view(@RequestParam("tno")int tno, Model model) {
//클릭한 글 번호에 대한 내용을 조회
TripVO vo = tripService.getContent(tno);
model.addAttribute("vo",vo);
//조회수-Cookie or 세션 이용해서 조회수 중복 방지
tripService.hitUpdate(tno); //조회수 업데이트
//이전글, 다음글
ArrayList<TripVO> list = tripService.getPrevNext(tno);
model.addAttribute("list", list);
return "trip/notice_view";
}
mapper.xml
<!-- xml or html에서 부등호는 태그로 인식이 되는데, <![CDATA[]]>는 순수한 문자열 형태로 인식을 시킨다. -->
<select id="getPrevNext" resultType="TripVO">
<![CDATA[
select *from trip
where tno in (
(select tno from trip where tno <#{tno} order by tno desc limit 1),
(select tno from trip where tno>#{tno} limit 1))
order by tno desc]]>
</select>
view.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<ul class="near_list mt20">
<!--
1.글이 2개인 경우 -이전글 번호<현재글 번호인 경우 이전글
2.글이 1개인 경우 -리스트 길이가 1이고, 글 번호<현재글 번호인 경우는 다음글이 없음
-->
<c:forEach var="data" items="${list}">
<c:if test="${fn:length(list)==1 and data.tno<vo.tno }">
<li><h4 class="prev">다음글</h4>마지막 글입니다.</li>
</c:if>
<c:if test="${data.tno<vo.tno }">
<li><h4 class="next">이전글</h4><a href="notice_view?tno=${data.tno}">${data.title }</a></li>
</c:if>
<c:if test="${data.tno>vo.tno }">
<li><h4 class="prev">다음글</h4><a href="notice_view?tno=${data.tno}">${data.title }</a></li>
</c:if>
<c:if test="${fn:length(list)==1 and data.tno>vo.tno }">
<li><h4 class="next">이전글</h4>첫번째 글입니다.</li>
</c:if>
</c:forEach>
</ul>
-class의 prev와 next는 단순히 css임. 신경쓰지 말 것.
-sql문의 order by를 통해 4번글이면 5번글이 먼저, 3번글이 다음에 담긴다.
-list에 한개만 담길 때 and로 tno값을 검사한다.
-list에 내용이 없으면 for문이 동작하지 않는다. 그러니 글이 없을 때의 if는 안해줘도 된다.
-글의 순서에 유의할 것. tno로 값을 가져오기 때문에 현재 글의 tno(${vo.tno})와 이전글/다음글의 tno(${data.tno})를 생각하면서 if문을 작성할 것.
-data.tno<vo.tno나 data.tno>vo.tno의 조건이 짝으로 있다. 먼저 if문이 돌아갔을 때 li가 그려질 순서가 중요하다.