You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Spring Boot Controller捕获favicon.ico请求

问题原因

你配置的@GetMapping({"/", "/{name}"})使用了顶层通配路径/{name},会匹配所有无对应精确映射的顶层GET请求,浏览器自动发起的/favicon.ico请求没有找到精确映射,就被该方法捕获,没有进入Spring默认的静态资源解析流程。

极简实现方案(二选一即可,无需大量配置)

方案1:修改路径匹配规则(仅改1行代码)

给路径变量增加正则限制,仅匹配不带后缀的路径,自动过滤掉带.ico后缀的favicon请求,Spring会自动走静态资源逻辑返回static目录下的文件:

// 原代码
// @GetMapping({"/", "/{name}"})
// 修改为如下,正则表示仅匹配不包含点的路径变量
@GetMapping({"/", "/{name:^[^.]+$}"})
public String hello(@PathVariable(required = false) String name) {
    System.out.println("Name: " + name);
    return "hello";
}

方案2:新增精确favicon映射(优先级更高,不影响原有业务逻辑)

直接新增一个favicon专属的请求处理方法,精确路径的映射优先级高于通配路径,会优先命中:

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// 放在你的MyController类中即可
@GetMapping("/favicon.ico")
@ResponseBody
public ResponseEntity<Resource> getFavicon() {
    Resource resource = new ClassPathResource("static/favicon.ico");
    return ResponseEntity.ok()
            .contentType(MediaType.valueOf("image/x-icon"))
            .body(resource);
}

两种方案改完重启项目即可生效,/favicon.ico请求会直接返回static目录下的图标文件,不会再进入hello方法。


内容的提问来源于stack exchange,提问作者tonik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:36:05