servlet code

servlet code

how to implement paging or pagination in java code using servlets.
View Answers

March 23, 2010 at 5:37 PM

Hi Friend,

Try the following code:

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PaginationInServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
PrintWriter out = response.getWriter();
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root";, "root");
ResultSet rs1 = null;
ResultSet rs2 = null;
PreparedStatement ps1=null;
PreparedStatement ps2=null;

int showRows=5;
int totalRecords=5;
int totalRows=nullIntconvert(request.getParameter("totalRows"));
int totalPages=nullIntconvert(request.getParameter("totalPages"));
int iPageNo=nullIntconvert(request.getParameter("iPageNo"));
int cPageNo=nullIntconvert(request.getParameter("cPageNo"));

int startResult=0;
int endResult=0;
if(iPageNo==0){
iPageNo=0;
}
else{
iPageNo=Math.abs((iPageNo-1)*showRows);
}
String query1="SELECT SQL_CALC_FOUND_ROWS * FROM student limit "+iPageNo+","+showRows+"";
ps1=conn.prepareStatement(query1);
rs1=ps1.executeQuery();
String query2="SELECT FOUND_ROWS() as cnt";
ps2=conn.prepareStatement(query2);
rs2=ps2.executeQuery();
if(rs2.next()) {
totalRows=rs2.getInt("cnt");
System.out.println(totalRows);
}
out.println("<html><h3>Pagination of JSP page</h3><body><form>");
out.println("<input type='hidden' name='iPageNo' value='<%=iPageNo%>'>");
out.println("<input type='hidden' name='cPageNo' value='<%=cPageNo%>'>");
out.println("<input type='hidden' name='showRows' value='<%=showRows%>'>");
out.println("<table width='100%' cellpadding='0' cellspacing='0' border='1' >");
out.println("<tr><td>Roll No</td><td>Name</td><td>Marks</td><td>Grade</td></tr>");
while(rs1.next()){
out.println("<tr><td>"+rs1.getInt("rollNo")+"</td><td>"+rs1.getString("name")+"</td><td>"+rs1.getInt("marks")+"</td><td>"+rs1.getString("grade")+"</td></tr>");
}
try{
if(totalRows<(iPageNo+showRows)) {
endResult=totalRows;
}
else{
endResult=(iPageNo+showRows);
}
startResult=(iPageNo+1);
totalPages=((int)(Math.ceil((double)totalRows/showRows)));
}
catch(Exception e){
e.printStackTrace();
}
out.println("<tr><td colspan='3'><div>");
int i=0;
int cPage=0;
if(totalRows!=0) {
cPage=((int)(Math.ceil((double)endResult/(totalRecords*showRows))));
int prePageNo=(cPage*totalRecords)-((totalRecords-1)+totalRecords);
if((cPage*totalRecords)-(totalRecords)>0){
out.println("<a href=PaginationInServlet?iPageNo="+prePageNo+"&cPageNo="+prePageNo+"'> << Previous</a>");
}
for(i=((cPage*totalRecords)-(totalRecords-1));i<=(cPage*totalRecords);i++){
if(i==((iPageNo/showRows)+1)){
out.println("<a href=PaginationInServlet?iPageNo="+i+"style=cursor:pointer;color: red><b>"+i+"</b></a>");
}
else if(i<=totalPages){
out.println("<a href=PaginationInServlet?iPageNo="+i+">"+i+"</a>");
}
}
if(totalPages>totalRecords && i<totalPages){
out.println("<a href=PaginationInServlet?iPageNo="+i+"&cPageNo="+i+"> >> Next</a>");
}
}
out.println("<b>Rows "+startResult+"-"+endResult+"Total Rows"+totalRows+"</b></div></td></tr></table></form></body></html>");

March 23, 2010 at 5:38 PM

continue..

try{
if(ps1!=null){
ps1.close();
}
if(rs1!=null){
rs1.close();
}

if(ps2!=null){
ps2.close();
}
if(rs2!=null){
rs2.close();
}
if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
catch(Exception ex){}
}
public int nullIntconvert(String str){
int num=0;
if(str==null) {
str="0";
}
else if((str.trim()).equals("null")) {
str="0";
}
else if(str.equals("")) {
str="0";
}
try{
num=Integer.parseInt(str);
}
catch(Exception e) { }
return num;
}
}

For the above code, we have used following database table:

CREATE TABLE `student` (
`rollNo` bigint(40) NOT NULL auto_increment,
`name` varchar(40) default NULL,
`marks` varchar(40) default NULL,
`grade` varchar(40) default NULL,
PRIMARY KEY (`rollNo`)
)

Thanks









Related Tutorials/Questions & Answers:
servlet code
servlet code  how to implement insert update n delete in one servlet in net beans   If you want to perform insert, update and delete functions in the same servlet, then please visit the following links: http
servlet code - JSP-Servlet
servlet code  Create a servlet to develop a login application with javascript clientside validations and serverside validations
Advertisements
servlet code - JSP-Servlet
servlet code  how to implement paging or pagination in java code using servlets.  Hi Friend, Try the following code: import java.io.... code, we have used following database table: CREATE TABLE `student
Searching for Code - JSP-Servlet
JSP, Servlet Searching for Code  Hi, i am looking for a jsp servlet code examples for the search function in my application.Thanks
code - Servlet Interview Questions
by the servlet container. The status code of the response always should...code  servlet service method along with an example code  Hi Friend, Servlet service() method: Once the servlet starts getting
atm code in servlet& jsp
atm code in servlet& jsp  pls send me the code of ATM project in servlet jsp . my requirements are first of all an user login window open then balance enquiry, withdraw of money, money transfer, then log out. pls send as early
servlet code to update password?
servlet code to update password?  Create a servlet page which helps the user to update his password. The user should give the username,old password... users.then Store it into a table. please tell me the code for the above question
code required in servlet
code required in servlet  hello... you provided me the answer with javascript.. i want to check which button is clicked in the servlet.. i have only 1 servlet an in that separate codes for different button clicks.. can u plzzz
servlet code problem - JSP-Servlet
servlet code problem  This is my JSP code index.jsp Sync... here!!!..., i want to pass the texbox value and file to servlet im stuck with this error plzz help me..., in servlet if i use request.getParameter() its
jsp code - JSP-Servlet
jsp code  Can anyone help me in writing jsp/servlet code to retrieve files and display in the browser from a given directory.  Hi Friend, Try the following code: Thanks
Encryption code - JSP-Servlet
Encryption code  Iam developing a web security application for that reason i need a code of encryption in servlet. Can u please send it to me.Its very urgent Because my project delivery date is very near
servlet code problem - JSP-Servlet
servlet code problem  This is my JSP code index.jsp Sync Data Sync Data Please use the following input box to upload file or enter... to servlet im stuck with this error plzz help me..., thanks in advance....  
Help in completing Servlet code!
Help in completing Servlet code!  Complete the following Servlet codes to store the information read from the input form to session object. public... String comment = req.getParameter(?commentText?); //Complete the code to store
code for JSP and Servlet - JSP-Servlet
code for JSP and Servlet  i have to create a jsp page that contains username and password, so how to code servlet according to it?  Hi sushil, package javacode; import java.io.*; import javax.servlet.*; import
servlet code - Applet
servlet code  how to communicate between applet and servlet  Hi Friend, We are providing you the code that will display the message sent from the servlet to applet. Here is the code of 'ServletExample.java
Code - JSP-Servlet
Code  Using servlet,JSP,JDBC and XML create a Web application for a courrier company to provide online help in tracking the delivery status of items
java servlet code - Servlet Interview Questions
java servlet code  iam doing a project in java, preparation of on line examination in that how to prepare a question paper using servlet code
code - JSP-Servlet
; use some server side script like servlet or jsp, call these when user click
download code using servlet - Servlet Interview Questions
download code using servlet  How to download a file from web to our system using Servlet
code - Servlet Interview Questions
code  code for matrimoney site using servlets
source code - JSP-Servlet
source code for webcam chat application  I want source code for this webcam chat application. I like the concept of XAWARE ORG regarding web cam chat. So that i want the code through this XAWARE only.pls send the code as soon
java code - JSP-Servlet
java code  Code to send SMS through mobile to a web application
jsp code - JSP-Servlet
jsp code  I need code for bar charts using jsp. I searched some code but they are contain some of their own packages. Please give me asimple code... friend, Code to solve the problem : Thanks
program code - JSP-Servlet
program code  what is the program code for LOGINFORM USING SERVLETS? RESPOND SOON
program code - JSP-Servlet
program code  what is the program code for LOGINFORM USING SERVLETS? RESPOND SOON
jsp code - JSP-Servlet
jsp code  sample code for change password example Old Password: new Password: confirm Password
jsp code - JSP-Servlet
jsp code  sample code to create hyperlink within hyperlink example: reservation: train: A/C department non A/c Department
Code Works - JSP-Servlet
Code Works  Hi The code provided is working fine along with the pagination . i edited the queries and that makes difference.. here is the code. Thank you Regards Eswaramoorthy Pagination of JSP page
code - JSP-Servlet
code  hi sir my question is i have created a html ang jsp code.... how to write the code to accept an existing id and password.  Hi Friend, Try the following code: 1)login.html: Login
code for this problem - JSP-Servlet
code for this problem   i have buttom submit .It is working with single click.Suppose if i am At the same time clicking(parallel) twise second request will be stoped until process the proces first requst and terminate
source code - JSP-Servlet
source code  please i want source code for online examination project (web technologies)  Hi Friend, Send some details of your project. Thanks
code error - JSP-Servlet
code error  hii this program is not working becoz when the mouse... complaint   Hi friend, Do some changes in your code to solve the problem. 1)In "describe()" function write code "return true"; 2
jsp code - JSP-Servlet
jsp code  in my table there are 3 fields named orderid ,itemname, itemqty. i want code that fetch orderid in dropdown... on select dropdown get table of item details of that orderid... there are multiple items at one orderid
jsp code - JSP-Servlet
jsp code   the value did not passed from script and not inserted in to database in the code u given . var numberOfClicks = 0; function hello(){ numberOfClicks++; alert( numberOfClicks ); document.form1.text.value
JSP code - JSP-Servlet
. thanking u......... This is what my code is. Jam Name...;   Hi Friend, Try the following code: Jam Name
source code - JSP-Servlet
source code  i need source code for client server application in jsp to access multiple clients   Hi Friend, Please visit the following link: http://www.roseindia.net/jsp/ Here you will get lot of examples
jsp code - JSP-Servlet
jsp code  how to count no of clicks made on a link and save it on database( using jsp)  Hi Friend, Try the following code: 1)click.jsp var numberOfClicks = 0; function hello(){ numberOfClicks
code - JSP-Servlet
code  hi can any one tell me how to create a menu which includes 5 fields using jsp,it's urgent  Hi friend, Plz give details with full source code where you having the problem. Thanks
code in javscript - JSP-Servlet
code in javscript  hi, deepak i need a code for checkin a sting... button   Hi friend, Code to Javascript Pallindrome Checker... for giving Answer Try this code String comparisons
jsp code - JSP-Servlet
jsp code  in a jsp a table is existed ,in table each row contain one checkbox and name and desription how to delete specific rows in a table .  Hi Friend, Try the following code: 1)form.jsp: Name
jsp code - JSP-Servlet
jsp code  how to write a code in jsp with out using servelts finding sum and avg of 40 numbers  Hi Friend, Try the following code: Thanks  Hi Friend, Do one change in the provided code.As we
jsp code - JSP-Servlet
statement? pls provide code how to get first selected drop down list value..., Try the following code: function city(){ var cid...; For the above code, we have created following database tables
code - JSP-Servlet
code  how to retrieve database value in array  Hi friend, Code to help in solving the problem : import java.sql.*; import... code does not execute."); } } catch (Exception e
source code - JSP-Servlet
source code  i want source code for my project online examination it includes two modules user and administrator so if user want to write exam first he register his details and then select the topics on which he want to write
source code - JSP-Servlet
source code  i want source code for my project online examination it includes two modules user and administrator so if user want to write exam first he register his details and then select the topics on which he want to write
jsp code - JSP-Servlet
jsp code  i want to add below code data in mysql database using jsp... using below code we got data in text box i want to add multiple data in database... Add/Remove dynamic rows in HTML table
source code - JSP-Servlet
source code  I want source code for Online shopping Cart. Application Overview The objective of the Shopping Cart is to provide an abstract view... Rakesh, I am sending a link where u will found complete source code
JSP code - JSP-Servlet
JSP code  hello,i working in project with JSP technology,i have one page Login.html and on there two options NewUser and Recoverpassword..can u tell me how to link these pages with each other using JSP..and how to write the code
jsp code - JSP-Servlet
will be allotted to six days. pls send me code for this pls thankyou
JSP Code - JSP-Servlet
Rai.  Hi Friend, Try the following code: Pagination... For the above code,we have created a table 'student'. CREATE TABLE `student

Ads