I am trying to use jQuery Scroller to a number of images stored in Java Web application.
I used UPLOAD_PATH
to set upload folder for each images:
UPLOAD_PATH = this.getClass().getResource("/uploads").toURI()
.getPath();
These images are successfully saved and stored to this path.
During client binding I get JSON values as:
[ { "id" : "57b08900505ab53e40a97355", "title" : "fdsafdasf", "description" : "sfdfasd", "rating" : 3, "price" : 21.0, "quantity" : 121, "type" : "Road Bike", "primaryimage" : "/uploads/1uSdodND_2016_08_14.jpg", "addedon" : "2016-08-14", "isactive" : true },
{ "id" : "57b0318991ed7332c8dd67a3", "title" : "fdsaf", "description" : "fdsafd safdsaf", "rating" : 4, "price" : 32232.0, "quantity" : 232, "type" : "Mountain Bike", "primaryimage" : "/uploads/rM1hHzek_2016_08_14.png", "addedon" : "2016-08-14", "isactive" : true } ]
I am trying to use simple HTML page to bind those images into a <img>
tag but because images are actually stored in WEB-INF\\classes\\uploads
I can not directly load those images into the page. Is there any simple way to load those JSON primaryimage
field in a HTML
page and display them.
You may write a simple Servlet and map the request to it. Sample code below:
Servlet
package com.javavirtues.sample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getPathInfo();
InputStream resourceContent = getServletContext()
.getResourceAsStream("/WEB-INF/classes/uploads" + fileName);
if (resourceContent == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
OutputStream outputStream = resp.getOutputStream();
byte[] buffer = new byte[1024];
for (int length = 0; (length = resourceContent.read(buffer)) > 0;) {
outputStream.write(buffer, 0, length);
}
}
}
}
web.xml snippet
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.javavirtues.sample.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/uploads/*</url-pattern>
<servlet-name>ImageServlet</servlet-name>
</servlet-mapping>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.