Serving images from my military catalog?

I have a servlet that serves an image file that was saved in blob. If the requested image cannot be found, I would like to upload a static image, which I have included in my military directory. How do we do this? This is how I serve blob images from the data store:

public class ServletImg extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
  {
    MyImgWrapper obj = PMF.get().getPersistenceManager().
      getObjectById(MyImgWrapper.class, 'xyz');
    if (obj != null) {
      resp.getOutputStream().write(obj.getBlob().getBytes());
      resp.getOutputStream().flush();
    }
    else {
      // Here I'd like to serve an image from my war file. 
      /war/img/missingphoto.jpg
    } 
  }
}

Yes, I'm just not sure how to get the images from the image in my military directory, or if there is some other way to do this?

thank

+3
source share
4 answers

, ClassLoader#getResourceAsStream(), , classpath. webcontent, ServletContext#getResourceAsStream(). ServletContext getServletContext().

InputStream input = getServletContext().getResourceAsStream("/img/missingphoto.jpg");

, / byte[] . (1 ~ 10KB) :

input = getServletContext().getResourceAsStream(path);
output = response.getOutputStream();
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
    output.write(buffer, 0, length);
}
+3

Follow Haveacafe .

Google: java war file resource.

+1

.

ClassLoader classLoader = this.getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream(fileNameInClasspath);
...
+1

http ( 301) URL .

0

Source: https://habr.com/ru/post/1753555/


All Articles