This post not related to any Java
framework but general web programming using simple jsp and servlet.
Yesterday my
friend having a problem, he have different images path in database and he want
to show these images which are actually outside the web container (not in image
folder of project but on system location ex: /user/home/image).
Here is the code
that how we can display images on jsp page.
Now suppose image
Path in your database are like user/home/images/mypic.jpg or in windows
D:/images/ mypic.jpg
step1: First
create the Servlet in your project which containing the code like this one
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.io.OutputStream;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
/**
*
Servlet implementation class DisplayImage
*/
public
class DisplayImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public DisplayImage() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request,
response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
String imagePath=request.getParameter("img");
response.setContentType("image/gif");
File f = new File(imagePath);
FileInputStream fin = new
FileInputStream(f);
byte[] buffer = new
byte[fin.available()];
fin.read(buffer);
fin.close();
OutputStream o =
response.getOutputStream();
o.write(buffer);
o.flush();
o.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Step2: Now
when you read the jpg file path in other servlet or in you controller just
forward the response on any jsp which showing all the images.
In your jsp if you
want to show multiple images just create a loop on array or list and use this
HTML img tag to show the images
<img
alt="My img"
src="<%=request.getContextPath()%>/DisplayImage?img=<%=yourPathFromDB%>"></img>
When this jsp is
called directly or when control come to this it will call the DisplayImage
servet which show the response simply because we set the response Content Type image/gif.
Enjoy..
No comments:
Post a Comment