TIL/academy

국비 TIL(Today I Learned) 20220809 테이블 페이징 처리

토희 2022. 8. 9. 18:18
728x90

Paging(페이징) : 데이터를 분할하여 제공

어떻게 구현하는거에 따라 방식이 다 제각각

 

포인트! 

- 한번에 몇 건의 데이터를 가지고 올 것인가

- 페이지를 몇 개씩 보여줄 것인가

 

 

 

 

 

PAGECOUNT 상수

 

 

 

 

Bin으로 만들었다가 Map으로 만들었다...

Bin이 뭐요

 

 

페이지라는 데이터를 넘겨줘야 하는데, 아직 넘겨준적이 없음

params를 넘겨줬으니, ITestService, TestService, ITestDao, TestDao도 수정해주고,

쿼리도 수정

getSellCnt() a메서드 만들고!

TestDao까지 쭉쭉쭉

 

 

지금은 데이터가 같은상황이라 결과물이 똑같긴 하지만

 

 

sellList.jsp

 

 

sellDetail.jsp

sellRes, sellUpdate에도 똑같이 적어주기

 

강사님의 샘플위치

우리는 이걸 가져다 와서 쓴거임

페이지 전환시 들고다닐 것들

=> 다시 돌아왔을 때 상태를 유지하기 위한 값들

ex) 상세보기 갔다가 목록으로 왔을때 페이지정보 필요

 

 

강사님이랑 sell테이블 같이하고, manager테이블 페이징에 대해서는 실습

내일 풀어줄 예정

 

TestController.jsp

바뀐곳은 sellList, managerList 부분

package com.spring.sample.web.test.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.spring.sample.common.service.IPagingService;
import com.spring.sample.web.test.service.ITestService;

@Controller
public class TestController {
	// 3.
	@Autowired
	public ITestService iTestService;

	@Autowired
	public IPagingService ips; // 페이징 서비스 객체 주입

	/*
	 * Database나 파일 같이 외부에 접근하는 경우 외적 요인으로 문제가 발샐할 수 있음으로 예외처리가 반드시 필요하다.
	 */

	// 글 목록
	@RequestMapping(value = "/sellList")
	public ModelAndView sellList(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		// 현재페이지
		int page = 1;

		if (params.get("page") != null) { // 페이지가 넘어왔을때
			page = Integer.parseInt(params.get("page")); // 받아온 페이지 할당
		}

		// 총 데이터 개수 취득
		int cnt = iTestService.getSellCnt(params);

		// 페이징 데이터 계산
		// ips.getPagingData(page, maxCount, viewCnt, pageCnt)
		HashMap<String, Integer> pd = ips.getPagingData(page, cnt, 3, 2);

		// 파라미터에 시작, 종료값 추가
		// 한쪽으로 필요 데이터를 몰았다?
		params.put("start", Integer.toString(pd.get("start")));
		params.put("end", Integer.toString(pd.get("end")));

		// 데이터 취득
		List<HashMap<String, String>> list = iTestService.getSellList(params);

		// 목록 데이터
		mav.addObject("list", list);
		// 페이징 정보
		mav.addObject("pd", pd);
		// 현재 페이지
		mav.addObject("page", page);
		mav.setViewName("test/sellList");

		return mav;
	}

	// 글 상세보기
	@RequestMapping(value = "/sellDetail")
	// 페이지 이동할때 값이 하나가 넘어가는 경우가 거의 없음,
	// params를 다른이름 줘도됨, a이든 뭐든 상관없음, 여기서만, 나는 HashMap만 받으면 된다
	public ModelAndView sellDetail(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		// no가 값이 안 넘어오거나 no자체가 안넘어온 경우
		if (params.get("no") == null || params.get("no") == "") {
			// setViewName에서 redirect : 해당 주소로 이동한다.
			// 단, GET방식밖에 안됨
			// 사용시 고민해야부분 중 하나는 단순이동할때는 redirect, 나머지는 문제가 있을수있다. 값이 주소창에 나옴!
			// mav.addObject("test", "abc"); // get방식으로 쓰이는 예
			mav.setViewName("redirect:sellList");

		} else {
			HashMap<String, String> data = iTestService.getSell(params);

			mav.addObject("data", data);
			mav.setViewName("test/sellDetail");
		}

		return mav;
	}

	// 글 추가
	@RequestMapping(value = "/sellInsert")
	public ModelAndView sellInsert(ModelAndView mav) {
		// DB에 붙을게 없으니, 굳이 예외처리 할 필요 없음
		mav.setViewName("test/sellInsert");
		return mav;
	}

	// 글 등록
	@RequestMapping(value = "/sellRes")
	public ModelAndView sellInsertRes(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		try {
			int cnt = 0; // insert, update, delete 다 쓸거기 때문에 처음에 0줌

			switch (params.get("gbn")) {
			case "i":
				cnt = iTestService.insertSell(params);
				break;
			case "u":
				cnt = iTestService.updateSell(params);
				break;
			case "d":
				cnt = iTestService.deleteSell(params);
				break;
			}

			if (cnt > 0) { // 1건 이상 등록된 경우
				mav.addObject("res", "success");
			} else { // 등록 안된 경우
				mav.addObject("res", "failded");
			}
		} catch (Exception e) { // 예외 발생시
			e.printStackTrace();
			mav.addObject("res", "error");
		}
		mav.setViewName("test/sellRes");
		return mav;
	}

	// 글 수정페이지
	@RequestMapping(value = "/sellUpdate")
	public ModelAndView sellUpdate(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {
		// 기존데이터 조회해와야함
		HashMap<String, String> data = iTestService.getSell(params);
		mav.addObject("data", data);

		mav.setViewName("test/sellUpdate");

		return mav;

	}

	// 실습
	@RequestMapping(value = "/managerList")
	public ModelAndView managerList(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		// 현재페이지
		int page = 1;

		if (params.get("page") != null) { // 페이지가 넘어왔을때
			page = Integer.parseInt(params.get("page")); // 받아온 페이지 할당
		}

		// 총 데이터 개수 취득
		int cnt = iTestService.getManagerCnt(params);

		// 페이징 데이터 계산
		// ips.getPagingData(page, maxCount, viewCnt, pageCnt)
		HashMap<String, Integer> pd = ips.getPagingData(page, cnt, 3, 2);

		// 파라미터에 시작, 종료값 추가
		// 한쪽으로 필요 데이터를 몰았다?
		params.put("start", Integer.toString(pd.get("start")));
		params.put("end", Integer.toString(pd.get("end")));

		// 데이터 취득
		List<HashMap<String, String>> list = iTestService.getManagerList(params);

		// 목록 데이터
		mav.addObject("list", list);
		// 페이징 정보
		mav.addObject("pd", pd);
		// 현재 페이지
		mav.addObject("page", page);

		mav.setViewName("test/managerList");

		return mav;
	}

	@RequestMapping(value = "/managerDetail")
	public ModelAndView managerDetail(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		if (params.get("no") == null || params.get("no") == "") {
			mav.setViewName("redirect:managerList");

		} else {
			HashMap<String, String> data = iTestService.getManager(params);

			mav.addObject("data", data);
			mav.setViewName("test/managerDetail");
		}

		return mav;
	}

	@RequestMapping(value = "/managerInsert")
	public ModelAndView managerInsert(ModelAndView mav) {
		mav.setViewName("test/managerInsert");
		return mav;

	}

	@RequestMapping(value = "/managerRes")
	public ModelAndView managerInsertRes(@RequestParam HashMap<String, String> params, ModelAndView mav)
			throws Throwable {

		System.out.println(params.toString());
		try {
			int cnt = 0; // insert, update, delete 다 쓸거기 때문에 처음에 0줌

			switch (params.get("gbn")) {
			case "i":
				cnt = iTestService.insertManager(params);
				break;
			case "u":
				cnt = iTestService.updateManager(params);
				break;
			case "d":
				cnt = iTestService.deleteManager(params);
				break;
			}

			if (cnt > 0) { // 1건 이상 등록된 경우
				mav.addObject("res", "success");
			} else { // 등록 안된 경우
				mav.addObject("res", "failded");
			}
		} catch (Exception e) { // 예외 발생시
			e.printStackTrace();
			mav.addObject("res", "error");
		}
		mav.setViewName("test/managerRes");
		return mav;
	}

	// 글 수정페이지
	@RequestMapping(value = "/managerUpdate")
	public ModelAndView managerUpdate(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {
		// 기존데이터 조회해와야함
		HashMap<String, String> data = iTestService.getManager(params);
		mav.addObject("data", data);

		mav.setViewName("test/managerUpdate");

		return mav;

	}

	// divs 글 목록페이지
	@RequestMapping(value = "/divsList")
	public ModelAndView divsList(ModelAndView mav) throws Throwable {
		// 데이터 취득
		List<HashMap<String, String>> list = iTestService.getDivsList();

		mav.addObject("list", list);
		mav.setViewName("test/divsList");

		return mav;
	}

	// divs 글 상세페이지
	@RequestMapping(value = "/divsDetail")

	public ModelAndView divsDetail(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		System.out.println(params.toString());
		if (params.get("no") == null || params.get("no") == "") {
			mav.setViewName("redirect:divsList");

		} else {
			HashMap<String, String> data = iTestService.getDivs(params);

			mav.addObject("data", data);
			mav.setViewName("test/divsDetail");
		}

		return mav;
	}

	// divs 글 추가
	@RequestMapping(value = "/divsInsert")
	public ModelAndView divsInsert(ModelAndView mav) {
		mav.setViewName("test/divsInsert");
		return mav;

	}

	@RequestMapping(value = "/divsRes")
	public ModelAndView divsInsertRes(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {

		System.out.println(params.toString());
		try {
			int cnt = 0; // insert, update, delete 다 쓸거기 때문에 처음에 0줌

			switch (params.get("gbn")) {
			case "i":
				cnt = iTestService.insertDivs(params);
				break;
			case "u":
				cnt = iTestService.updateDivs(params);
				break;
			case "d":
				cnt = iTestService.deleteDivs(params);
				break;
			}

			if (cnt > 0) { // 1건 이상 등록된 경우
				mav.addObject("res", "success");
			} else { // 등록 안된 경우
				mav.addObject("res", "failded");
			}
		} catch (Exception e) { // 예외 발생시
			e.printStackTrace();
			mav.addObject("res", "error");
		}
		mav.setViewName("test/divsRes");
		return mav;
	}

	@RequestMapping(value = "/divsUpdate")
	public ModelAndView divsUpdate(@RequestParam HashMap<String, String> params, ModelAndView mav) throws Throwable {
		// 기존데이터 조회해와야함
		HashMap<String, String> data = iTestService.getDivs(params);
		mav.addObject("data", data);

		mav.setViewName("test/divsUpdate");

		return mav;

	}

}

 

 

ITestService.java

package com.spring.sample.web.test.service;

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

public interface ITestService {

	public List<HashMap<String, String>> getSellList(HashMap<String, String> params) throws Throwable;

	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable;

	public int insertSell(HashMap<String, String> params) throws Throwable;

	public int deleteSell(HashMap<String, String> params) throws Throwable;

	public int updateSell(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getManagerList(HashMap<String, String> params) throws Throwable;

	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable;

	public int insertManager(HashMap<String, String> params) throws Throwable;

	public int updateManager(HashMap<String, String> params) throws Throwable;

	public int deleteManager(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getDivsList() throws Throwable;

	public HashMap<String, String> getDivs(HashMap<String, String> params) throws Throwable;

	public int insertDivs(HashMap<String, String> params) throws Throwable;

	public int updateDivs(HashMap<String, String> params) throws Throwable;

	public int deleteDivs(HashMap<String, String> params) throws Throwable;

	public int getSellCnt(HashMap<String, String> params) throws Throwable;

	public int getManagerCnt(HashMap<String, String> params) throws Throwable;

}

 

TestService.java

package com.spring.sample.web.test.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.sample.web.test.dao.ITestDao;

@Service
public class TestService implements ITestService {
	// 2. DAO를 가져다 쓰는걸 만들어야함
	@Autowired
	public ITestDao iTestDao;

	@Override
	public List<HashMap<String, String>> getSellList(HashMap<String, String> params) throws Throwable {
		return iTestDao.getSellList(params);
	}

	@Override
	// getSell매소드의 인자로 HashMap<String, String> param 받는거
	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.getSell(params);
	}

	@Override
	public int insertSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.insertSell(params);
	}

	@Override
	public int deleteSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.deleteSell(params);
	}

	@Override
	public int updateSell(HashMap<String, String> params) throws Throwable {
		return iTestDao.updateSell(params);
	}

	@Override
	public List<HashMap<String, String>> getManagerList(HashMap<String, String> params) throws Throwable {
		return iTestDao.getManagerList(params);
	}

	@Override
	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.getManager(params);
	}

	@Override
	public int insertManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.insertManager(params);
	}

	@Override
	public int updateManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.updateManager(params);
	}

	@Override
	public int deleteManager(HashMap<String, String> params) throws Throwable {
		return iTestDao.deleteManager(params);
	}

	@Override
	public List<HashMap<String, String>> getDivsList() throws Throwable {
		return iTestDao.getDivsList();
	}

	@Override
	public HashMap<String, String> getDivs(HashMap<String, String> params) throws Throwable {
		return iTestDao.getDivs(params);
	}

	@Override
	public int insertDivs(HashMap<String, String> params) throws Throwable {
		return iTestDao.insertDivs(params);
	}

	@Override
	public int updateDivs(HashMap<String, String> params) throws Throwable {
		return iTestDao.updateDivs(params);
	}

	@Override
	public int deleteDivs(HashMap<String, String> params) throws Throwable {
		return iTestDao.deleteDivs(params);
	}

	@Override
	public int getSellCnt(HashMap<String, String> params) throws Throwable {
		return iTestDao.getSellCnt(params);
	}

	@Override
	public int getManagerCnt(HashMap<String, String> params) throws Throwable {
		return iTestDao.getManagerCnt(params);
	}

}

 

ITestDao.java

package com.spring.sample.web.test.dao;

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

public interface ITestDao {

	public List<HashMap<String, String>> getSellList(HashMap<String, String> params) throws Throwable;

	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable;

	public int insertSell(HashMap<String, String> params) throws Throwable;

	public int deleteSell(HashMap<String, String> params) throws Throwable;

	public int updateSell(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getManagerList(HashMap<String, String> params) throws Throwable;

	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable;

	public int insertManager(HashMap<String, String> params) throws Throwable;

	public int deleteManager(HashMap<String, String> params) throws Throwable;

	public int updateManager(HashMap<String, String> params) throws Throwable;

	public List<HashMap<String, String>> getDivsList() throws Throwable;

	public HashMap<String, String> getDivs(HashMap<String, String> params) throws Throwable;

	public int insertDivs(HashMap<String, String> params) throws Throwable;

	public int updateDivs(HashMap<String, String> params) throws Throwable;

	public int deleteDivs(HashMap<String, String> params) throws Throwable;

	public int getSellCnt(HashMap<String, String> params) throws Throwable;

	public int getManagerCnt(HashMap<String, String> params) throws Throwable;

}

 

TestDao.java

package com.spring.sample.web.test.dao;

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

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class TestDao implements ITestDao {
	// 1.
	@Autowired
	public SqlSession sqlSession;

	@Override
	public List<HashMap<String, String>> getSellList(HashMap<String, String> params) throws Throwable {
		// selectList("namespace.id"): 해당 namespace에 있는 id를 찾아서 조회 실행 목록을 받음
		// 목록으로 받을때 selectList
		return sqlSession.selectList("test.getSellList", params);
	}

	@Override
	public HashMap<String, String> getSell(HashMap<String, String> params) throws Throwable {
		// selectOne(쿼리, 데이터) : 해당 쿼리에 데이터를 전달하고 단건 결과를 돌려받음
		return sqlSession.selectOne("test.getSell", params);
	}

	@Override
	public int insertSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.insert("test.insertSell", params);
	}

	@Override
	public int deleteSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.delete("test.deleteSell", params);
	}

	@Override
	public int updateSell(HashMap<String, String> params) throws Throwable {
		return sqlSession.update("test.updateSell", params);
	}

	@Override
	public List<HashMap<String, String>> getManagerList(HashMap<String, String> params) throws Throwable {
		// selectList("namespace.id"): 해당 namespace에 있는 id를 찾아서 조회 실행 목록을 받음
		// 목록으로 받을때 selectList
		return sqlSession.selectList("test.getManagerList", params);
	}

	@Override
	public HashMap<String, String> getManager(HashMap<String, String> params) throws Throwable {
		// selectOne(쿼리, 데이터) : 해당 쿼리에 데이터를 전달하고 단건 결과를 돌려받음
		// selectOne이기 때문에 여러줄 들어오면 터짐
		return sqlSession.selectOne("test.getManager", params);
	}

	@Override
	public int insertManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.insert("test.insertManager", params);
	}

	@Override
	public int deleteManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.delete("test.deleteManager", params);
	}

	@Override
	public int updateManager(HashMap<String, String> params) throws Throwable {
		return sqlSession.update("test.updateManager", params);
	}

	@Override
	public List<HashMap<String, String>> getDivsList() throws Throwable {
		return sqlSession.selectList("test.getDivsList");
	}

	@Override
	public HashMap<String, String> getDivs(HashMap<String, String> params) throws Throwable {
		return sqlSession.selectOne("test.getDivs", params);
	}

	@Override
	public int insertDivs(HashMap<String, String> params) throws Throwable {
		return sqlSession.insert("test.insertDivs", params);
	}

	@Override
	public int updateDivs(HashMap<String, String> params) throws Throwable {
		return sqlSession.update("test.updateDivs", params);
	}

	@Override
	public int deleteDivs(HashMap<String, String> params) throws Throwable {
		return sqlSession.delete("test.deleteDivs", params);
	}

	@Override
	public int getSellCnt(HashMap<String, String> params) throws Throwable {
		return sqlSession.selectOne("test.getSellCnt", params);
	}

	@Override
	public int getManagerCnt(HashMap<String, String> params) throws Throwable {
		return sqlSession.selectOne("test.getManagerCnt", params);
	}

}

 

Test_SQL.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace : 클래스와 동일, 이 파일의 대표명 -->
<mapper namespace="test">
	<!-- select : 조회 
		id: 구분자, 메소드명과 동일
		resultType : 조회 결과 중 한줄에 대한 자료 형태를 지정
		hashmap: mybatis-config.xml에서 별칭 지정해놔서 줄여쓸수있는거임
		쿼리 삽입시 주의사항: ;이 있는경우 문제가 발생한다. 이유는 해당 쿼리 실행시 자동으로 추가되기 때문
	-->
	<select id="getSellList" resultType="hashmap" parameterType="hashmap">
		SELECT S.SELL_NO, S.ITEM_NAME, S.COUNT, S.SELL_DT
		FROM (SELECT SELL_NO, ITEM_NAME, COUNT, SELL_DT,
       		  ROW_NUMBER() OVER(ORDER BY SELL_DT DESC, SELL_NO DESC) AS RNK
			  FROM SELL
             ) S
		WHERE S.RNK BETWEEN #{start} AND #{end}
	</select>
	
	<!-- 
		parameterType : 실행시 받는 값 
		#{키} : 헤당위치에 문자열로 키에 해당하는 값을 넣어준다
		ex) no에 3이 들어있는 경우
		WHERE SELL_NO = #{no}
		=> WHERE SELL_NO = '3' // 문자열이기 때문에  ' '이 들어감
		parameterType dao받는값, resultType값이 db실행결과
	-->
	<select id="getSell" resultType="hashmap" parameterType="hashmap">
		SELECT SELL_NO, ITEM_NAME, COUNT, SELL_DT
		FROM SELL
		WHERE SELL_NO = #{no}
	</select>
	
	<!-- insert는 resultType 이 없음 -->
	<insert id="insertSell" parameterType="hashmap">
		INSERT INTO SELL(SELL_NO, ITEM_NAME, COUNT, SELL_DT)
		VALUES(SELL_SEQ.NEXTVAL, #{itemName},#{count},#{sellDt})
	</insert>
	
	<delete id="deleteSell" parameterType="hashmap">
		DELETE FROM SELL
		WHERE SELL_NO = #{no}
	</delete>
	
	<update id="updateSell" parameterType="hashmap">
		UPDATE SELL SET ITEM_NAME = #{itemName},
                COUNT = #{count},
                SELL_DT = #{sellDt}
       	WHERE SELL_NO = #{no}
	</update>
	
	<select id="getManagerList" resultType="hashmap" parameterType="hashmap">
		SELECT S.EMP_NO, S.NAME, S.DEPT
		FROM(SELECT EMP_NO, NAME, DEPT,
		ROW_NUMBER() OVER(ORDER BY EMP_NO DESC) AS RNK
		FROM MANAGER) S
		WHERE S.RNK BETWEEN #{start} AND #{end}
	</select>

	<select id="getManager" resultType="hashmap" parameterType="hashmap">
		SELECT EMP_NO, NAME, DEPT
		FROM MANAGER
		WHERE EMP_NO = #{no}
	</select>
	
	<insert id="insertManager" parameterType="hashmap">
		INSERT INTO MANAGER(EMP_NO, NAME, DEPT)
		VALUES(MANAGER_SEQ.NEXTVAL, #{name}, #{deptName})
	</insert>
	
	<delete id="deleteManager" parameterType="hashmap">
		DELETE FROM MANAGER
		WHERE EMP_NO = #{no}
	</delete>
	
	<update id="updateManager" parameterType="hashmap">
		UPDATE MANAGER SET NAME = #{name},
                DEPT = #{deptName}
                WHERE EMP_NO = #{no}
	</update>
	
	<select id="getDivsList" resultType="hashmap">
		SELECT DIV_CODE, DIV_NAME FROM DIVS ORDER BY DIV_CODE
	</select>
	
	<select id="getDivs" resultType="hashmap" parameterType="hashmap">
		SELECT DIV_CODE, DIV_NAME FROM DIVS
		WHERE DIV_CODE = #{no}
	</select>
	
	<insert id="insertDivs" parameterType="hashmap">
		INSERT INTO DIVS(DIV_CODE, DIV_NAME)
		VALUES((SELECT #{divCode} || LPAD(NVL(MAX(REPLACE(DIV_CODE, #{divCode}, '')),0) + 1,2,0 )
		FROM DIVS
		WHERE DIV_CODE LIKE #{divCode} || '%'), #{divName})
	</insert>
	
	<delete id="deleteDivs" parameterType="hashmap">
		DELETE FROM DIVS
		WHERE DIV_CODE = #{no}
	</delete>
	
	<update id="updateDivs" parameterType="hashmap">
		UPDATE DIVS SET DIV_CODE = #{divCode},
                DIV_NAME = #{divName}
                WHERE DIV_CODE = #{no}
	</update>
	
	
	<select id="getBookList" resultType="hashmap">
		SELECT BOOK_NO, BOOK_TITLE, BOOK_AUTHOR
		FROM BOOK
	</select>
	
	<select id="getBook" resultType="hashmap" parameterType="hashmap">
		SELECT BOOK_NO, BOOK_TITLE, BOOK_AUTHOR, BOOK_CO,
		TO_CHAR(BOOK_DT,'YYYY-MM-DD') AS BOOK_DT, TO_CHAR(REG_DT,'YYYY-MM-DD') AS REG_DT
		FROM BOOK
		WHERE BOOK_NO = #{no}
	</select>
	
	<insert id="insertBook" parameterType="hashmap">
		INSERT INTO BOOK(BOOK_NO, BOOK_TITLE, BOOK_AUTHOR, BOOK_CO, BOOK_DT)
		VALUES(BOOK_SEQ.NEXTVAL, #{bookTitle}, #{bookAuthor}, #{bookCo}, #{bookDt})
	</insert>
	
	<delete id="deleteBook" parameterType="hashmap">
		DELETE FROM BOOK
		WHERE BOOK_NO = #{no}
	</delete>
	       
	<update id="updateBook" parameterType="hashmap">
			UPDATE BOOK SET BOOK_TITLE = #{bookTitle},
                BOOK_AUTHOR = #{bookAuthor},
                BOOK_CO = #{bookCo},
                BOOK_DT = #{bookDt}
                WHERE BOOK_NO = #{no}
	</update>
	
	<select id="getSellCnt" parameterType="hashmap" resultType="Integer">
		SELECT COUNT(*) AS CNT
		FROM SELL
	</select>
	
	<select id="getManagerCnt" parameterType="hashmap" resultType="Integer">
		SELECT COUNT(*) AS CNT
		FROM MANAGER
	</select>
	
</mapper>

 

sellList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table{
	border-collapse: collapse;
}

th, td {
	border: 1px solid #000;
	padding: 5px;
}

#pagingWrap span{
	cursor: pointer;
}

</style>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("tbody").on("click", "tr", function () {
		console.log($(this).attr("no"));
		$("#no").val($(this).attr("no"));
		
		$("#actionForm").attr("action","sellDetail");
		$("#actionForm").submit();
	})
	
	$("#insertBtn").on("click", function () {
		location.href = "sellInsert";
	});
	
	
	$("#pagingWrap").on("click", "span", function () {
		$("#page").val($(this).attr("page"));
		
		$("#actionForm").attr("action","sellList");
		$("#actionForm").submit();
	});
	
});

</script>
</head>
<body>
<form action="#" id="actionForm" method="post">
	<input type="hidden" id="no" name="no" /> 
	<input type="hidden" id="page" name="page" value="${page}" />  <!-- 상세보기 갈때 page 가져갈거임 -->
</form>
<input type="button" value="추가" id="insertBtn" />
<br />
<table>
	<thead>
		<tr>
			<th>판매번호</th>
			<th>품목</th>
			<th>수량</th>
			<th>일자</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach var="data" items="${list}">
			<tr no="${data.SELL_NO}">
				<td>${data.SELL_NO}</td>
				<td>${data.ITEM_NAME}</td>
				<td>${data.COUNT}</td>
				<td>${data.SELL_DT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<div id="pagingWrap">
<span page="1">처음</span>
<!-- 이전은 현재페이지에서 하나 전, 
지금 1페이지인지 아닌지 먼저 체크 따라서, 현재페이지 필요-->
<!-- 이전페이지 : 현제페이지가 1이면 1로 이동 아니면 현제페이지 -1 -->
<c:choose>
	<c:when test="${page eq 1}">
		<span page="1">이전</span>
	</c:when>
	<c:otherwise>
		<span page="${page - 1}">이전</span>
	</c:otherwise>
</c:choose>
<!-- 페이지들 -->
<c:forEach var="i" begin="${pd.startP}" end="${pd.endP}" step="1">
	<%-- 현재 페이지의 경우 별도 처리 --%>
	<c:choose>
		<c:when test="${i eq page}"> <%-- 현재페이지 --%>
			<span page="${i}"><b>${i}</b></span>
		</c:when>
		<c:otherwise> <%-- 다른페이지 --%>
			<span page="${i}">${i}</span>
		</c:otherwise>
	</c:choose>
</c:forEach>

<!-- 다음페이지 : 마지막에 도달했을때는 증가하지 않고, 다른 경우는 +1 -->
<c:choose>
	<c:when test="${page eq pd.maxP}">
		<span page="${pd.maxP}">다음</span>
	</c:when>
	<c:otherwise>
		<span page="${page + 1}">다음</span>
	</c:otherwise>
</c:choose>

<span page="${pd.maxP}">마지막</span>
</div>
</body>
</html>

sellDetail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" 
		src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	$("#listBtn").on("click", function() {
		$("#actionForm").attr("action","sellList"); 
		$("#actionForm").submit();
	});
	
	$("#deleteBtn").on("click", function () {
		if(confirm("삭제하시곘습니까?")){
			$("#actionForm").attr("action","sellRes"); 
			$("#actionForm").submit();
		}
	})
	
	$("#updateBtn").on("click", function () {
		$("#actionForm").attr("action","sellUpdate");
		$("#actionForm").submit();
	});
});

</script>
</head>
<body>
<!-- form action에서 #은 아무런 이동을 하지 않는다. -->
<form action="#" id="actionForm" method="post">
<!-- 상세보기에서는 삭제만 쓸거니 d를 박아줘도 됨, 수정이면 수정페이지로 이동할거니 -->
<!-- 이 페이지에서 수정도 같이하면 value에 값 비어두기 -->
	<input type="hidden" name="gbn" value="d" /> <!-- selRes는 gbn을 받게 되어있어서 값을 추가해줘야함 -->
	<input type="hidden" name="no" value="${data.SELL_NO}" /> <!-- 삭제하기위해  번호 보내주기 -->
	<input type="hidden" name="page" value="${param.page}" /> <!-- 전 화면에서 넘어온 페이지 정보 -->
</form>	
	판매번호: ${data.SELL_NO}<br/>
	품목: ${data.ITEM_NAME}<br/>
	수량: ${data.COUNT}<br/>
	일자: ${data.SELL_DT}<br/>
<input type="button" value="수정" id="updateBtn" />
<input type="button" value="삭제" id="deleteBtn" />
<input type="button" value="목록" id="listBtn" />
</body>
</html>

 

sellRes.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	
	// el tag를 script에서 사용시
	// 해당 위치에 값이 그대로 들어가기 때문에 보편적으로 ''를 달아서 문자열로 인식시킨 뒤 사용
	// ${res}해서  success가 들어올경우, success 이렇게되면 변수로 인식되서 "success" 이렇게 인식되게
	// "${res}"로 써줌
	switch("${res}"){
	case "success" : 
		if("${param.gbn}" == "u"){ // 수정이 성공했을 떄
			$("#goForm").submit();
		} else { // 등록, 삭제가 성공했을 떄
			location.href = "sellList" 
		}
		break;
	case "failed" : 
		alert("작업에 실패하였습니다.");
		history.back();
		break;
	case "error" : 
		alert("작업중 문제가 발생 하였습니다.");
		history.back();
		break;
	}
});
</script>
</head>
<body>
<form action="sellDetail" id="goForm" method="post">
	<input type="hidden" name="no" value="${param.no}" /> <!-- 전 화면에서 넘어오니까 param.no -->
	<input type="hidden" name="page" value="${param.page}" /> <!-- 전 화면에서 넘어온 페이지 정보 -->
</form>
</body>
</html>

 

sellUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	// 기존값으로 셀렉트박스 선택 내용 변경
	$("#itemName").val("${data.ITEM_NAME}");
	
	$("#listBtn").on("click", function () {
		history.back();
	});
	
	$("#updateBtn").on("click", function () {
		if($("#count").val() == ""){
			alert("수량을 입력하세요");
			$("#count").focus();
		} else if($("#count").val()*1 < 1){ // 문자열이기 때문에 *1 해줘야 숫자로 바뀜
			alert("수량은 1개 이상이어야 합니다");
			$("#count").focus();
		}
		else if($("#sellDt").val() == ""){
			alert("일자를 입력하세요");
			$("#sellDt").focus();
		} else {
			$("#actionForm").submit();
		}
	});
});

</script>
</head>
<body>
<!-- 번호는 시퀀스 쓸거기 때문에 받을 필요없음, 보여줄 필요 없음, 저장되야 글번호 보여지지 -->
<!-- select 전달하기 위해  name줘야함 -->
<!-- option value 지정해줘야함! -->
<form action="sellRes" id="actionForm" method="post">
<!-- gbn : 구분, 혹은 flag -->
<!-- 구분: i - insert, u - update, d - delete -->
<input type="hidden" name="gbn" value="u"/>
<input type="hidden" name="no" value="${data.SELL_NO}"/> <!-- 이 번호만 수정해라라는 조건 달기위해 필요 -->
<input type="hidden" name="page" value="${param.page}" /> <!-- 전 화면에서 넘어온 페이지 정보 -->
판매번호 : ${data.SELL_NO}<br/>
품목명
<select name="itemName" id="itemName">
	<option value="감자">감자</option>
	<option value="고구마">고구마</option>
	<option value="애호박">애호박</option>
	<option value="호박">호박</option>
	<option value="호박고구마">호박고구마</option>
</select>
<br />
수량 <input type="number" name="count" id="count" value="${data.COUNT}" />
<br />
일자 <input type="date" name="sellDt" id="sellDt" value="${data.SELL_DT}" />
<br />
</form>
<input type="button" value="수정" id="updateBtn">
<input type="button" value="뒤로가기" id="listBtn">
</body>
</html>

 

PagingService.java ( 강사님 샘플코드)

package com.spring.sample.common.service;

import java.util.HashMap;

import org.springframework.stereotype.Service;

import com.spring.sample.common.CommonProperties;

@Service
public class PagingService implements IPagingService {
	/*
	 * Paging
	 */
	// 테이블 시작row
	@Override
	public int getStartCount(int page) {
		int startCount = 0;
		// viewCount : 보여질 갯수
		int viewCount = CommonProperties.VIEWCOUNT;
		// page : 현재페이지
		startCount = (page - 1) * viewCount + 1;
		return startCount;
	}

	// 테이블 종료row
	@Override
	public int getEndCount(int page) {
		int endCount = 0;
		endCount = page * CommonProperties.VIEWCOUNT;
		return endCount;
	}

	// 페이징 최대 크기
	@Override
	public int getMaxPcount(int maxCount) {
		int maxPcount = 0;

		if (maxCount % CommonProperties.VIEWCOUNT > 0) {
			maxPcount = (maxCount / CommonProperties.VIEWCOUNT) + 1;
		} else {
			maxPcount = (maxCount / CommonProperties.VIEWCOUNT);
		}
		// 데이터가 0경일경우라도 페이지는 1
		if (maxCount == 0) {
			maxPcount = 1;
		}

		return maxPcount;
	}

	// 현재페이지 기준 시작페이지
	@Override
	public int getStartPcount(int page) {
		int startPcount = 0;

		if (page % CommonProperties.PAGECOUNT == 0) {
			startPcount = page - CommonProperties.PAGECOUNT + 1;
		} else {
			startPcount = ((page / CommonProperties.PAGECOUNT) * CommonProperties.PAGECOUNT) + 1;
		}

		return startPcount;
	}

	// 현재페이지 기준 종료페이지
	@Override
	public int getEndPcount(int page, int maxCount) {
		int endPcount = 0;
		int maxPcount = getMaxPcount(maxCount);

		// 시작페이지 가져와서 구했는데
		endPcount = getStartPcount(page) + CommonProperties.PAGECOUNT - 1;

		// 내가 구한값이 최대페이지보다 크면, 최대페이지로 변경
		if (endPcount >= maxPcount) {
			endPcount = maxPcount;
		}

		return endPcount;
	}

	// 빈형식으로 취득, 빈이 아니고 Map
	@Override
	public HashMap<String, Integer> getPagingData(int page, int maxCount) {
		HashMap<String, Integer> pd = new HashMap<String, Integer>();

		pd.put("start", getStartCount(page));
		pd.put("end", getEndCount(page));
		pd.put("maxP", getMaxPcount(maxCount));
		pd.put("startP", getStartPcount(page));
		pd.put("endP", getEndPcount(page, maxCount));

		return pd;
	}

	/*****************
	 * Custom Paging *
	 *****************/
	// 테이블 시작row
	@Override
	public int getStartCount(int page, int viewCnt) {
		int startCount = 0;
		startCount = (page - 1) * viewCnt + 1;
		return startCount;
	}

	// 테이블 종료row
	@Override
	public int getEndCount(int page, int viewCnt) {
		int endCount = 0;
		endCount = page * viewCnt;
		return endCount;
	}

	// 페이징 최대 크기
	@Override
	public int getMaxPcount(int maxCount, int viewCnt) {
		int maxPcount = 0;

		if (maxCount % viewCnt > 0) {
			maxPcount = (maxCount / viewCnt) + 1;
		} else {
			maxPcount = (maxCount / viewCnt);
		}

		if (maxCount == 0) {
			maxPcount = 1;
		}

		return maxPcount;
	}

	// 현재페이지 기준 시작페이지
	@Override
	public int getStartPcount(int page, int pageCnt) {
		int startPcount = 0;

		if (page % pageCnt == 0) {
			startPcount = page - pageCnt + 1;
		} else {
			startPcount = ((page / pageCnt) * pageCnt) + 1;
		}

		return startPcount;
	}

	// 현재페이지 기준 종료페이지
	@Override
	public int getEndPcount(int page, int maxCount, int viewCnt, int pageCnt) {
		int endPcount = 0;
		int maxPcount = getMaxPcount(maxCount, viewCnt);

		endPcount = getStartPcount(page, pageCnt) + pageCnt - 1;

		if (endPcount >= maxPcount) {
			endPcount = maxPcount;
		}

		return endPcount;
	}

	// 빈형식으로 취득
	@Override
	public HashMap<String, Integer> getPagingData(int page, int maxCount, int viewCnt, int pageCnt) {
		HashMap<String, Integer> pd = new HashMap<String, Integer>();

		pd.put("start", getStartCount(page, viewCnt));
		pd.put("end", getEndCount(page, viewCnt));
		pd.put("maxP", getMaxPcount(maxCount, viewCnt));
		pd.put("startP", getStartPcount(page, pageCnt));
		pd.put("endP", getEndPcount(page, maxCount, viewCnt, pageCnt));

		return pd;
	}
}

 

 

IPagingService.java

package com.spring.sample.common.service;

import java.util.HashMap;

public interface IPagingService {
	// 테이블 시작row
	public int getStartCount(int page);

	// 테이블 종료row
	public int getEndCount(int page);

	// 페이징 최대 크기
	public int getMaxPcount(int maxCount);

	// 현재페이지 기준 시작페이지
	public int getStartPcount(int page);

	// 현재페이지 기준 종료페이지
	public int getEndPcount(int page, int maxCount);

	// 빈형식으로 취득
	public HashMap<String, Integer> getPagingData(int page, int maxCount);

	/*****************
	 * Custom Paging *
	 ******************/
	// 테이블 시작row
	public int getStartCount(int page, int viewCnt);

	// 테이블 종료row
	public int getEndCount(int page, int viewCnt);

	// 페이징 최대 크기
	public int getMaxPcount(int maxCount, int viewCnt);

	// 현재페이지 기준 시작페이지
	public int getStartPcount(int page, int pageCnt);

	// 현재페이지 기준 종료페이지
	public int getEndPcount(int page, int maxCount, int viewCnt, int pageCnt);

	// 빈형식으로 취득
	public HashMap<String, Integer> getPagingData(int page, int maxCount, int viewCnt, int pageCnt);

}
728x90