Search code examples
javaspringweb-applicationsspring-mvcfavicon

How to intercept all requests for favicon.ico in SpringMVC?


I've got a controller that will respond to /favicon.ico appropriately.

But I just realized that when you're in a sub page such as /subpage/index.html the browser (at least chrome) is requesting /subpage/favicon.ico.

Is there a clean way to just respond to all favicon.ico requests? I'd rather not redirect all .ico requests if possible, but if that's the best solution, perhaps.


Solution

  • Ok, one option I just finagled out of my fingers using the controller:

    @Controller
    @RequestMapping("/")
    public class PublicPagesController extends BaseController {
        @RequestMapping("**/favicon.ico")
        public String favIconForward(){
            return "forward:/public/img/fav.ico";
        }
    
        // ...other stuff...
    }
    

    Note the need to use the file name fav.ico, if you try this using file name favicon.ico you'll get an infinite loop.

    I previously was using this approach for just @RequestMapping("favicon.ico")

    And this assumes you're serving static content out of /public with something like this:

    <mvc:resources mapping="/public/**" location="/public/"/>