0

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();
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
bobby
  • 99
  • 1
  • 2
  • 9
  • Hey Jeff! Welcome to Stack Overflow! We ask that you make your answers as clear as possible and show any code, material, or other information you have gathered or tried while attempting to solve your problem. This makes it much easier to answer questions. – nmagerko Nov 10 '11 at 01:34
  • 1
    If you show some code and write more detailed description of a problem I bet you'll get help here :) – Igor Nikolaev Nov 10 '11 at 01:35
  • It looks like you've done what you're asking about; is there a problem? – Dave Newton Nov 10 '11 at 01:43
  • My image doesn't show, only the text. I guess there must be a problem with my file path. – bobby Nov 10 '11 at 01:45

2 Answers2

5

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:


Unrelated to the concrete problem, HTML belongs in JSP, not in Servlet.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Find the docBase path given in (YourProjectname).xml file(mine was D:\MiniProject2\MiniProject2\build\web), Then just make an Image Folder(i made folder "Images" in D:\MiniProject2\MiniProject2\build\web ) Store Your Images in this Folder

now use

It will work;