How to Upload an Image to Java Jsp Website
- Details
- Written by
- Terminal Updated on 04 July 2019 | Print Electronic mail
In this tutorial, we will guide y'all how to write lawmaking for displaying images stored in database on a JSP page inside Java web application. Suppose that the images are stored in the database in BLOB format (Binary Large Object), and your awarding needs to display the images on spider web pages without saving the images somewhere on the server'due south deejay. By and large, here are the key steps to implement:
- Retrieve the image data from the database as an array of bytes, past using JDBC. If you are using Hibernate, this can be done transparently by the framework.
- Encode the image's binary information to String representation in Base64 format.
- Display the image on a JSP page using <IMG>tag with image source is the base64 string.
Now, let's run into how to integrate these steps into a typical request-response workflow of a Coffee web application based on Servlet and JSP. The database we use for the example is MySQL.
1. The Database
Suppose that nosotros have a table named book that has a column called image which is of type LONGBLOB (this type can store files up to 4GB):
So our ultimate goal is to retrieve image data from this column and display the image on a web page.
2. The Java Model Grade
The Java model grade for the table needs to have a field to store the base64 string representation of the paradigm. For case:
package net.codejava; public form Book { individual String championship; private String writer; private String base64Image; public String getBase64Image() { return base64Image; } public void setBase64Image(String base64Image) { this.base64Image = base64Image; } // other fields... // other getters and setters… }
The field'south setter setBase64Image() volition be called past a DAO form that retrieves the image binary data and converts it to a base64 string.
The field's getter getBase64Image() volition be called past a JSTL tag in the JSP page in order to show the paradigm.
If yous are using Hibernate, the paradigm column should exist mapped similar the following code, in boosted the getter and setter for base64Image field:
package internet.codejava; public grade Book { private Cord title; individual String author; private byte[] image; @Cavalcade(name = "image") public byte[] getImage() { return this.image; } private String base64Image; public Cord getBase64Image() { render base64Image; } public void setBase64Image(String base64Image) { this.base64Image = base64Image; } // other fields... // other getters and setters }
three. The DAO Grade
In the DAO class, we write some additional code for retrieving the image's binary data and converting information technology to a base64 string. Given a ResultSet object named result, the post-obit code reads the paradigm column into a byte assortment, and and so converts information technology to a String in base64 format:
Blob blob = result.getBlob("image"); InputStream inputStream = blob.getBinaryStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -ane; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] imageBytes = outputStream.toByteArray(); String base64Image = Base64.getEncoder().encodeToString(imageBytes); inputStream.close(); outputStream.close();
The Base64 class can be found in the java.util package.
In example Hibernate is used, but update the getter getBase64Image() equally follows:
@Transient public String getBase64Image() { base64Image = Base64.getEncoder().encodeToString(this.image); return base64Image; }
And the post-obit is sample code of a DAO grade - BookDAO:
package cyberspace.codejava; import java.io.ByteArrayOutputStream; import coffee.io.IOException; import coffee.io.InputStream; import java.sql.Hulk; import java.sql.Connection; import java.sql.DriverManager; import coffee.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import coffee.util.Base64; public class BookDAO { String databaseURL = "jdbc:mysql://localhost:3306/bookstoredb"; String user = "root"; String password = "pass"; public Book become(int id) throws SQLException, IOException { Book book = aught; String sql = "SELECT * FROM book WHERE book_id = ?"; endeavor (Connection connection = DriverManager.getConnection(databaseURL, user, password)) { PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(one, id); ResultSet result = statement.executeQuery(); if (outcome.next()) { book = new Book(); String title = result.getString("title"); String author = event.getString("writer"); Blob blob = result.getBlob("image"); InputStream inputStream = hulk.getBinaryStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] imageBytes = outputStream.toByteArray(); String base64Image = Base64.getEncoder().encodeToString(imageBytes); inputStream.close(); outputStream.close(); book.setTitle(championship); book.setAuthor(author); book.setBase64Image(base64Image); } } catch (SQLException | IOException ex) { ex.printStackTrace(); throw ex; } return book; } }
Every bit you can run across, the go(int id) method finds a row in the book table that associates with the specified id. If the row is found, a new Book object is created and populated its data similar this:
volume.setTitle(title); volume.setAuthor(author); book.setBase64Image(base64Image);
4. The Servlet Class
In the Servlet class, it receives request from the user with the specified book ID, then it calls the DAO to think the Volume object, which is then stored as a request attribute. Finally the servlet forwards the processing to a destination JSP folio.
Here is sample code of the servlet class:
package internet.codejava; import java.io.IOException; 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("/viewbook") public class GetBookServlet extends HttpServlet { private static final long serialVersionUID = 1L; public GetBookServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int bookId = Integer.parseInt(request.getParameter("id")); BookDAO dao = new BookDAO(); try { Volume book = dao.get(bookId); request.setAttribute("book", book); String page = "/alphabetize.jsp"; RequestDispatcher requestDispatcher = request.getRequestDispatcher(page); requestDispatcher.forrad(request, response); } catch (SQLException ex) { throw new ServletException(ex); } } }
5. Brandish Image in the JSP Page
To display the image represented by a base64 String, use the <IMG> tag with the following syntax:
<img src="information:epitome/jpg;base64, [base_64_String_goes_here] " />
And here is code of a sample JSP page that uses JSTL tags mixed with HTML tags:
<%@ taglib uri="http://java.dominicus.com/jsp/jstl/core" prefix="c" %> <%@ page language="java" contentType="text/html; charset=ISO-8859-one" pageEncoding="ISO-8859-1"%> <html> <body> <div align="heart"> <h2><c:out value="${book.championship}" /></h2> <h3><c:out value="${book.author}" /></h3> <img src="data:image/jpg;base64,${book.base64Image}" width="240" height="300"/> </div> </body> </html>
half dozen. Test Paradigm Display
Suppose that the book table contains some rows with epitome data. To exam if the image gets displayed in the JSP page or non, call the Coffee Servlet by typing the post-obit URL in a web browser:
http://localhost:8080/Bookshop/viewbook?id=1
You can see the volume image gets displayed as shown in the following screenshot:
So far you have learned how to implement a solution that helps display images from database in JSP folio, without having to shop images somewhere on the server'due south disk. The key bespeak here is using the <IMG>tag with a base64 String that represents the image.
Other Java Coding Tutorials:
- How to implement forgot password characteristic for Java web awarding
- How to implement recall password (remember me) for Java web application
- How to code login and logout with Coffee Servlet, JSP and MySQL
- How to Lawmaking Hit Counter for Java web application
- 10 Common Mistakes Every Beginner Coffee Programmer Makes
- 10 Java Core Best Practices Every Java Developer Should Know
- How to get a skilful programmer? 13 tasks you should practice now
- How to calculate MD5 and SHA hash values in Java
- Java File Encryption and Decryption Example
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java 1.4 and has been falling in beloved with Coffee since and so. Brand friend with him on Facebook and watch his Java videos you YouTube.
Add comment
stockdillgolou1940.blogspot.com
Source: https://www.codejava.net/coding/how-to-display-images-from-database-in-jsp-page-with-java-servlet