-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
  • 27,586
  • 72
  • 207
  • 327

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,335,956
  • 823
  • 8,931
  • 9,049
3

Just say

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

or

<img src="/mycompany/imageProducerServlet" id="id"/>
jmj
  • 232,312
  • 42
  • 391
  • 431
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
  • 1,040,783
  • 362
  • 3,548
  • 3,513