Membuat Paging pada JSP
Hm…, lama nih ga nulis artikel tentang JSP, habis, nasib ngurusin PHP mulu,
, he..he… Di sini saya memodifikasi kelas pagination punya CodeIgniter (PHP), cuma copy logika nya aja, karena pagination nya emang udah bagus
(bilang aja ga bisa buat sendiri, xi..xi…xi…).
Hal pertama yang harus ditentukan adalah, apa yang akan kita list dan kita paging. Saya di sini akan memberi contoh tentang paging menggunakan PostgreSQL, dengan table orang dengan field2 nya id, nama, alamat, simple kan ? ![]()
OK, sekarang kita siapkan modelnya :
1. Kelas Koneksi
package beanpackage;
import java.sql.*;
/**
*
* @author samsonasik
*/
public class Koneksi {
private Connection con=null;
private Statement st=null;
private ResultSet rs=null;
public Koneksi()throws SQLException,ClassNotFoundException {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ikhsandb","ikhsan","123456");
st = con.createStatement();
}
public void seleksi(String s) throws SQLException{
rs = st.executeQuery(s);
}
public boolean getNext() throws SQLException{
return rs.next();
}
public String getText(String t) throws SQLException{
return rs.getString(t);
}
public int getInt(String t) throws Exception {
return rs.getInt(t);
}
}
2. Kelas Pagination (library pagination nya )
package beanpackage;
/**
*
* @author samsonasik
*/
//dimodifikasi dari kelas paginationnya codeIgniter
public class Pagination {
public int totalrows = 0;
public int numlink = 2;
public int curpage = 0;
public int perpage = 2;
public String firstlink = "First";
public String nextlink = "Next";
public String prevlink = "Previous";
public String lastlink = "Last";
public String createlinks(int halaman) {
if ( (this.totalrows==0) || (this.perpage==0)) {
return "";
}
int numpage = this.totalrows / this.perpage ;
int sisa = this.totalrows % this.perpage;
if (sisa > 0 ){
numpage = numpage + 1;
}
if (numpage==1) {
return "";
}
try {
this.curpage = halaman;
} catch (Exception e) {
this.curpage = 1;
}
try {
this.curpage = (int) this.curpage;
} catch (Exception e) {
this.curpage = 1;
}
if (this.curpage > this.totalrows)
{
this.curpage = (numpage -1 ) * this.perpage ;
}
if (this.curpage < 1 ) {
this.curpage = 1;
}
int uri_page_number = this.curpage ;
int start = ((this.curpage - this.numlink) > 0 ) ? this.curpage - (this.numlink -1) : 1;
int end = ((this.curpage + this.numlink < numpage)) ? this.curpage + this.numlink : numpage;
//inisialisasi ...
String theoutput = "";
//Render first link
if (this.curpage > (this.numlink +1))
{
if (this.curpage <= numpage) {
theoutput +="<a href=\"?page=1\">"+this.firstlink+"</a>nbsp;";
} else {
theoutput +="";
}
}
//Render Previous Link
if (this.curpage !=1) {
if (this.curpage <= numpage) {
theoutput +="<a href=\"?page="+(this.curpage-1)+"\">"+this.prevlink+"</a>nbsp;";
} else {
theoutput +="";
}
}
//render digit link
for (int loop = start -1; loop<end;loop++) {
if (this.curpage <= numpage) {
if (this.curpage == (loop+1)) {
theoutput += loop+1+"nbsp;";
} else {
theoutput += "<a href=\"?page="+(loop+1)+"\">"+(loop+1)+"</a>nbsp;";
}
} else {
theoutput +="";
}
}
//render the next link
if (this.curpage < numpage) {
theoutput += "<a href=\"?page="+(this.curpage+1)+"\">"+this.nextlink+"</a>nbsp;";
} else {
theoutput +="";
}
//render the last link
if ((this.curpage + this.numlink)<numpage) {
theoutput += "<a href=\"?page="+numpage+"\">"+this.lastlink+"</a>";
}
return theoutput;
}
}
3. Kelas Orang (Model dari table orang)
package beanpackage;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author samsonasik
*/
public class Orang {
private int id;
private String nama, alamat;
public Orang(){ }
public Orang(int id, String n,String a){
this.id = id;
this.nama = n;
this.alamat = a;
}
public void setNama(String n)
{
this.nama = n;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setAlamat(String al)
{
this.alamat = al;
}
public String getNama()
{
return nama;
}
public String getAlamat()
{
return alamat;
}
//seleksi offset limit
public ArrayList<Orang> seleksi(int offset, int limit) throws SQLException, ClassNotFoundException
{
ArrayList<Orang> temp = new ArrayList<Orang>();
try {
Koneksi kon = new Koneksi();
kon.seleksi("select * from orang offset '"+offset+"' limit '"+limit+"'");
while (kon.getNext()) {
temp.add(new Orang(kon.getInt("id"), kon.getText("nama"), kon.getText("alamat")));
}
} catch(Exception e) {}
return temp;
}
public int getJml() {
int jml = 0;
try {
Koneksi kon = new Koneksi();
kon.seleksi("select count(*) as jml from orang");
if (kon.getNext()) jml = kon.getInt("jml");
} catch (Exception e){}
return jml;
}
}
Nah, kalau sudah tuh, kita buat servletnya, ga akan saya tulis lengkap
deh kaya’nya, cuma isi method nya aja yang memanggil
model-model yang ada.
.............
ArrayList<Orang> temp = new ArrayList<Orang>();
PrintWriter out = response.getWriter();
try {
Orang org = new Orang();
int page = 0;
try {
page = Integer.parseInt(request.getParameter("page"));
} catch (Exception e) {
page = 1;
}
Pagination pgn = new Pagination();
pgn.totalrows = org.getJml();
temp = org.seleksi(page*pgn.perpage-pgn.perpage,pgn.perpage);
request.setAttribute("temp", temp);
request.setAttribute("perpage",pgn.perpage);
request.setAttribute("paging", pgn.createlinks(page));
} catch(Exception e) {
out.print("terjadi kesalahan koneksi");
out.close();
}
request.getRequestDispatcher("/testlist.jsp").forward(request, response);
................
Jangan lupa konfigurasi web.xml nya, udah bisa kan ?
Terakhir adalah view :
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
${paging}
<table border="1" cellpadding="1" cellspacing="1">
<tr>
<td>No</td>
<td>Id</td>
<td>Nama</td>
<td>Alamat</td>
</tr>
<c:catch var ="catchException">
<c:if test="${param.page eq null || param.page eq '1'}">
<c:set var="no" value="0"/>
</c:if>
<c:if test="${param.page gt '1'}">
<c:set var="no" value="${param.page * perpage - perpage }"/>
</c:if>
</c:catch>
<c:if test="${catchException !=null}">
<c:set var="no" value="0"/>
</c:if>
<c:forEach var="testlist" items="${temp}">
<c:set var="no" value="${no +1}"/>
<tr>
<td>${no} .</td>
<td>${testlist.id}</td>
<td>${testlist.nama}</td>
<td>${testlist.alamat}</td>
</tr>
</c:forEach></table>
${paging}
Simple kan ? selamat mencoba
Boz,,,
Gmna kbrnya?
Lama gk ktemu,,
Eh ngomong2 JSP punya driver database apa aja yang support buat JSP?
Aq lgi cari driver SQL Anywhere buat JSP punya gk?
mas cahyo bisa cari sendiri di Google
Mas kl bikin paging untuk link yang larinya Ke body index gmna? mohon bantuannya
ada beberapa cara , diantaranya :
1. membuat frame, cara ini adalah cara termudah, yaitu membuat frame kosong dengan source web kita, misal :
<frameset framespacing=”0″ frameborder=”0″ rows=”100%”>
<frame marginheight=”0″ marginwidth=”0″ frameborder=”0″ src=”http://samsonasik.wordpress.com”>
</frame>
</frameset>
2. Dengan menampung data kiriman ke sesi, tapi ini makan resource besar di memory :
misal, diarahkan ke tampungsesi.php?edit=true&id=1
nah, sesi menerima parameter tersebut, dan redirect ke index lagi, otomatis kondisi sekarang adalah halaman edit.
mantaP>….
sangat berManfaat…
kebeTulaN saYa lagi ngeMIgrasiin aplikasi pake codeIgniter ke java…
dan sangat kebetulan ini paging nya..ni..
maksIH OM…
mas, kalau di php untuk update beberapa record kan pakai sintaks ini ya
$id = $_POST[id];
$jml_data = count($id);
$jumlah = $_POST[jml]; // quantity
for ($i=1; $i <= $jml_data; $i++){
mysql_query("UPDATE orders_temp SET jumlah = '".$jumlah[$i]."'
WHERE id_orders_temp = '".$id[$i]."'");
sehingga kita bisa mengupdate beberapa baris sekaligus,
tapi untuk jsp bagaimana ya mas?
secara konsep ya sama aja, tinggal executeUpdate nya diulang2
, dilooping sejumlah record yang ada / yang akan diupdate
mas mau nanya donk kan saya pernah buat sistem buat ktp gt tp di web base agak kesulitan nieh mas karna pke jsp kan sistemnya udah jadi berhubung kebiasaan gunain php di kirain klo di pindah ke tempat lain (komputer lain) itu bs jalan hanya dgn mengunakan xampp yang ada apacetomcatnya gt mas ternyata ga mau jalan tuh btw saya pke aplikasi netbeen buat bikinya mas mohon pencerahanya mas
aplikasi sudah jadi ? atau baru mau buat ? ya tinggal dipindahin aja kan coding-nya, secara konsep sama.
makasih gaaaaan ^^
saya dah eneg sama framework2 Java : struts, tapestry, webwork
setelah buat aplikasi di CI 2x, wah, amaze ma mudahnya
ni lagi koding JSP, tapi distruktur spt CI
harapannya mudah2an bs nulung, at least, saya sendiri ^^
library Vagi..eh, Pagination nya ^^, saya Kopi yaks
jazaaaakallah
thx for share…
bwt kode otomatis di jsp gmn ea???
mohon bntuanya donk…
bingung nieh
otomatis gmn ? scaffolding ? ya tinggal dibuat aja toh, heuheu