-1

I want to call a Servlet from img src. I have defined a Servlet class with name ImageProducerServlet and registered it in web.xml:

<servlet>
   <servlet-name>ImageProducerServlet</servlet-name>
   <servlet-class>com.company.servlet.ImageProducerServlet</servlet-class>    
</servlet>
<servlet-mapping>
   <servlet-name>ImageProducerServlet</servlet-name>
   <url-pattern>/imageproducerservlet</url-pattern>
</servlet-mapping>

In this servlet's doGet I just wrote a System.out. Now From the JSF page I am calling that servlet as:

<img src="/imageProducerServlet" id="id"/>

I was expecting that it would print the System.out! But it doesn't.

The URL for the page where the img is added is:

http://localhost:7101/mycompany/faces/home

If I write in the address bar the follwoing URL:

http://localhost:7101/mycompany/imageproducerservlet

and press enter then the servlet's doGet is executing.

I am unable to find it's solution.

It will be very helpful if I get your suggestions.

Thanks and regards.

Tapas Bose
  • 25,780
  • 71
  • 202
  • 317

3 Answers3

3

If this is working:

http://localhost:7101/mycompany/imageproducerservlet

then you need your img tag to look like that:

<img src="/mycompany/imageProducerServlet" id="id"/>
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
3

Just say

<img src="imageProducerServlet" id="id"/>

or

<img src="/mycompany/imageProducerServlet" id="id"/>
jmj
  • 225,392
  • 41
  • 383
  • 426
1

You need to prepend the context path. You preferably won't hardcode it as the context path is a server-controlled setting. You can obtain it from the HTTP request as follows:

<img src="#{request.contextPath}/imageProducerServlet" id="id"/>

An alternative is to use the HTML <base> tag and set it to the URL of the context root. This way every URL which doesn't start with / will be relative to it.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452