【问题标题】:How to avoid Spring Boot Controller catching request for favicon?如何避免 Spring Boot Controller 捕获对 favicon 的请求?
【发布时间】:2021-09-28 16:30:35
【问题描述】:

我有以下控制器

@Controller
public class MyController {

    @GetMapping({"/", "/{name}"})
    public String hello(@PathVariable(required = false) String name) {
        System.out.println("Name: " + name);
        return "hello";
    }
}

还有这个目录结构

- resources
    - static
        - favicon.ico
    - templates
        - hello.html

当我通过浏览器GET http://localhost:8080/ 时,我的应用程序打印:

Name: null
Name: favicon.ico

所以/favicon.ico 的请求被我的控制器捕获,但我希望 Spring 处理此请求并返回放置在此处的 favicon.ico resources/static/favicon.ico

我认为应该有一种不需要添加几行配置的方法。

【问题讨论】:

  • 只是为了确保 - 包含 favicon.ico 的资源目录的路径是 src/main/resources/... ,对吗?
  • 谢谢@AjayKumar 通过将 放入我的 html 头部来解决它,顺便说一句我将 favicon 移动到 src/main/resources/static/images/

标签: spring spring-boot favicon


【解决方案1】:

您可以采取的一种方法是通过此property 禁用网站图标解析:

spring.mvc.favicon.enabled=false

【讨论】:

  • 不幸的是,这不起作用,这个属性在 Spring 5.3.9 中也被弃用了
【解决方案2】:

我必须在我的 html 头中包含 <link rel="icon" type="image/x-icon" href="images/favicon.ico">,它起作用了。 images 前缀不是必需的,但我将图标移到了他们的位置,因为我允许对 /images 的任何未经身份验证的请求,所以我不需要为 favicon.ico 设置额外的规则。这就是我当前的目录结构:

- resources
    - static
        - images
            - favicon.ico
    - templates
        - hello.html

s/o 到 Ajay Kumar 寻求帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2017-09-24
    • 2017-10-02
    • 2018-04-01
    • 1970-01-01
    • 2018-10-25
    • 2019-08-03
    相关资源
    最近更新 更多