Pagination using java - mysql

This is code for pagination in java i tried to implement. i have 20 records with columns emp_id and emp_name which i want to display using 4 pages i.e (5 records per page) using my sql workbench but code is not executing indicating many errors plz solve this
<%# page import ="java.io.*, java.sql.*, java.util.*" %>
<%!
Connection con = null;
ResultSet rs = null;
ResultSet rs1 = null;
int start_row_count, end_row_count, no_of_page, pages;
String page_name="paging.jsp";
%>
<html>
<head>
</head>
<body>
<table border="1" style="width:80%;">
<%
try
{
String pages1=request.getParameter("pages");
if(pages1!=null)
{
pages=Integer.parseInt(pages1);
}
if(pages==0)
pages=1;
if(pages==1)
{
start_row_count=1;
}
else
{
start_row_count=(pages-1)*5;
}
end_row_count=pages*5;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shelu", "root", "mysql");
String sql="select * from emp limit" + start_row_count +"5";
Statement st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next())
{%>
<tr>
<td><%=rs.getInt("emp_id")%></td>
<td><%=rs.getString("emp_name")%></td>
</tr>
<%
}
rs.close();
rs1=st.executeQuery("select count(*) from emp");
int total=0;
if(rs1.next())
total=rs1.getInt(1);
if(total%5==0)
no_of_page=total/5;
else
no_of_page=total/5+1;
%>
<tr>
<%
for(int i=1;i<=no_of_page;i++)
{
out.println("<a href='"+page_name+"?pages="+i+"'>"+i+"</a>");
}
%>
</tr>
<%
} catch(Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>

If you are looking at server side pagination, Displaytag is what you should be using.

Related

Display column names and records from table in a JSP Page

I know this question may be asked in many different ways, but i am kind of stuck in the code where i cannot display the column names along with the records. I am getting records displayed but not the column names. Any help appreciated, my code so far is below -
resultSet = statement.executeQuery(sql);
ResultSetMetaData metadata = resultSet.getMetaData();
int count = metadata.getColumnCount();
while(resultSet.next())
{
%>
<tr>
<%
ArrayList<String> columns = new ArrayList<>();
for(int i=1; i<=count;i++)
{
String name = metadata.getColumnName(i);
columns.add(name);
%>
<td>
<%= resultSet.getString(i)%>
</td>
<%
}
%>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
Modified code with #swati suggestion. I have added table before try and included the array and for loop in the try. This is throwing syntax and constructor error
<table style="width:100%;text-align:left;border-collapse:collapse;background-color:gold;" border="2" bordercolor="Blue">
<tr style="background-color:yellowgreen;color:white;">
</tr>
<%
try{
Connection connection = null;
ResultSet resultSet = null;
int counter=1;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#DEV:1521:DEV","DEV","DEV");
Statement statement = connection.createStatement();
String sql = ("SELECT * FROM tblnm");
resultSet = statement.executeQuery(sql);
ResultSetMetaData metadata = resultSet.getMetaData();
int count = metadata.getColumnCount();
ArrayList<String> columns = new ArrayList<>();
<table>
<tr> //row for displaying column names
<%for(int i=1; i<=count;i++)
{
String name = metadata.getColumnName(i);
columns.add(name);
%>
<td><%=name%></td> //displaying column name
<% } %>
</tr>
<%
while(resultSet.next())
{
%>
<tr>
//looping through names
<% for(int i=1;i<columns.size();i++) { %>
//get values from particular columns
<td><%= resultSet.getString(columns.get(i))%></td>
<% } %> //closing for loop
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
Your table structure is wrong .You need to display all column name first then all rows under columns currently your code doesn't show any column name because you are not writng any code to do the same.Instead your code should look like below :
resultSet = statement.executeQuery(sql);
ResultSetMetaData metadata = resultSet.getMetaData();
int count = metadata.getColumnCount();
ArrayList<String> columns = new ArrayList<>();
<table>
<tr> //row for displaying column names
<%for(int i=1; i<=count;i++)
{
String name = metadata.getColumnName(i);
columns.add(name);
%>
<td><%=name%></td> //displaying column name
<% } %>
</tr>
<%
while(resultSet.next())
{
%>
<tr>
//looping through names
<% for(int i=1;i<columns.size();i++) { %>
//get values from particular columns
<td><%= resultSet.getString(columns.get(i))%></td>
<% } %> //closing for loop
</tr>
<%
} //closing while loop
//other codes put here
%>
</table>

AJAX JSP displaying output data in a table

trying to display data from server in the page in a table. but unfortunately it is not working. I can display it using out.println. Code samples are attached. Thank you very much.
ajax1 handles the ajax part and ajax2 is the file for java code.
...
Ajax1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("ajax2.jsp",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
</head>
<body>
<select id = "users">
<option value="">Select Account ID</option>
<option value="calicut">calicut</option>
<option value="kochi">kochi</option>
<option value="Admin">Admin</option>
</select>
<br />
<div id="javaquery"><b>Name will be displayed here</b></div>
</body>
</html>
Ajax2.jsp
<%#page import="java.text.SimpleDateFormat"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.*,java.sql.*,java.io.*" %>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<%# page import="java.io.*" %>
<%# page import="javax.sql.*" %>
<%# page import="javax.naming.*,javax.swing.*,java.sql.Date.*,java.text.SimpleDateFormat.*,java.util.Date.*" %>
<html> <head> <meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"> <title></title> </head>
<body>
<%
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
Name:<%out.print(name);%>
eName:<%out.print(ename);%>
</body> </html>
.............................................
.................................................
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("AjaxServlet",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
Remove java code from 2nd jsp and add it to a servlet called "AjaxServlet" with url mapping "/AjaxServlet"
AjaxServlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q = request.getParameter("q"); //q value
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "blank name";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(name); // Write response body.
}
More info on how to do ajax with servlets here:
How to use Servlets and Ajax?

I want to select last 5 entries from DB table and display it on a page. How can I achieve it using JSP?

I want to select last 5 entries from Database table. I have a columns ID(int), Product(string), Version(string), Description(string) in my database.
Let's say I have 50 entries in database and I need last 5 entries (i.e. 46,47,48,49 and 50) selected from table and print it on a HTML page. how can I do that using JSP?
below is my sample code:
<%# page import="java.util.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.text.*" %>
<%# page language = "java" %>
<%
int id=0;
Connection connect2=null;
Statement state2=null;
ResultSet result2=null;
Connection connect=null;
Statement state=null;
ResultSet result=null;
try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect2=DriverManager.getConnection("jdbc:odbc:ppbu");
state2 = connect2.createStatement();
String strQuery2 = "select MAX(ID) from kb_articles_list";
result2 = state2.executeQuery(strQuery2);
while(result2.next())
{id=result2.getInt(1);
}
}finally {
try {
if (state2 != null)
state2.close();
} catch (SQLException e) {}
try {
if (connect2 != null)
connect2.close();
} catch (SQLException e) {}
}
out.print(id);
for(int a=0; a<5; a++)
{
try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection("jdbc:odbc:ppbu");
state = connect.createStatement();
String strQuery = "select * from kb_articles_list where ID.equals(id)";
result = state.executeQuery(strQuery);
while(result.next()){
%>
<option><%= result.getString(2)%></option>
<% }state.close(); connect.close(); %>
<% }catch (Exception e) {
e.printStackTrace();}
id--;}%>
Thanks for your time. I got this working using the code below.
String strQuery = "select * from kb_articles_list where ID="+id+"";

how to display multiple images and data from mysql in jsp

I am using jsp with mysql in these code. i got only one images at a time but all data retrieved... Can u tell me how to display multiple images in this code?
my data: imagename varchar(),description varchar(),imageid varchar(),category varchar image blob().
index.jsp:
<%#page import="java.io.InputStream"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.OutputStream"%>``
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.
getConnection("jdbc:mysql://localhost:3306/rich","root","");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select *from publishers");
while(rs.next())
{
String imgLen=rs.getString(5);
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(5);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
%>
</body>
</html>
**basic.jsp:**
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.OutputStream"%>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
< form action="index.jsp" method="post">
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/rich","root","");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select *from publishers");
while(rs.next())
{
%>
<table border="1">
<tr> <td>
<img src="index.jsp?" /> </td> </tr>
<tr>
<td> <%=rs.getString(1)%> </td>
<td> <%=rs.getString(2)%> </td>
<td> <%=rs.getString(3)%> </td>
<td> <%=rs.getString(4)%> </td>
</tr>
</table>
<%
}
%>
</form>
</body>
</html>
Actually it is not difficult . We will use two jsps files to show images first this page for getting image.
<%# Page import="java.sql.*" %>
<%# Page import="java.io.*" %>
<html>
<%
byte[] imgData = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/try","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select photo from employee where employee_id=" + request.getParameter("empId"));
while (rs.next())
{
Blob image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
response.setContentType("image/png");
OutputStream o = response.getOutputStream();
o.flush();
o.close();
rs.close();
stmt.close();
con.close();
}
catch (Exception e)
{
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
}
%>
</html>
and here i getting all ids to get all images
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<html>
<%
try
{
String EmpFirstName;
String EmpSurname;
String EmpId;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/try","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select employee_id,first_name,surname from employee");
while (rs.next())
{
EmpFirstName = rs.getString("first_name");
EmpSurname = rs.getString("surname");
EmpId = rs.getString("EmpId");
<DIV><%=EmpFirstName5> <%=Surname%> </DIV>
<img src="http://localhost/GetImage.jsp?empId=<%=EmpId%>" />
}
rs.close();
stmt.close();
con.close();
}
catch (Exception e)
{
out.println(e.Message);
return;
}
%>
</html>
the code and its explanation taken from
http://stackoverflow.com/users/535152/tom%c3%a1s
thank you very much

How to display an image from the DB in JSP?

I need to retrieve image from MySQL DB.
I got a code snippet from somewhere but could not display the image properly in the jQuery panel.
The code runs in a new JSP page.
Can anyone tell me how to use outputstream effectively in my application?
The code I have is:
<% #page import = "java.sql.*" %>
<% #page import = "java.io.*" %>
<% Blob image = null;
Connection con = null;
byte[] imgData = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aes", "root", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("select PHOTO from tab_1 where name ='" + name + "'");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1, (int) image.length());
} else {
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
JSP is the wrong tool for this. JSP is a view technology. Any whitespace outside the <% %> will also be printed/sent to the response. It's in your case exactly that whitespace which malforms the binary integrity of the image and thus the image ends up being corrupted and unrenderable.
You have basically 2 options.
The simple/lazy way: remove all, I really mean all, whitespace outside <% %> including newlines.
Use the right tool: create a class which extends HttpServlet and move the code which you've there in the JSP into the doGet() method. Finally just call that servlet instead of the JSP.