jmaki+jpa+glassfishv3(eclipselink)+pagination 2

0

Written on 오전 7:45 by 강여사(J.Y.Kang)

예전 게시물 올렸을 때에는 버튼을 이용하여 각각 페이지 앞뒤로의 이동을 올렸었는데,
이번에는 좀전의 yahoo의 pagination을 이용하여 페이징을 해보고자 한다.

일단 데이터베이스에서의 작업을 위해 JPA 관련 작업을 시작.

프로젝트에서 오른쪽 마우스 new - Entity Classes from Database 선택 (만약 이 메뉴가 안보이면 option (팝업창)- persistence 카테고리에 있다)

Data Source 는 jdbc/sample


선택할 테이블은 customer 를 add
다음
패키지 이름은 data


그리고 persistence unit 를 새로 작성해야 하므로 아래 버튼(create persistence unit) 클릭


이름 : 프로젝트이름+PU
프로바이더: eclipselink(v3 기본값)
나머지는 옵션대로
create
확인후 다음

그럼 자동생성된 customer.java 에 json 객체화 작업을 추가
다음내용 코드 작성
----------------------------
public JSONObject toJSON() throws Exception {
JSONObject thisJSON = new JSONObject();
thisJSON.put("name", this.getName());
thisJSON.put("city", this.getCity());
thisJSON.put("state", this.getState());
thisJSON.put("zip", this.getZip());
return thisJSON;
}
----------------------------
임포트 문제 해결
마우스오른쪽 클릭-fix import
원래 여기 이 대목에서 2개의 클래스 (하나는 서블릿, 다른 하나는 일반 자바 클래스) 를 작성해야 하는데 예전에 했던 대목인지라 작성 상세 내용은 skip 하고 이전 프로젝트의 파일 복사로 진행 (다만 파일만 복사되는 상태이므로 나머지 설정사항들은 수동으로 해줘야 함)

예전 프로젝트의 service 패키지 전체를 복사해서 source package 아래 붙여넣기
참고 1 ( Catalog.java)
-----------------------------

/*
* To change this template, choose Tools Templates
* and open the template in the editor.
*/
package service;

import data.Customer;

import java.util.List;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.json.JSONArray;
import org.json.JSONObject;

/**
*
* @author carol mcdonald
*/
public class Catalog {

/** Creates a new instance of Catalog */
public Catalog() {
}
private Customer customer;

private EntityManager getEntityManager() throws Exception {
EntityManager em = (EntityManager) (new InitialContext()).lookup("java:comp/env/persistence/em");
return em;
}
private int batchSize = 5;
private int firstItem = 0;

public Customer getCustomer() {
return customer;
}

public void setCustomer(Customer customer) {
this.customer = customer;
}

public List getCustomers() throws Exception {
EntityManager em = getEntityManager();

Query q = em.createQuery("select object(o) from Customer as o");
//////kj 2009-10-01
int count = ((Long) em.createQuery("select count(o) from Customer as o").getSingleResult()).intValue();
q.setMaxResults(count);
// q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
return q.getResultList();
}

public JSONArray getNextCustomersJSON(int page) throws Exception {
if (page < firstitem =" 0;" firstitem =" page" customersjson =" new"> customers = getCustomers();
for (Customer customerData : customers) {
JSONObject customerJSON = customerData.toJSON();
customersJSON.put(customerJSON);
}
return customersJSON;
}

public Customer findCustomer(String id) throws Exception {
EntityManager em = getEntityManager();
try {
Customer o = (Customer) em.find(Customer.class, id);
return o;
} finally {
em.close();
}
}

public int getItemCount() throws Exception {
EntityManager em = getEntityManager();
try {
int count = ((Long) em.createQuery("select count(o) from Customer as o").getSingleResult()).intValue();
System.out.println("size:"+ count);
return count;
} finally {
em.close();
}
}

public int getFirstItem() {
return firstItem;
}

public int getLastItem() throws Exception {
int size = getItemCount();
return firstItem + batchSize > size ? size : firstItem + batchSize;
}

public int getBatchSize() {
return batchSize;
}
}


------------------------------
참고2 CatalogServlet.java
------------------------------
/*
* To change this template, choose Tools Templates
* and open the template in the editor.
*/
package service;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;

/**
*
* @author carol mcdonald
*/
public class CatalogServlet extends HttpServlet {

/**
* Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

int page = 0;
int rowsonly = 0;
Catalog catalog = new Catalog();
response.setContentType("text/plain;charset=UTF-8");

String temp = request.getParameter("page");
if (temp != null) {
page = Integer.parseInt(temp);
}
temp = request.getParameter("rowsonly");
if (temp != null) {
rowsonly = Integer.parseInt(temp);
}

try {

// JSONArray array = catalog.getNextCustomersJSON(page);
JSONArray array = catalog.getCustomersJSON();
if (rowsonly == 1) {
out.println(array.toString());
} else {
out.println("{columns : [" +
"{ label : 'Company', id : 'name'}," +
"{ label :'City', id : 'city'}," +
"{ label : 'State', id : 'state'}," +
"{ label : 'Zip', id : 'zip'}" +
"],");
out.println("rows: ");
out.println(array.toString());
out.println(" }");
}
} catch (Exception e) {
out.println(e);
} finally {
out.close();
}
}

//
/**
* Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}//

}
-----------------------------
(이전프로젝트에서 service 패키지 복사)
(지금프로젝트의 source package 에 붙여넣기)
그런 다음 이 중 CatalogServlet 은 서블릿이므로 web.xml 을 열어 수동으로 편집
web.xml 을 연후 Servlet 탭을 클릭
오른쪽 아래 Add Servlet Element 버튼 클릭
팝업창에서 이름은 CatalogServlet 으로
클래스는 찾기에서 service - CatalogServlet 찾아서 선택
아래 URL Pattern 에는 /CatalogServlet (그림 참고)
OK
index.jsp 에서 yahoo datatable 위젯 수정

(내용은 그림 참고)source package 의 CatalogServlet.java 에서 다음 수정

47라인
// JSONArray array = catalog.getNextCustomersJSON(page);
JSONArray array = catalog.getCustomersJSON();
Catalog.java 의 50라인 수정

int count = ((Long) em.createQuery("select count(o) from Customer as o").getSingleResult()).intValue();
q.setMaxResults(count);
// q.setMaxResults(batchSize);



web.xml 에 persistence 관련 추가

그림 참고

프로젝트 실행(run)

If you enjoyed this post Subscribe to our feed


No Comment

댓글 쓰기