728x90
반응형
[step1] 데이터베이스 생성

※ Mysql 클라이언트 툴은 HeidSQL 사용


[step2] java 라이브러리 추가

이클립스 다이나믹 웹프로젝트를 생성하고, WEB-INF/lib 아래 다음과 같이 라이브러리 추가
※ Mysql connector는 www.mysql.com 에서 다운로드
    gson라이브러리는 code.google.com/p/google-gson 에서 다운로드




[step3] javascript 라이브러리 추가

jgGrid를 사용하기 위해서는 jQuery, jQueryUI 라이브러리가 필요하다.
※ jQuery는 jquery.com 에서 다운로드
    jQueryUI는 jqueryui.com 에서 다운로드
    jgGrid는 www.trirand.com/blog 에서 다운로드
다운받은 jqGrid파일의 css, js, plugins폴더를 프로젝트에 복사하고, jquery와 jqueryui관련 라이브러리도 복사하자.


사용예)


[step4] domain class

데이터베이스의 user 테이블과 맵핑되는 클래스

  1. package jqgrid.domain;
  2.  
  3. public class User {
  4.     private int id;
  5.     private String name;
  6.     private String email;
  7.     private int age;
  8.    
  9.     public int getId() {
  10.         return id;
  11.     }
  12.     public void setId(int id) {
  13.         this.id = id;
  14.     }
  15.     public String getName() {
  16.         return name;
  17.     }
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.     public String getEmail() {
  22.         return email;
  23.     }
  24.     public void setEmail(String email) {
  25.         this.email = email;
  26.     }
  27.     public int getAge() {
  28.         return age;
  29.     }
  30.     public void setAge(int age) {
  31.         this.age = age;
  32.     }
  33. }

jqGrid와 통신하기 위한 json형식의 데이트를 담을 클래스. 필드명은 동일하게 하는것이 정신건강에 도움이 될거다.^^;

  1. package jqgrid.domain;
  2.  
  3. import java.util.List;
  4.  
  5. public class UserJson {
  6.     // 다음의 이름은 jqGrid에 정해진 이름이기에 jqGrid를 사용시 꼭 지켜야 한다.
  7.     private int total; // jqGrid에 표시할 전체 페이지 수
  8.     private int page; // 현재 페이지
  9.     private int records; // 전체 레코드(row)수
  10.     private List<User> rows; // 목록
  11.     public int getTotal() {
  12.         return total;
  13.     }
  14.     public void setTotal(int total) {
  15.         this.total = total;
  16.     }
  17.     public int getPage() {
  18.         return page;
  19.     }
  20.     public void setPage(int page) {
  21.         this.page = page;
  22.     }
  23.     public int getRecords() {
  24.         return records;
  25.     }
  26.     public void setRecords(int records) {
  27.         this.records = records;
  28.     }
  29.     public List<User> getRows() {
  30.         return rows;
  31.     }
  32.     public void setRows(List<User> rows) {
  33.         this.rows = rows;
  34.     }  
  35. }

 
[step5] 목록페이지. 요청(ajax) jsp페이지

  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5.     <meta charset="utf-8">
  6.     <title>User List</title>
  7.     <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.10.4.custom.css">
  8.     <link rel="stylesheet" type="text/css" href="css/ui.jqgrid.css">
  9.     <script type="text/javascript" src="js/jquery-1.10.2.js"></script>
  10.     <script type="text/javascript" src="js/i18n/grid.locale-kr.js"></script>
  11.     <script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
  12.    
  13.     <script type="text/javascript">
  14.         $(document).ready(function(){
  15.             $("#user_list").jqGrid({
  16.                 // ajax 요청주소
  17.                 url:"/UserListAction",
  18.                 // 요청방식
  19.                 mtype:"post",
  20.                 // 결과물 받을 데이터 타입
  21.                 datatype:"json",
  22.                 // 그리드 갭션
  23.                 caption:"User List",
  24.                 // 그리드 높이
  25.                 height:"auto",
  26.                 // 그리드(페이지)마다 보여줄 행의 수 -> 매개변수이름은 "rows"로 요청된다
  27.                 rowNum:10,
  28.                 // rowNum변경 옵션
  29.                 rowList:[10,15,20],
  30.                 // 컬럼명
  31.                 colNames:["id","name","email","age"],
  32.                 // 컬럼 데이터(추가, 삭제, 수정이 가능하게 하려면 autoincrement컬럼을 제외한 모든 컬럼을 editable:true로 지정)
  33.                 // edittyped은 text, password, ... input type명을 사용
  34.                 colModel:[
  35.                           {name:"id", index:"id", align:"center"},
  36.                           {name:"name", index:"name", align:"center", editable:true, edittype:"text"},
  37.                           {name:"email", index:"email", align:"center", editable:true, edittype:"text"},
  38.                           {name:"age", index:"age", align:"center", editable:true, edittype:"text"}
  39.                           ],
  40.                 // 네비게이션 도구를 보여줄 div요소
  41.                 pager:"#pager",
  42.                 autowidth:true,
  43.                 // 전체 레코드수, 현재레코드 등을 보여줄지 유무
  44.                 viewrecords:true,
  45.                 // 추가, 수정, 삭제 url
  46.                 editurl: "/UserEditAction"
  47.             });
  48.            
  49.             // 네비게시션 도구 설정
  50.             $("#user_list").jqGrid(
  51.                     "navGrid",
  52.                     "#pager",
  53.                     {search:false, edit:true, add:true, del:true},
  54.                     {closeAfterEdit: true, reloadAfterSubmit: true},
  55.                     {closeAfterAdd: true, reloadAfterSubmit: true},
  56.                     {reloadAfterSubmit: true}
  57.             );
  58.         });
  59.  
  60.     </script>
  61. </head>
  62. <body>
  63.     <table id="user_list"></table>
  64.     <div id="pager"></div>
  65. </body>
  66. </html>


 

[step6] 목록 요청 컨트롤러(서블릿 클래스)


  1. package jqgrid.contrller;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.List;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12.  
  13. import com.google.gson.Gson;
  14. import com.google.gson.GsonBuilder;
  15.  
  16. import jqgrid.dao.UserDao;
  17. import jqgrid.domain.User;
  18. import jqgrid.domain.UserJson;
  19.  
  20. @WebServlet("/UserListAction")
  21. public class UserListAction extends HttpServlet {
  22.     private static final long serialVersionUID = 1L;
  23.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  24.         int page = Integer.parseInt(request.getParameter("page"));
  25.         int perPageRow = Integer.parseInt(request.getParameter("rows"));
  26.        
  27.         UserDao dao = new UserDao();
  28.         List<User> list = dao.selectUsers(page, perPageRow);
  29.         int records = dao.getCountRow();
  30.         int total = (int)Math.ceil((double)records/(double)perPageRow);
  31.        
  32.         UserJson userJson = new UserJson();
  33.         userJson.setTotal(total);
  34.         userJson.setRecords(records);
  35.         userJson.setPage(page);
  36.         userJson.setRows(list);
  37.        
  38.         Gson gson = new GsonBuilder().create();
  39.         String json = gson.toJson(userJson);
  40.        
  41.         response.setContentType("application/json");
  42.         response.setCharacterEncoding("utf-8");
  43.        
  44.         PrintWriter out = response.getWriter();
  45.         out.write(json);
  46.         out.flush();
  47.         out.close();
  48.     }
  49.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  50.         doGet(request, response);
  51.     }
  52.  
  53. }


[step7] 입력/수정/삭제 컨트롤러(서블릿 클래스)


  1. package jqgrid.contrller;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. import jqgrid.dao.UserDao;
  12. import jqgrid.domain.User;
  13.  
  14. @WebServlet("/UserEditAction")
  15. public class UserEditAction extends HttpServlet {
  16.     private static final long serialVersionUID = 1L;
  17.    
  18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19.         String oper = request.getParameter("oper");
  20.         UserDao dao = new UserDao();
  21.         if(oper.equals("add")){
  22.             String name = request.getParameter("name");
  23.             String email = request.getParameter("email");
  24.             int age = Integer.parseInt(request.getParameter("age"));
  25.            
  26.             User user = new User();
  27.             user.setName(name);
  28.             user.setEmail(email);
  29.             user.setAge(age);
  30.             dao.insert(user);
  31.         }else if(oper.equals("edit")){
  32.             int id = Integer.parseInt(request.getParameter("id"));
  33.             String name = request.getParameter("name");
  34.             String email = request.getParameter("email");
  35.             int age = Integer.parseInt(request.getParameter("age"));
  36.            
  37.             User user = new User();
  38.             user.setId(id);
  39.             user.setName(name);
  40.             user.setEmail(email);
  41.             user.setAge(age);
  42.             dao.update(user);
  43.         }else if(oper.equals("del")){
  44.             int id = Integer.parseInt(request.getParameter("id"));
  45.             dao.deleteById(id);
  46.         }else{
  47.             System.out.println("잘못된 접근 입니다.");
  48.         }
  49.     }
  50.  
  51.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  52.         doGet(request, response);
  53.     }
  54.  
  55. }



[step8] DAO 클래스

  1. package jqgrid.dao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10.  
  11. import jqgrid.domain.User;
  12.  
  13. public class UserDao {
  14.     public void update(User user){
  15.         Connection conn = null;
  16.         PreparedStatement pstmt = null;
  17.         String sql = "update user set name=?,email=?,age=? where id=?";
  18.         try {
  19.             Class.forName("com.mysql.jdbc.Driver");
  20.             conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jsdb","root","java1234");
  21.             pstmt = conn.prepareStatement(sql);
  22.             pstmt.setString(1, user.getName());
  23.             pstmt.setString(2, user.getEmail());
  24.             pstmt.setInt(3, user.getAge());
  25.             pstmt.setInt(4, user.getId());
  26.             pstmt.executeUpdate();
  27.         } catch (ClassNotFoundException | SQLException e) {
  28.             // TODO Auto-generated catch block
  29.             e.printStackTrace();
  30.         }
  31.        
  32.     }
  33.    
  34.     public void insert(User user){
  35.         Connection conn = null;
  36.         PreparedStatement pstmt = null;
  37.         String sql = "insert into user(name,email,age) values(?,?,?)";
  38.         try {
  39.             Class.forName("com.mysql.jdbc.Driver");
  40.             conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jsdb","root","java1234");
  41.             pstmt = conn.prepareStatement(sql);
  42.             pstmt.setString(1, user.getName());
  43.             pstmt.setString(2, user.getEmail());
  44.             pstmt.setInt(3, user.getAge());
  45.             pstmt.executeUpdate();
  46.         } catch (ClassNotFoundException | SQLException e) {
  47.             e.printStackTrace();
  48.             if(instanceof ClassNotFoundException){
  49.                 System.out.println("드라이버 로딩 실패!");
  50.             }else if (instanceof SQLException){
  51.                 System.out.println("sql 에러!");
  52.             }
  53.         } finally {
  54.             try {
  55.                 pstmt.close();
  56.                 conn.close();
  57.             } catch (SQLException e) {
  58.                 // TODO Auto-generated catch block
  59.                 e.printStackTrace();
  60.             }
  61.         }
  62.     }
  63.    
  64.    
  65.     public void deleteById(int id) {
  66.         Connection conn = null;
  67.         PreparedStatement pstmt = null;
  68.         String sql = "delete from user where id=?";
  69.         try {
  70.             Class.forName("com.mysql.jdbc.Driver");
  71.             conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jsdb","root","java1234");
  72.             pstmt = conn.prepareStatement(sql);
  73.             pstmt.setInt(1, id);
  74.             pstmt.executeUpdate();
  75.         } catch (ClassNotFoundException | SQLException e) {
  76.             e.printStackTrace();
  77.             if(instanceof ClassNotFoundException){
  78.                 System.out.println("드라이버 로딩 실패!");
  79.             }else if (instanceof SQLException){
  80.                 System.out.println("sql 에러!");
  81.             }
  82.         } finally {
  83.             try {
  84.                 pstmt.close();
  85.                 conn.close();
  86.             } catch (SQLException e) {
  87.                 // TODO Auto-generated catch block
  88.                 e.printStackTrace();
  89.             }
  90.         }
  91.     }
  92.    
  93.    
  94.     // 전체 행의 수를 리턴하는 메서드
  95.     public int getCountRow() {
  96.        
  97.         Connection conn = null;
  98.         PreparedStatement pstmt = null;
  99.         ResultSet rs = null;
  100.         String sql="select count(*) from user";
  101.         try{
  102.             // DB 드라이버 로딩
  103.             Class.forName("com.mysql.jdbc.Driver");
  104.             // DB 접속
  105.             conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jsdb","root","java1234");
  106.             // 쿼리 명령어 설정, 보내기, 결과물 받기
  107.             pstmt = conn.prepareStatement(sql);
  108.             rs = pstmt.executeQuery();
  109.             // 결과물 편집, 리턴
  110.             if(rs.next()){
  111.                 return rs.getInt(1);
  112.             }
  113.         } catch(Exception e){
  114.             e.printStackTrace();
  115.         } finally {
  116.             // db관련  커넥션 해제
  117.         }
  118.         return 0;
  119.     }
  120.    
  121.     // 전체 행의 데이터 리스트를 리턴하는 메서드
  122.     public List<User> selectUsers(int page, int perPageRow) {
  123.         int beginRow = perPageRow * page - perPageRow;
  124.         List<User> list = new ArrayList<User>();
  125.         Connection conn = null;
  126.         PreparedStatement pstmt = null;
  127.         ResultSet rs = null;
  128.         String sql="select id,name,email,age from user order by id desc limit ?,?";
  129.         // DB 드라이버 로딩
  130.         try{
  131.             Class.forName("com.mysql.jdbc.Driver");
  132.             // DB 접속
  133.             conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jsdb","root","java1234");
  134.             // 쿼리 명령어 설정, 보내기, 결과물 받기
  135.             pstmt = conn.prepareStatement(sql);
  136.             pstmt.setInt(1, beginRow);
  137.             pstmt.setInt(2, perPageRow);
  138.             rs = pstmt.executeQuery();
  139.             // 결과물 편집, 리턴
  140.             while(rs.next()){
  141.                 User user = new User();
  142.                 user.setId(rs.getInt("id"));
  143.                 user.setName(rs.getString("name"));
  144.                 user.setEmail(rs.getString("email"));
  145.                 user.setAge(rs.getInt("age"));
  146.                 list.add(user);
  147.             }
  148.         } catch(Exception e){
  149.             e.printStackTrace();
  150.         } finally {
  151.             // db관련  커넥션 해제
  152.         }
  153.         return list;
  154.     }
  155. }


[실행화면]


리스트 




추가



수정



삭제




728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,