[jQuery] Spring jqGrid

Posted by 신희준 on December 29, 2017

2017 - 12 - 30 (토)


jqGrid


  • jqgrid 사용 용도 : admin 을 좀더 쉽고 빠르게 제작하고자 하던 중, 지인의 추천으로 알게 되었고 서칭 해본 결과 다양한 예제와 용이성을 인지하고 해당 플러그인을 적용하고자 함.

  • jQuery ui download http://jqueryui.com/download/ 맨 아래에서 테마를 설정하고 다운로드 받는다.

  • jqGrid plugin download http://www.trirand.com/blog/?page_id=6 에서 jqGrid plugin 다운로드

  • 압축을 풀고 현재 사용하고 있는 프로젝트에 적용하고 임포트 해준다.

jqGrid

  • jsp
<html>
<%@ page language="java" contentType="text/html; charset=UTF-8"   
        pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>


<head>
<link rel="stylesheet" type="text/css" media="screen"
        href="../../../resources/jqGrid/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen"
        href="../../../resources/jqGrid/plugins/ui.multiselect.css" />



	<link rel="stylesheet" type="text/css" media="screen" href="../../../resources/jqueryUI/jquery-ui.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="../../../resources/jqGrid/css/ui.jqgrid.css" />

<script src="../../../resources/js/jquery-3.2.1.js"></script>
<script src="../../../resources/jqGrid/js/jquery.jqGrid.min.js"></script>
<script src="../../../resources/jqGrid/src/grid.common.js"></script>
<script src="../../../resources/jqGrid/src/grid.formedit.js"></script>
<script src="../../../resources/jqGrid/src/jqModal.js"></script>
<script src="../../../resources/jqGrid/src/jqDnR.js"></script>
<script src="../../../resources/jqueryUI/jquery-ui.js"></script>

<script src="../../../resources/jqGrid/src/i18n/grid.locale-kr.js"></script>
<script src = "../../../resources/js/userGrid.js"></script>

</head>
<html>
<body>
	<table id="list"></table>
	<div id="pager"></div>
</body>

</html>
  • userGrid.js
<script>
$(document).ready(function() {
	jqgridTable.init();
	jqgridTable.search();
	jqgridTable.navGrid();
})

var jqgridTable =
{
		init : function () {
			var cnames = ['ID', '이메일', '이름', '휴대폰번호', '직업' , '생년월일', '성별', '유입경로','회원 상태'],
				$jqGrid = $("#jqGrid");

			$jqGrid.jqGrid({
				url			:	"getUserList",
				datatype	:	"local",
				colNames	:	cnames,
				colModel	:	[
					{name	: 	"user_id" , index : "user_id", width : 50 },
					{name	: 	"user_email" , index : "user_email", width : 200

						,formatter : function(cellValue, options, rowObject){                    

	        	  			var resultStr = "";

	        	  			if(cellValue == "카카오 로그인 계정"){
	        	  				resultStr = "Kakao";        	  				
	        	  			}else if(cellValue== "네이버 로그인 계정"){
	        	  				resultStr = "naver";
	        	  			}else if(cellValue =="페이스북 로그인 계정"){
	        	  				resultStr = "facebook";
	        	  			}else if(cellValue == "구글 로그인 계정"){
	        	  				resultStr = "google";
	        	  			}else{
	        	  				resultStr = cellValue
	        	  			}

	        	  			return resultStr;
	        	  		}







					},
					{name	: 	"user_name" , index : "user_name", width : 100 },
					{name	: 	"user_phoneNumber" , index : "user_phoneNumber", width : 150 },
					{name	: 	"user_job" , index : "user_job", width : 100 },
					{name	: 	"user_birth" , index : "user_birth", width : 100 },
					{name	:	"user_sex"	, index : "user_sex"	, width : 100

						,formatter : function(cellValue, options, rowObject){                    

	        	  			var resultStr = "";

	        	  			if(cellValue == 1){
	        	  				resultStr = "남자";        	  				
	        	  			}else if(cellValue== 0){
	        	  				resultStr = "여자";
	        	  			}else{
	        	  				resultStr = cellValue;
	        	  			}

	        	  			return resultStr;
	        	  		}


					},
					{name	: 	"user_snsId" , index : "user_snsId", width : 150

					 	,formatter : function(cellValue, options, rowObject){                    
	        	  			if(cellValue !=null){
								var first = cellValue.charAt(0);

	        	  			}
	        	  			var resultStr = "";

	        	  			if(first == 'k'){
	        	  				resultStr = "Kakao 회원";        	  				
	        	  			}else if(first== 'n'){
	        	  				resultStr = "naver 회원";
	        	  			}else if(first =='f'){
	        	  				resultStr = "facebook 회원";
	        	  			}else if(first == 'g'){
	        	  				resultStr = "google 회원";
	        	  			}else{
	        	  				resultStr = "알몸 자체 회원"
	        	  			}

	        	  			return resultStr;
	        	  		}






					},
					{name	: 	"user_status" , index : "user_status", width : 100 }
				],
				height		: 480,
				rowNum		: 10,
				rowList		: [10,20,30],
				pager		: "#jqGridPager",
				rownumbers	: true,
				viewrecords : true,
				cellEdit	: true,
				cellsubmit	: "clientArray",
				caption		: "회원 리스트"
			})
		},

		search : function () {
			$("#jqGrid").setGridParam({
				datatype		: "json",
			}).trigger("reloadGrid");
		},

		navGrid : function() {
			$("#jqGrid").jqGrid('navGrid', '#jqGridPager',

				{
					edit:false ,add:false ,del:true ,search:true ,refresh:true
				},
				{
					// 삭제 옵셥
				},			
				{
					// 찾기 옵션				
				});
		}

}

</script>
  • JsonObj.java
package com.almom.domain;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonObj {

	private int page;
	private int records;
	private int total;
	private List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();

	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRecords() {
		return records;
	}
	public void setRecords(int records) {
		this.records = records;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public List<Map<String, Object>> getRows() {
		return rows;
	}
	public void setRows(List<Map<String, Object>> rows) {
		this.rows = rows;
	}
}

  • Controller
@RequestMapping("/getUserList")
	@ResponseBody
	public JsonObj getJqGridJson(
			@RequestParam(value="page", required=false, defaultValue="1") String page,
			@RequestParam(value="rows", required=false, defaultValue="") String rows)throws Exception{

		// dao에서 리스트 형식으로된 데이터를 DB에서 가져옴.			
		System.out.println(page);
		List<UserVO> list = service.getAllUser(page, rows);
		System.out.println(list);
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

		JsonObj totalCnt = service.getCount();

		HashMap<String, Object> tempMap = new HashMap<String, Object>();
		System.out.println(page);
		// list 형식으로 된 데이터의 크기를 구함.
		int size = list.size();
		System.out.println(size);


		for(int i=0; i<size; i++){

			tempMap.put("user_id"		, list.get(i).getUser_id());
			tempMap.put("user_email"	, list.get(i).getUser_email());
			tempMap.put("user_job"	, list.get(i).getUser_job());
			tempMap.put("user_phoneNumber"	, list.get(i).getUser_phoneNumber());

			tempMap.put("user_name"		, list.get(i).getUser_name());

			tempMap.put("user_birth"		, list.get(i).getUser_birth());
			tempMap.put("user_sex"		, list.get(i).getUser_sex());
			tempMap.put("user_snsId"	, list.get(i).getUser_snsId());
			tempMap.put("user_status", list.get(i).getUser_status());
			resultList.add(tempMap);

			tempMap = new HashMap<String, Object>();
		}

		JsonObj jsonObj = new JsonObj();
		//임시
		jsonObj.setRecords(totalCnt.getTotalCnt());
		jsonObj.setTotal(totalCnt.getTotalPage());
		jsonObj.setPage(page);
		jsonObj.setRows(resultList);
		return jsonObj;
	}
  • service

	@Override
	public List<UserVO> getAllUser(String page, String rows) throws Exception {
		// TODO Auto-generated method stub
		return dao.getAllUser(page, rows);
	}

	@Override
	public JsonObj getCount() throws Exception {
		// TODO Auto-generated method stub
		return dao.getCount();
	}
  • DAO
@Override
public List<UserVO> getAllUser(String page, String rows) throws Exception {
  // TODO Auto-generated method stub
  HashMap <String, Object> map = new HashMap<String,Object>();
  map.put("page", page);
  map.put("rows", rows);
  return sqlSession.selectList(namespace+".selectAllUser", map);
}


@Override
public JsonObj getCount() throws Exception {
  return sqlSession.selectOne(namespace+".getCount");
}
  • mapper
<select id = "selectAllUser" resultType = "UserVO">
select aa.*
from(select a.*,@rownum:=@rownum+1 as rnum, FLOOR((@rownum -1)/#{rows}+1) pageNumber
from( SELECT @rownum := 0 )b , (select * from USER order by user_id asc)a)aa
where aa.pageNumber = #{page} order by aa.rnum
<!-- select * from USER -->
</select>

<select id = "getCount" resultType="JsonObj">
select count(*) totalCnt, CEIL(count(*)/5) totalPage from USER;
</select>

Post Sample Image