How to display an image from the DB in JSP? - mysql

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.

Related

Java Sql Exception After End of Result Set

My code works fine but when I try to run the code it first shows java.sql.SQLException:After end of result set. I would like to know what is causing this and how to fix this as this is for a graded project.
public GenerateBill()
{
initComponents();
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore","root","root");
Statement stmt=(Statement)con.createStatement();
String query, product;
query="select * from store;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next());
{
product=rs.getString("productname");
jComboBox1.addItem(product);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
}
When I execute the code a Message Dialog Box shows up first.
And when I click OK, the page I'm trying to make opens and executes normally.
So, I'm confused as to what it means. Also, I'm new to this site, so I don't really know how much of the code I need to add. The rest of the code is for different jButtons. The page is for Generating Bills/Receipts.
There are some parts in your code that could be better. Specifically,
Use com.mysql.jdbc.Driver as your DB is MySQL, instead of java.sql.DriverManager
No need to cast your Connection object.
After /bookstore you could add ?useSSL=false, although it is not mandatory, so something like jdbc:mysql://localhost:3306/bookstore?useSSL=false
Use java.sql.PreparedStatement instead of simply Statement.
Close your connection in a finally block after catch.
Eventually, your code should look somehow like the following,
public GenerateBill() {
initComponents();
Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?useSSL=false","root","root");
String query = "select * from store";
stmt = con.prepareStatement(query);
String product;
rs = stmt.executeQuery();
while(rs.next())
{
product = rs.getString("productname");
jComboBox1.addItem(product);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.toString());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
LOG.error("Error closing the connection with the database...");
e.printStackTrace();
}
}
}
Try the above and let me know if it is OK. If not, please post the whole exception to see what causes the issue.

My code not displaying image on chrome browser but works find on internet explorer

I'm trying to display image from MySQL server on to the browser. But the following code works on Internet Explorer but not working on Chrome and Mozilla Firefox browser.
I'm new to JSP and I've already tried code from this question but didn't work .Displaying image in jsp from database
`<%# include file="connect.jsp" %>
<%#page import="java.sql.*,java.io.*"%>
<%# page import="java.sql.*,java.io.*,java.util.*" %>
<%
try{
int id = Integer.parseInt(request.getParameter("id"));
Statement st=connection.createStatement();
String strQuery = "select image from user where id="+id+"" ;
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next())
{
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next())
{
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st.close();
response.reset();
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}%>
To retrieve multiple images from the SQL database and display in JSP pages you can do this:
<%
int id = Integer.parseInt(request.getParameter("imgid"));
try {
Connection con=DriverManager.getConnection("jdbc:sqlserver://XXXXX\\SQLEXPRESS14;databaseName=Student;user=XX;password=XXXXX");
Statement st = con.createStatement();
String strQuery = "select image from login_users where id='" + id + "'";
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next()) {
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next()) {
byte[] bytearray = new byte[4096];
int size=0;
InputStream sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1) {
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
sImage.close();
rs.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
%>

Display multiple Blob files from mySQL

I want to create a gallery in a java web app project. The gallery reads images that are stored as BLOB files in a mySQL DB. This is what I have done but only the first Image in the db displays. Is it possible to read multiple BLOB images from a db or would I be better off creating a gallery from images stored in a folder?
<%# 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/capture","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("select file from photoentry");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
else {
out.println("Display Blob Example");
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/jpg");
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();
}
}
%>

Export excel from MySQL database using JSP

This is my JSP coding, I am using link to redirect to JSP page :
Excel.jsp
<%#page import="java.sql.*"%>
<%#page import="java.sql.SQLException"%>
<%#page import="org.apache.poi.hssf.usermodel.*"%>
<%#page import=" java.io.*"%>
<%
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url + dbName", "userName",
"password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from openstock");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("fisocon");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("iname");
rowhead.createCell((short) 1).setCellValue("wname");
rowhead.createCell((short) 2).setCellValue("catname");
rowhead.createCell((short) 3).setCellValue("class");
rowhead.createCell((short) 4).setCellValue("unit");
rowhead.createCell((short) 5).setCellValue("nname");
int i = 1;
while (rs.next()){
out.println("hai2");
HSSFRow row = sheet.createRow((short) i);
row.createCell((short)
0).setCellValue(Integer.toString(rs.getInt("iname")));
row.createCell((short) 1).setCellValue(rs.getString("wname"));
row.createCell((short) 2).setCellValue(rs.getString("catname"));
row.createCell((short) 3).setCellValue(rs.getString("class"));
row.createCell((short) 4).setCellValue(rs.getString("unit"));
row.createCell((short) 5).setCellValue(rs.getString("nname"));
i++;
}
String yemi = "d:/xls/test.xls";
FileOutputStream fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
%>
In this coding, createcell is strikeout. I don't know why it is.
There is no errors in coding. I also add poi 3.14 jar file in library.
My output page displays as empty. Please help me. Thanks in advance.
Page is empty because everything You made is outside of page.
BTW doing such in JSP is the worst idea.
Move this code to servlet, here is tip how to return binary data.
java servlet response returning data
Add
response.contentType = "application/vnd.ms-excel"
and JPS page should only have link
The additional effect: servlet code is more, more friendly to debugging.

Query MySQL using JSP and Servlet POST method

I'm not sure if I'm trying to "print" my result correctly. What I'm trying to do is use JSP to take in the variable and then pass it to the servlet where it will query the database and then display the result. I tested querying my database in a different java file and I had no trouble with that. Any advice would be greatly appreciated!
JSP file:
<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>
<input type = "submit" />
</form>
JAVA file (servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.setContentType("text/html; charset=ISO-8859-1");
PrintWriter out = response.getWriter();
java.sql.Connection con = null;
java.sql.PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/masters";
String user = "christine";
String password = "password";
try{
String exName = request.getParameter("exName");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
rs = pst.executeQuery();
while (rs.next()){
String name = rs.getString("description_txt");
out.print(exName);
out.print(name);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
There are few things you need to change in your code.
As #BalusC mentioned do not suppress exception. Write exception to browser using out.println(ex); or throw new ServletException(ex). This will help you in finding the cause of problem.
Add Class.forName("com.mysql.jdbc.Driver"); before DriverManager.getConnection().
As you are already using PreparedStatement use
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name =?");
pst.setString(1, exName);
rs = pst.executeQuery();