Milson Milson - 1 year ago 60
jQuery Question

How to bind the Images in HTML page where the files are located inside WEB-INF\classes\uploads folder in tomcat server

I am trying to use jQuery Scroller to a number of images stored in Java Web application.

I used

to set upload folder for each images:

UPLOAD_PATH = this.getClass().getResource("/uploads").toURI()

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
tag but because images are actually stored in
I can not directly load those images into the page. Is there any simple way to load those JSON
field in a
page and display them.

Answer Source

You may write a simple Servlet and map the request to it. Sample code below:


package com.javavirtues.sample;


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;

    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) {
        } else {
            OutputStream outputStream = resp.getOutputStream();
            byte[] buffer = new byte[1024];
            for (int length = 0; (length = > 0;) {
                outputStream.write(buffer, 0, length);

web.xml snippet

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download