프로그래밍/Java_Spring 게시판 만들기

Spring 게시판 만들기 (6) - 페이징 처리(전자정부프레임워크 페이징)

개발계발게발 2021. 9. 3. 17:44
반응형

https://www.egovframe.go.kr/wiki/doku.php?do=show&id=egovframework%3Arte%3Aptl%3Aview%3Apaginationtag 

 

egovframework:rte:ptl:view:paginationtag [eGovFrame]

전자정부프레임워크에서는 페이징 처리의 편의를 위해 태그를 제공한다. 페이징 기능을 사용할때 기능은 유사하지만 이미지나 라벨등의 포맷만 다양하게 사용하게 되는 경우가 있

www.egovframe.go.kr

 

pom.xml

 

전자정부 페이징 repository, dependency 추가

		<repository>
			<id>egovframe</id>
			<url>http://www.egovframe.go.kr/maven/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>

<!-- 전자정부 페이징 -->
		<dependency>
			<groupId>egovframework.rte</groupId>
			<artifactId>egovframework.rte.ptl.mvc</artifactId>
			<version>3.8.0</version>
		</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.knowhoon</groupId>
	<artifactId>web</artifactId>
	<name>aug24re</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>4.3.2.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

	</properties>

	<repositories>
		<repository>
			<id>mvn2</id>
			<url>http://repo1.maven.org/maven2/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>egovframe</id>
			<url>http://www.egovframe.go.kr/maven/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

	<dependencies>
		<!-- 전자정부 페이징 -->
		<dependency>
			<groupId>egovframework.rte</groupId>
			<artifactId>egovframework.rte.ptl.mvc</artifactId>
			<version>3.8.0</version>
		</dependency>
	
		
		<!-- 파일 업로드용 -->
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>

		<!-- mariadb -->
		<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>2.7.2</version>
		</dependency>

		<!-- 추가 DriverManager를 가지고 있는 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- mybatis -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.6</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.2</version>
		</dependency>


		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

 

 

 

src/main/webapp/WEB-INF/spring/root-context.xml에 bean 추가

 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<!-- For Pagination Tag -->	 
	<bean id="imageRenderer" class="com.knowhoon.util.ImagePaginationRenderer"/>
 
	<bean id="textRenderer" class="egovframework.rte.ptl.mvc.tags.ui.pagination.DefaultPaginationRenderer"/>
 
	<bean id="paginationManager" class="egovframework.rte.ptl.mvc.tags.ui.pagination.DefaultPaginationManager">
		<property name="rendererType">
			<map>
				<entry key="image" value-ref="imageRenderer"/>
				<entry key="text" value-ref="textRenderer"/>
			</map>
		</property>
	</bean>
	
</beans>

 

 

ImagePaginaionRenderer.java 추가

package com.knowhoon.util;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;

import egovframework.rte.ptl.mvc.tags.ui.pagination.AbstractPaginationRenderer;

public class ImagePaginationRenderer extends AbstractPaginationRenderer implements ServletContextAware  {
	
	private ServletContext servletContext;

	public ImagePaginationRenderer() {

	}

	public void initVariables() {
		firstPageLabel = " <a href=\"?pageIndex={1}\" class=\"paginationInfoText\" onclick=\"{0}({1});return false; \">처음</a> ";
		previousPageLabel = " <a href=\"?pageIndex={1}\" class=\"paginationInfoText\"  onclick=\"{0}({1});return false; \">이전</a> ";
		currentPageLabel = " <strong style=\"color: red; font-size: 18px;\">{0}</strong> ";
		otherPageLabel = " <a href=\"?pageIndex={1}\" style=\"color: black; font-size: 18px;\" onclick=\"{0}({1});return false; \">{2}</a> ";
		nextPageLabel = " <a href=\"?pageIndex={1}\" class=\"paginationInfoText\"  onclick=\"{0}({1});return false; \">다음</a> ";
		lastPageLabel = " <a href=\"?pageIndex={1}\" class=\"paginationInfoText\" onclick=\"{0}({1});return false; \">끝</a> ";
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		initVariables();
	}
}

 

 

TestController.java board 수정

package com.knowhoon.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.knowhoon.util.Util;

import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

@Controller
public class TestController {
	@Autowired
	private TestService testService;
	@Autowired
	private Util util;
	@RequestMapping("/menu")
	public ModelAndView header(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("menu");
		int sb_cate = 1 ;
		List<HashMap<String, Object>> categoryList = testService.categoryList();
		mv.addObject("categoryList", categoryList);
		if(request.getParameter("sb_cate") != null || util.str2Int(request.getParameter("sb_cate")) != 0){
			sb_cate = Integer.parseInt(request.getParameter("sb_cate"));
			if(sb_cate > categoryList.size()) {
				sb_cate = 1;
			}
		}
		String category = (String) categoryList.get(sb_cate-1).get("sca_category");
		mv.addObject("category", category);	
		return mv;		
	}
	
	@RequestMapping(value = "/board", method = RequestMethod.GET)
	public ModelAndView board(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("board");
		//데이터 베이스 접근 값 가져오기
		// DAO / DTO(VO)	Service
		
		int sb_cate = 1 ;
		
		if(request.getParameter("sb_cate") == null || util.str2Int(request.getParameter("sb_cate")) == 0){
						
		}else {
			sb_cate = Integer.parseInt(request.getParameter("sb_cate"));
		}
		Map<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("sb_cate", sb_cate);
		
		//페이지네이션인포
		PaginationInfo paginationInfo = new PaginationInfo();
		int pageNo = 1; //현재 페이지 번호
		int listScale = 10; //한 페이지에 나올 글 수
		int pageScale = 10; // 페이지 개수
		
		if(request.getParameter("pageNo") != null) {
			pageNo = util.str2Int(request.getParameter("pageNo"));
		}
		
		paginationInfo.setCurrentPageNo(pageNo);	//현재 페이지 번호
		paginationInfo.setRecordCountPerPage(listScale);	//한 페이지에 나올 글 수
		paginationInfo.setPageSize(pageScale);	//페이지 개수
		
		int startPage = paginationInfo.getFirstRecordIndex(); // 시작페이지
		int lastPage = paginationInfo.getRecordCountPerPage(); // 마지막페이지
		
		sendMap.put("startPage", startPage); // sendMap에 시작페이지 추가
		sendMap.put("lastPage", lastPage);	 // sendMap에 마지막 페이지 추가
		mv.addObject("sb_cate", sb_cate);
		List<TestDTO> boardList = testService.boardList(sendMap);
		paginationInfo.setTotalRecordCount(boardList.get(0).getTotalList());//전체 글 수 저장
		mv.addObject("boardList", boardList);
		mv.addObject("paginationInfo", paginationInfo);
		mv.addObject("pageNo", pageNo);
		//그 값을 mv에 저장
		//board에 찍기
		
		return mv;
	}
	
	//@RequestMapping(value = "/write", method = {RequestMethod.GET, RequestMethod.POST})
	//@RequestMapping(value ="/write") 메소드 생략시 GET, POST 둘다 받는다.
	@GetMapping("/write")
	public String write(HttpServletRequest request) {
		if(request.getSession().getAttribute("sm_id") != null && request.getSession().getAttribute("sm_name") != null) {
			return "write";			
		}else {
			return "redirect:/?writeError";
		}	
	}
	
	//HttpServletRequest request
	//@Requestparam("title) String title
	//DTO방식 두가지 다 시연하기
	@PostMapping("/write")
	public String write2(TestDTO testDTO, HttpServletRequest request) {
		//String title = request.getParameter("title");
		//String content = request.getParameter("content");
		if(request.getSession().getAttribute("sm_id") != null && request.getSession().getAttribute("sm_name") != null) {
			testDTO.setSm_id((String) request.getSession().getAttribute("sm_id"));
			testService.write(testDTO);
			return "redirect:/board?sb_cate=" + testDTO.getSb_cate();//board 메소드 다시 실행			
		}else {
			return "redirect:/?writeError2";
		}	
	}
	@GetMapping("/detail")
	public ModelAndView detail(@RequestParam("sb_no") Integer sb_no) {
		ModelAndView mv = new ModelAndView("detail");
		mv.addObject("detail", testService.boardDetail(sb_no));
		return mv;
	}
	@GetMapping("/boardDelete")
	public String boardDelete(@RequestParam("sb_no") Integer sb_no) {
				
		int result = testService.delete(sb_no);	
		System.out.println("결과 : " + result);
		return "redirect:/board";
	}
	
	@GetMapping("/boardUpdate")
	public ModelAndView boardUpdate(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("boardUpdate");
		int sb_no = Integer.parseInt(request.getParameter("sb_no"));
		
		mv.addObject("update",testService.boardDetail(sb_no));
		
		return mv;
	}
	@PostMapping("/boardUpdate")
	public String boardUpdate2(TestDTO testDTO) { //name이 똑같다면 자동으로 저장
		
		int result = testService.update(testDTO);
		if(result == 1) {
			return "redirect:/detail?sb_no=" + testDTO.getSb_no();			
		}else {
			return "redirect:/error?modifyError";
		}
	}
}

 

 

board 페이지 수정

<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui" %>
------------------------------------
<script type="text/javascript">
function linkPage(pageNo){
	location.href="./board?pageNo="+pageNo+"&sb_cate="+${sb_cate};
}

------------------------------------
<ui:pagination paginationInfo="${paginationInfo }" type="text" jsFunction="linkPage"/>

 

 

board.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="./css/wrapper.css">
<link rel="stylesheet" href="./css/index.css">
<script type="text/javascript">
function linkPage(pageNo){
	location.href="./board?pageNo="+pageNo+"&sb_cate="+${sb_cate};
}
</script>
</head>
<body>
<div id="wrapper">
	<header>
		<jsp:include page="./header.jsp"></jsp:include>
		<c:import url="/menu"/>
	</header>
	<main id="container">
		<ul id="subTitle" class="title">
			<li>번호</li>
			<li>제목</li>
			<li>날짜</li>
			<li>조회수</li>
			<li>추천수</li>
			<li>글쓴이</li>
		</ul>
		<c:choose>
			<c:when test="${fn:length(boardList) gt 0 }">
				<c:forEach items="${boardList }" var="l">
					<ul id="main" class="title" onclick="location.href='./detail?sb_no=${l.sb_no }'">
						<li>${l.sb_no }</li>
						<li>${l.sb_title }</li>
						<li>${l.sb_date }</li>
						<li>${l.sb_count }</li>
						<li>${l.sb_like }</li>						
						<li>${l.sm_name }<small>(${l.sm_id })</small></li>
					</ul>
				</c:forEach>
				<!-- 페이징 -->
				<div style="text-align: center;"><ui:pagination paginationInfo="${paginationInfo }" type="text" jsFunction="linkPage"/>
				</div>
			</c:when>
			<c:otherwise>
				출력할 글이 없습니다.<br/><br/>
			</c:otherwise>
		</c:choose>
		<c:if test="${sessionScope.sm_id ne null }">
		<a class="navHover" href="./write?sb_cate=${sb_cate }">글쓰기</a>
		</c:if>

	</main>
	<footer></footer>
</div>
</body>
</html>

 

완성

정상 작동

반응형