This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 3 years ago.
I am trying to retrieve multiple images from database and display those images in another JSP page.
First, I tried single image to display in particular JSP page, I retrieved but the display is showing as file type,
I want to display that image in particular JSP page.
I am using MySQL database.
my servlet code:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Retrieve")
public class Retrieve extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas", "root", "root");
ps = con.prepareStatement("select * from rough");
rs=ps.executeQuery();
if (rs.next()) {
byte[] content = rs.getBytes("image");
response.setContentLength(content.length);
response.getOutputStream().write(content);
request.setAttribute("image", content);
RequestDispatcher rd=request.getRequestDispatcher("View.jsp");
rd.forward(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Display Image</title>
</head>
<body>
<div>THE DISPLAY</div>
<div style="width:25%; height:25%">
<%request.getAttribute("image"); %>
</div>
</body>
</html>
Try using Base64 encoding,
Use Apache Commons Codec to do Base64 encodings.
byte[] content = rs.getBytes("image");
String base64Encoded = new String(Base64.encodeBase64(content), "UTF-8");
request.setAttribute("imageBt", base64Encoded);
Retrieve it from JSP
<img src="data:image/png;base64,${requestScope['imageBt']}"/>
For multiple images you could try something like this, (i didnt try this)
List<String> images = new ArrayList<>();
if (rs.next()) {
byte[] content = rs.getBytes("image");
images.add(new String(Base64.encodeBase64(content), "UTF-8"));
}
request.setAttribute("imageBt", images);
In JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="img" items="${imageBt}">
<img src="data:image/png;base64, ${img}"/>
</c:forEach>
Related
I am sending form data using Jsp through AJAX on Servlet.
reg.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form>
Enter name:<input type="text" id="name" /> <br />
<button onclick="callJqueryAjax()">Save</button>
</form>
<span id="result"></span>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function callJqueryAjax() {
location.reload(false);
var name = $('#name').val();
console.log(name);
$.ajax({
url : 'Save',
method : 'POST',
data : {
name : name,
},
success : function(resultText) {
$("#result").html(resultText);
}
});
}
</script>
</body>
</html>
SaveMe.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Save")
public class SaveMe extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection makeCon;
private Statement stmt;
public void init(ServletConfig config) throws ServletException {
JdbcCon jdbcCon = new JdbcCon();
makeCon = jdbcCon.makeCon();
try {
stmt = makeCon.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String name = request.getParameter("name");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql = "insert into users (name) Values('" + name + "')";
System.out.println(sql);
try {
int result = stmt.executeUpdate(sql);
if (result > 0) {
out.print("Inserted");
} else
out.print("Not Inserted");
} catch (SQLException e) {
}
}
}
I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.
Please provide me the solution and also a better way for writing an ajax call
First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request.
You could remove it.
In addition a good practice when using ajax request is to specify the "dataType", in your case "html".
Here is an example:
$.ajax( {
type : 'POST',
url : 'SaveMe',
success : function(result) {
$("#result").html(result);
},
dataType : "html"
});
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 4 years ago.
I am trying to retrieve multiple images from database and display them using JSP page, I tried but not getting perfect logic to retrieve multiple images from database.
The below is code of retrieving single image, please help in retrieve multiple images
I am using mysql database
my servlet code:
package com.Image;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.codec.binary.Base64;
#WebServlet("/ImageRetrieve")
public class ImageRetrieve extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database1", "root", "vicky");
ps = con.prepareStatement("select frontimage from album ");
rs=ps.executeQuery();
if (rs.next()) {
byte[] fi = rs.getBytes("frontimage");
String FI = new String(Base64.encodeBase64(fi), "UTF-8");
request.setAttribute("FIS", FI);
RequestDispatcher rd=request.getRequestDispatcher("RetrieveImage.jsp");
rd.forward(request, response);
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
my jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Display Image</title>
</head>
<body>
<div>THE DISPLAY</div>
<div >
<img src="data:image/png;base64,${requestScope['FIS']}" style="width:50px; height:50px"/>
</div>
</body>
</html>
if (rs.next()) {
...
}
will only get the first byte[] from rs. Change this to a while loop to get each of them:
while (rs.next()) {
...
}
But you need a container, such as a List to hold them:
List<String> images = new ArrayList<>();
while (rs.next()) {
...
images.add(FI)
}
Then after the loop, set the attribute of the List and forward on:
request.setAttribute("FIS", images);
RequestDispatcher rd= ...;
rd.forward(request, response);
And in the JSP, iterate over FIS (which is now a List) to display each one.
Your issue is in the if-statement if (rs.next()) which only executes a single time regardless of number of results in the ResultSet. Because the if-statement returns true if there are any number of results in the ResultSet, the first image of the ResultSet is stored and the code moves on because the if-condition has been satisfied. The code has done exactly what you have told it to do. Changing the if-statement to while (rs.next()) will iterate through the entire ResultSet, saving each image to your predefined array.
I am trying to retrieve data from one column of my table in MySQL and display the whole row in a .jsp file. Right now, when I run the code it prints the table with no values. As Shown here.
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
#WebServlet("/review")
public class findservlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8402378218178447403L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection conn = null;
//using movie_resolved view
try{
// Get a Connection to the database
String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
String DB_USERNAME = "root";
String DB_PASSWORD = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
// Create a Statement object
PreparedStatement st = (PreparedStatement) con.prepareStatement("SELECT * FROM coursereview");
ResultSet rs = st.executeQuery();
if (rs.next())
{
com.java.bean.coursereview Course = new com.java.bean.coursereview ();
Course.setCourse_id(rs.getString("courseid"));
Course.setCourserate(rs.getString("courserate"));
Course.setProfessor(rs.getString("professor"));
Course.setProrate(rs.getString("prorate"));
Course.setReview(rs.getString("review"));
req.setAttribute("Course", Course);
RequestDispatcher view = req.getRequestDispatcher("review.jsp");
view.forward(req, res);
}
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}
finally {
// Always close the database connection.
try {
if (conn != null) conn.close();
}
catch (SQLException ignored) { }
}
}
}
Here is my reivew page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="styles/style1.css">
<meta http-equiv="Content-Type" content="text/css; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="banner">
<img class="banner-image" src="images/uncclogo400.jpg"></div>
<h2>Review a Course</h2>
<table>
<TR>
<TD>Course ID: </TD>
<TD>${course.courseid}</TD>
</TR>
<TR>
<TD>Course Rate: </TD>
<TD>${course.courserate}</TD>
</TR>
<TR>
<TD>Professor: </TD>
<TD>${course.professor}</TD>
</TR>
<TR>
<TD>Professor Rate: </TD>
<TD>${course.prorate}</TD>
</TR>
<TR>
<TD>Review: </TD>
<TD>${course.review}</TD>
</TR>
</table>
</body>
</html>
I am trying to pull the values from the MySQL DB to print to the review.jsp page. Any ideas on what I am doing wrong?
Hello, I think it's a typo
Change this req.setAttribute("Course", Course); by this req.setAttribute("course", Course);
Best,
I'm beginner in java field and i'm working on a project books store. I have created a purchase link which is redirected to purchase servlet and in purchase servlet i have my sql query through which i'm fetchin the book details of the selected book but the sql is throwing exception of can not issue executeUpdate for SELECTs.
Thanks for the help in advance
here is my jsp code where i have purchase link
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page 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>Insert title here</title>
<link href="templatemo_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql:/
/localhost:3306jsp","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from books where
book_type='Thriller Book'");
out.print("<table width='80%'>");
out.print("<tr><th>ID</th><th>Book Name</th><th>Book Author</th><th>Book
Price</th><th>Book Category</th><th></th></tr>");
while(rs.next())
{
String str1=rs.getString("id");
String str2=rs.getString("book_name");
String str3=rs.getString("book_author");
String str4=rs.getString("book_price");
String str5=rs.getString("book_type");
out.println("<tr><td align='center'>"+str1+"</td><td
align='center'>"+str2+"</td><td align='center'>"+str3+"</td><td
align='center'>"+str4+"</td><td align='center'>"+str5+"</td><td
align='center'>Purchase
</td></tr>");
}
out.print("</table>");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
</body>
</html>
here is my purchase servlet where i have my sql code
package purchase;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/purchase")
public class Purchase extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
PrintWriter out=response.getWriter();
Connection con=null;
try
{
String str1=request.getParameter("id");
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306
/jsp","root","root");
PreparedStatement ps=con.prepareStatement("select
book_name,book_author,book_price from books where id=?");
ps.setString(1,str1);
int i=ps.executeUpdate();
if(i!=0)
{
out.println("Details");
}
else if(i==0)
{
out.println("<table>");
out.print("<tr><td>Book Name</td><td>Book Author</td><td>Book
Price</td><td>Purchase</td></tr>");
out.println("</table>");
}
}
catch (ClassNotFoundException | SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are doing a SELECT, so you should be calling executeQuery(), not executeUpdate():
String sql = "SELECT book_name, book_author, book_price FROM books WHERE id=?";
Statement ps = con.createStatement();
ps.setString(1, str1);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String bookName = rs.getString("book_name");
// etc.
}
The solutions I found for this error were "add the jar file via build path" and "put the jar file containing the driver in WEB-INF/lib" (and similar formulations) but I already tried the two of them.
Back to my problem. Here is my Code:
jsp-file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="db.DBAccess" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="dba" class="db.DBAccess"></jsp:useBean>
<jsp:setProperty name="dba" property="selection" value="s" />
</body>
</html>
javabean
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBAccess {
public DBAccess() {
}
private String selection = "";
public void setSelection(String s) {
final String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "user1";
String pswd = "user1pswd";
Connection con = null;
Statement stmt = null;
try {
// initialize connection
Class.forName(driver);
con = DriverManager.getConnection(url, user, pswd);
stmt = con.createStatement();
// execute select
ResultSet results = stmt.executeQuery("SELECT * FROM t");
results.next();
selection = results.getString(1);
// close connection
stmt.close();
con.close();
} catch (ClassNotFoundException cnfe) {
System.out.println(cnfe.toString());
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
The content of t is one column with the label "string" and the content "hello world"
Why am I getting this exception even though I linked the jar file correctly?
Did you insert your jar file to lib folder of Webinf?