This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 6 years ago.
I am trying to retrieve few blob images from mysql database using java. Now , the problem is that I'm able to get only one image at a time, the other images are not getting displayed.
Below is my jsp code , where I'm doing this(just for demonstration purpose):
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MindDotEditor posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow" />
<link href="../sample.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../fckeditor.gif" type="image/x-icon" />
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/grandsho_register";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url,"root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT image FROM user ");
int i = 1;
if(rs.next()) {
Blob len1 = rs.getBlob("image");
int len = (int)len1.length();
byte[] b = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index = readImg.read(b, 0, len);
System.out.println("index" +index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(b,0,len);
response.getOutputStream().flush();
}
} catch(Exception ex) {
out.println(ex);
} finally {
rs.close();
stmt.close();
con.close();
}
%>
<br>
<center><input type="button" value="Print" onclick="window.print();return false;" /> </center>
</body>
</html>
Can anyone suggest how can i display multiple images on jsp page?
Instead of if(rs.next()) {} you have to use while(rs.next()){}
Related
I have written simple jsp program where I am trying to retrieve username and password from database, here is my jsp program.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="oracle.sql.*" %>
<%# page import ="oracle.jdbc.driver.*" %>
<%#page import="oracle.jdbc.driver.OracleDriver"%>
<%# page import ="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String driver="oracle.jdbc.driver.OracleDriver";
String userid = request.getParameter("username");
String pwd=request.getParameter("password");
Connection con = null;
%>
<%try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:CCB25", "CISADM", "CISADM");
Statement st= con.createStatement();
String query="select * from CMLOGIN where USERID='"+userid+"'";
ResultSet rs=st.executeQuery(query);
String pass1="";
rs.next();
pass1 = rs.getString("password");
if(pass1.equals(pwd))
{
%>
<%String name=request.getParameter("username");
session.setAttribute("nam",name);%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%}
else
{
String msg="Username or password failed";%>
<center> <p style="font-family:verdana;color:red;"><%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<%}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
and i have javax.servlet.jar and ojdbc7-12.1.0.2.jar in web-inf/lib folder. I am getting java.sql.SQLException: Result set after last row on the following line "pass1 = rs.getString("password");" Could you please guide me what I am doing wrong.
You first need to check if the ResultSet has any rows in it before calling .next(), in order to prevent this exception.
Use this:
if (rs.next){
//read next row
}
if you want to loop through all the rows of the ResultSet, use a while loop:
while(rs.next){
//do something for every row
}
Here is the same cleaned up a little. You'll have to add back in exception handling and closing of the connection/statement/resultset
Hopefully you never have to use this code for real as it's taking in a password from query string in clear then comparing to a clear version in the db.
Password comparison moved to the sql itself.
Always use PreparedStatements to avoid sql injection
Comments are in the code.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String userid = request.getParameter("username");
String pwd = request.getParameter("password");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "klrice", "klrice");
//
// USE BINDS ! to avoid sql injection
// push the userid and passwd comparison to the db
// no need to get the password and compare locally
//
String query = "select password from cmlogin where userid=? and password=?";
PreparedStatement st = con.prepareStatement(query);
//
// Binds in the vaules
//
st.setString(1,userid);
st.setString(2,pwd);
ResultSet rs = st.executeQuery();
String pass1;
// .next will advance if the query has any results
//
if ( rs.next() ) {
pass1 = rs.getString("password");
String name =request.getParameter("username");
session.setAttribute("nam",name);
%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%
} else {
String msg="Username or password failed";
%>
<center> <p style="font-family:verdana;color:red;"> <%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<% } %>
</body>
the following jsp code returns just a blank screen on web browser... what to do?
<%#page import="java.sql.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GAURAV GOSWAMI</title>
<%
try
{
Class.forName("java.sql.DriverManager");
Connection con =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/quiz","root","");
Statement stmt = con.createStatement();
String query = "select * from qa";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
%>
<p><br><%rs.getString(0);%></p>
<p><br><%rs.getString(1);%></p>
<p><br><%rs.getString(2);%></p>
<p><br><%rs.getString(3);%></p>
<p><br><%rs.getString(4);%></p>
<%
}
}
catch(Exception e)
{
%>
<br><%e.getMessage();%>
<%
}
%>
</head>
</html>
You're writing the body in the head section.
Move your code in the body section, like following:
<%#page import="java.sql.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GAURAV GOSWAMI</title>
</head> <!-- Add this line -->
<body> <!-- Add this line -->
<%
try
{
Class.forName("java.sql.DriverManager");
Connection con =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/quiz","root","");
Statement stmt = con.createStatement();
String query = "select * from qa";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
%>
<p><br><%rs.getString(0);%></p>
<p><br><%rs.getString(1);%></p>
<p><br><%rs.getString(2);%></p>
<p><br><%rs.getString(3);%></p>
<p><br><%rs.getString(4);%></p>
<%
}
}
catch(Exception e)
{
%>
<br><%e.getMessage();%>
<%
}
%>
</body> <!-- Add this line -->
<!-- **** </head> *** Remove this line -->
</html>
I hope it helps you, bye.
PS: I've marked with comments like <!-- Add this line --> the lines to change.
Besides Alessandro's answer(do not write content into head),the jdbc driver you wrote is also incorrect
You need to use com.mysql.jdbc.Driver instead.
So change
Class.forName("java.sql.DriverManager");
to
Class.forName("com.mysql.jdbc.Driver");
very recently i started learning Java Technology right now I'm working on Servlets while i fetch the data from data base it's not resolving resultset rs
here I attached my code
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<script>
<%
try{
ResultSet rs=null;
String mail=(String)session.getAttribute("mail");
String sql="select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con=DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, mail);
rs=ps.executeQuery();
}catch(Exception e){
}
%>
<%
while(rs.next())
{
%>
<%=rs.getString(4)%>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}%>
</script>
</a>
</body>
</html>
please help me out.. thanks
Your code should be changed at least:
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<%
ResultSet rs = null;
try {
String mail = (String) session.getAttribute("mail");
String sql = "select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con = DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, mail);
rs = ps.executeQuery();
while (rs.next()) {
%>
<%=rs.getString(4)%>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
This is what i have, when i run the jsp file on the browser the only thing i get is the "Report" header but not the query result, please guide me to the right way.
<%#page import="java.sql.ResultSet"%>
<%#page import="database.Dba"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center> <h1> Report </h1></center>
<%
//scriplet
try{
Dba db =
new Dba(application.getRealPath("daw.mdb"));
db.conectar();
db.query.execute("select usuario from usuarios");
ResultSet rs = db.query.getResultSet();
while(rs.next()){
out.print(rs.getString(1)+ "<br>");
}
db.desconectar();
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
After the delete below how can this page be redirected to the previours page and do a refresh to not show the data deleted?
I tried some options like:
<%
String redirectURL = "Index.jsp";
response.sendRedirect(redirectURL);
%>
but did not work. Should it just work with complete urls?
am I doing this right also or this is not the best practice?
Thanks you!
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java"%>
<%#page import="java.lang.*" import="org.postgresql.*"
import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<%
try {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/postgres";
Connection connection = DriverManager.getConnection(url,
"postgres", "admin");
String strquery = "DELETE FROM projects WHERE project = '"
+ request.getParameter("project") + "'";
Statement st = connection.createStatement();
//System.out.println("Connecting to database...");
ResultSet rs = st.executeQuery(strquery);
System.out.println(strquery);
pageContext.forward("Index.jsp");
rs.close();
st.close();
} catch (Exception e) {
System.out.println(e);
}
%>
</body>
</html>