spring boot thymeleaf 搭建前端hello world


本工程,能做到如下:

  • 借由spring boot,依賴thymeleaf搭建一個簡單的hello world前端項目
  • 能夠引入靜態(tài)js等文件
  • 能夠生成jar包或war包

文章主要分為兩部分:項目搭建、項目打包


1,項目搭建

1.1 按照如下,創(chuàng)建一個包含thymeleaf的spring項目。
1.2 按照如下結(jié)構(gòu),創(chuàng)建文件。
工程結(jié)構(gòu)
WebConfig為:
package com.lanlishi.thymeleaf.hello.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

使用WebConfig實現(xiàn)WebMvcConfigurer是為了引用靜態(tài)js文件。在嘗試多次失敗后,看到了這種方法,有效果。
來源:https://blog.csdn.net/qq_37244513/article/details/82317560
我自己是一知半解,這里僅做一個記錄。

MyController為:
@Controller
public class MyController {
    @RequestMapping("/{index}")
    public String index(@PathVariable String index) {
        System.out.println("訪問了:" + index);
        return index;
    }
}
hello.js為:
function sayHello() {
    alert("hello");
}
hello.html為:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--實測,下面兩種寫法,都可以引入靜態(tài)js文件-->
    <!--<script type="text/javascript" th:src="@{~/static/hello.js}"></script>-->
    <script src="/static/hello.js"></script>
</head>
<body>
    hello world
    <button onclick="sayHello()">按一下</button>
</body>
</html>
application.properties配置為:
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
#熱部署文件,頁面不產(chǎn)生緩存,及時更新
spring.thymeleaf.cache=false
#靜態(tài)文件找不到,要在這里配置下面這句話,然后還要實現(xiàn)WebMvcConfig配置類
#解決參考:https://blog.csdn.net/qq_37244513/article/details/82317560
spring.mvc.static-path-pattern=/static/**

這樣,就可以啟動工程了。
在瀏覽器訪問得到如下結(jié)果:


image.png
2,打包
2.1,jar 包

直接在terminal中,輸入如下命令:

mvn clean install -Dmaven.test.skip

看到 BUILD SUCCESS說明打包成功了。

然后通過java -jar 運行該jar包。
實測,html能夠打開, 但是靜態(tài)js文件沒有加載成功,這里以后再看看為什么。

2.2,war包

需要將pom的打包方式修改為war
同時需要移除Tomcat插件

后續(xù)再補(bǔ)充


完成

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容