Search code examples
tomcatweb.xmlfavicon

I can't display the favicon of my tomcat app


I put a favicon in my application root folder. But I can't display it. If I try to point the browser to it, I get 404.

Now I've this mapping for my servlet:

<servlet-mapping>
    <servlet-name>springDispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

and for now I can't change everything just for the favicon.... do you have any fix that is not so traumatic?


Solution

  • Depending on how you are serving the favorite icon to the users you could try something like the following.

    Create a new web application, lets call it IconDispatcher. The web.xml of this application can be blank. Then in your main application, the pages being displayed will have the following in the header

    <link rel="icon" type="image/ico" href="/IconDispatcher/favicon.ico"/>
    

    Since Tomcat will use the most specific path possible when serving the page, it should go to the new Icon application to get your favicon.ico file instead of looking in your main app.

    If you don't want to create a new webapp just to serve the image, you could create a new dispatcher which is only used to forward the requested resource back to the user. The url-mapping would be more specific so requests would go to the proper servlet

    <servlet-mapping>
        <servlet-name>iconDispatcher</servlet-name>
        <url-pattern>/Icon</url-pattern>
    </servlet-mapping>
    

    Another option could be to put a web server in front of Tomcat. By doing this, you can serve all your static content from the web server and only forward the non-static content to the tomcat server for processing.

    Hope these ideas help