Spring 启动自定义 favicon.ico 未显示

Spring Boot custom favicon.ico not showing

我知道这个问题已经在这里被反复问过,并且有多种解决方案。除了建议为此编写您自己的配置 bean 的那些之外,我已经尝试了其中的几个。我不想做所有这些只是为了显示一个小图标,它接缝有点矫枉过正。但我无法让它工作。这些是我到目前为止尝试过的解决方案。

  1. 只需在静态资源下添加 favicon.ico,它应该可以工作....但没有。
  2. spring.mvc.favicon.enabled=false in application.properties,根本没有显示图标(我想这就是重点)。
  3. 尝试了 2 个将网站图标作为 link 包含在 html 页面中的示例。像这样: <link rel="icon" type="image/png" href="favicon.png" /> <link rel="icon" type="image/x-icon" href="favicon.ico" />

这些都不起作用。

  1. 尝试将我自己的网站图标重命名为其他名称并按上述方式引用它。不起作用。

在浏览器中检查页面时,尽管没有显示图标,但有时我完全没有打印出任何错误,或者我收到一条错误消息,说 GET http://localhost:8080/myapp/favicon.png 404 () 将类型引用为 JSON(我觉得很奇怪)。

我 运行 没有想法,所以如果有人能告诉我为什么这不起作用,请告诉我。我是否可能忘记了那些神奇的 spring 注释之一? 这就是我的主要 class 的样子。

@SpringBootApplication 
@ComponentScan
@Configuration
@EnableWebMvc
public class JobengineMonitorApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(JobengineMonitorApplication.class, args);
    }

 }

我正在使用 thymeleaf 作为模板引擎

我也有这个与 Spring Boot 配置并且正在工作

<link rel="shortcut icon" type="image/png" th:href="@{/img/favicon.png}"/>

以及resources/public/img

下的favicon.png

好的,现在看来可以使用了。当然,我在咆哮之后设法让它工作了:)。

反正我是这么做的

  1. 从主程序中删除@EnableWebMvc class
  2. 根据 url 添加 ../ 到 href,例如 /index 很好,但 /edit/something.html 不是

抱歉浪费大家的时间,但希望这对像我这样的新手有用

我通过将 favicon.ico 放入 main/resource/static 并将这行添加到我的安全配置中解决了这个问题

 httpSecurity
            .authorizeRequests()
                .antMatchers( "/favicon.ico").permitAll()

我发现我必须将我的 favicon.ico 文件放在:

src/main/resources/public

将您的 favicon.png 放在 src/main/resources/public 下,并将其添加到 *.html 页面的 header 部分

 <link rel="shortcut icon" type="image/png" th:href="@{favicon.png}"/>

出于某种原因,.ico 格式无法正常工作。我只是放置了一个 png 图像,spring 自动选择了图标。

我把png图片放在了\src\main\resources\public

Spring 靴子 + 百里香

如果有人在使用较新版本的 Spring(在我的例子中是 spring boot 2.4.4)时遇到同样的问题,下面是适合我的场景:

  1. 将 favicon.ico 放入 /resources/static 文件夹。我也试过把它放在 /resourses/ 文件夹里,效果也很好,所以不用太担心文件夹。
  2. 在您的配置文件夹中创建一个 FaviconConfiguration,内容如下:
@Configuration
public class FaviconConfiguration {

    @Bean
    public SimpleUrlHandlerMapping customFaviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Integer.MIN_VALUE);
        mapping.setUrlMap(Collections.singletonMap(
                "/static/favicon.ico", faviconRequestHandler()));
        return mapping;
    }

    @Bean
    protected ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler
                = new ResourceHttpRequestHandler();
        requestHandler.setLocations(Collections.singletonList(new ClassPathResource("/")));
        return requestHandler;
    }
}
  1. 如果您使用 Spring 安全性,请不要忘记通过将以下代码添加到您的 SpringSecurityConfiguration[= 来为您的网站图标资源添加 antMatcher 34=](如上文所述):
.antMatchers("/static/favicon.ico").permitAll()
  1. 在您的 html 中 显式 将 link 用于您的自定义图标。为此,只需按以下方式将以下 link 放入 each 页面的 <head> 部分(我在这里使用了 thymeleaf ):
<head>
    ...
    <link rel="icon" type="image/ico" th:href="@{../static/favicon.ico}">
    ...
</head>

尝试用 href 替换 th:href。它对我有用。

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

我将简单的 .png 下载的图标保存为 src/main/resources/static/favicon.ico

我无法让它显示,直到我尝试了另一个浏览器并且它工作正常 - 所以尝试清除浏览器缓存,或者尝试在另一个浏览器上测试

我遇到了同样的问题并通过删除 @EnableAdminServer 注释解决了这个问题

我对此采取了一种非正统的方法。

@RestController
@RequestMapping(path = "/")
public class PublicController {
    private static final String FAVICON_PATH = "src/main/resources/static/favicon.ico";
    private static final byte[] IN_MEMORY_FAVICON;

    /**
     * This will prevent Bean/Application initialization if it catches an {@link IOException}.
     */
    static {
        try {
            IN_MEMORY_FAVICON = Files.readAllBytes(Paths.get(FAVICON_PATH));
        } catch (IOException e) {
            throw new RuntimeException(String.join("", FAVICON_PATH, " not found"));
        }
    }
    // Your code before
    @GetMapping(path="/favicon.ico", produces="image/x-icon")
    public byte[] favicon() {
        return IN_MEMORY_FAVICON;
    }
    // Your code after
}

如果您的应用程序 @EnableWebSecurity 确保您 permitAll()HttpMethod.GET 搜索网站图标资源。

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
// Your code before
httpSecurity.antMatchers(HttpMethod.GET, "/favicon.ico").permitAll()
// Your code after
return httpSecurity.build();

此外,如果您有任何自定义过滤器,例如 OncePerRequestFilter,通过覆盖 shouldNotFilter(HttpServletRequest request).

绕过应用于搜索图标图标的请求的过滤器可能很有用
@Component
public class MyCustomFilter extends OncePerRequestFilter {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    // Your code before
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return antPathMatcher.match( "/favicon.ico", request.getServletPath()));
    }
   // Your code after
}