Image Src for calling a Servlet

浪尽此生 提交于 2019-12-31 07:41:28

问题


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.


回答1:


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"/>



回答2:


Just say

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

or

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



回答3:


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:

  • How get the base URL?


来源:https://stackoverflow.com/questions/9835061/image-src-for-calling-a-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!