Issue
I am new to java, and am trying to add an image 'space.gif' from a file path through a html servlet.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<HTML>");
out.print("<HEAD><TITLE>Upload Image</TITLE></HEAD>");
out.print("<BODY>");
out.print("<img src='space.gif' alt='image' />");
out.print("</BODY>");
out.print("</HTML>");
out.close();
}
Solution
If you put the space.gif
at the right location in the public web content and reference it by the right URL, then it'll work fine. As you have it right now, its location is dependent on the URL with which the servlet is been invoked. Basically, it should be virtually in the same folder as the servlet.
This example should do:
WebContent
|-- images
| `-- space.gif
`-- WEB-INF
|-- classes
`-- lib
with
out.print("<img src='" + request.getContextPath() + "/images/space.gif' alt='image' />");
Or, if that image is actually located outside the public web content and you can't move it in the public web content for some unobvious reason, then you'd need to add an extra web application context to your server configuration pointing to that folder, e.g. /images
, so that you can do
out.print("<img src='/images/space.gif' alt='image' />");
See also:
- Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag
Unrelated to the concrete problem, HTML belongs in JSP, not in Servlet.
Answered By - BalusC