简体   繁体   English

使用Thymeleaf在Spring Boot中加载静态资源

[英]Load static resource in Spring Boot with Thymeleaf

I want to make page using thymeleaf . 我想用thymeleaf来制作页面。 But I have some problem with the static files. 但我对静态文件有一些问题。 I've investigated questions( 1 , 2 , 3 ) with similar problem, but it didn't help me. 我调查过的问题( 123有类似的问题),但它并没有帮助我。

I use Spring Boot framework in the application. 我在应用程序中使用Spring Boot框架。 My files look like: 我的文件看起来像: 在此输入图像描述

test.html 的test.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script src="js/test.js" th:src="@{/test.js}"/>
</head>
<body>
<button onclick="testFunction('test value')">Button</button>
</body>
</html>

test.js test.js

function testFunction(test) {
    console.log(test);
}

Configuration class 配置类

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
        super.addResourceHandlers(registry);
    }
}

And problem, when I load test.html file with javascript not loaded. 和问题,当我加载没有加载javascript的test.html文件。

@GetMapping(value = "web/test")
public String getTestHtmlPage() {
    return "test";
}

在此输入图像描述

/api/v1 is a configuration in application.properties => server.servlet-path=/api/v1 /api/v1application.properties => server.servlet-path=/api/v1

What do I do wrong? 我做错了什么? Can you help me? 你能帮助我吗?

Thanks all! 谢谢大家!

For a better understanding of registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/"); 为了更好地理解registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");

I wrote a more thorough answer here that discusses invalid resource location mappings. 在这里写了一个更全面的答案 ,讨论了无效的资源位置映射。 It didn't receive any upvotes, so I hope it's not terrible. 它没有收到任何赞成票,所以我希望它并不可怕。 :-) :-)

In short, with the way you're mapping classpath:/static/js/ , and then accessing, /js/test.js , you're telling Spring to look in /static/js/js/test.js . 简而言之,通过映射classpath:/static/js/的方式classpath:/static/js/ ,然后访问/js/test.js ,你告诉Spring查看/static/js/js/test.js

What you probably want is classpath:/static/ . 你可能想要的是classpath:/static/ In that case, when you try to access /js/test.js , it's looking in /static/js/test.js for the file instead. 在这种情况下,当您尝试访问/js/test.js ,它会在/static/js/test.js查找该文件。

As for Thymeleaf, I've never used it, but docs indicate you should load scripts with th:src instead of th:href . 至于Thymeleaf,我从来没有使用它,但文档表明你应该用th:src而不是th:href加载脚本。 th:href appears to only be for HTML content. th:href似乎只适用于HTML内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM