Saving a resource (image etc) relative to application root and using it back in a Servlet / Jsp
I have this use case for which I 开发者_StackOverflowam generating an image in the getPost method of servlet. I was saving the image in the local file system at /tmp/xyz.jpg and then doing something like
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<title>Example</title>");
out.println("<body><h2>Graph is :</h2>");
out.println("<img src='/tmp/TimeSeriesChart.jpg'></body>");
out.println("</html>");
Naturally the image did not get displayed when I hit the URL (to call servlet).
The reason I think was that img src is calculating against the Application's Root not fileSystem's Root.
So to summarize I want to be able to save the image at a proper place relative to Application Root , access the image and display it.
Q1. How to find the Application Root within the servlet. So that I can save the image rightly.
Q2. How advisable is to set the content as image and then read it as bytes and display : http://www.exampledepot.com/egs/javax.servlet/GetImage.html
Ans1: ServletContext.getRealPath() will give you the app root location.
Ans2: Nothing wrong in having a servlet, but Container doing that would handle the following cases as well:
- If-Modified-Since, sends SC_NOT_MODIFIED response
- Caching the image data in container for subsequent requests.
精彩评论