spring boot thymeleaf 搭建前端hello

2019-02-27  本文已影响0人  赶圩归来阿理理

本工程,能做到如下:

文章主要分为两部分:项目搭建、项目打包


1,项目搭建

1.1 按照如下,创建一个包含thymeleaf的spring项目。
1.2 按照如下结构,创建文件。
工程结构
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实现WebMvcConfigurer是为了引用静态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>
    <!--实测,下面两种写法,都可以引入静态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
#热部署文件,页面不产生缓存,及时更新
spring.thymeleaf.cache=false
#静态文件找不到,要在这里配置下面这句话,然后还要实现WebMvcConfig配置类
#解决参考:https://blog.csdn.net/qq_37244513/article/details/82317560
spring.mvc.static-path-pattern=/static/**

这样,就可以启动工程了。
在浏览器访问得到如下结果:


image.png
2,打包
2.1,jar 包

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

mvn clean install -Dmaven.test.skip

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

然后通过java -jar 运行该jar包。
实测,html能够打开, 但是静态js文件没有加载成功,这里以后再看看为什么。

2.2,war包

需要将pom的打包方式修改为war
同时需要移除Tomcat插件

后续再补充


完成

上一篇下一篇

猜你喜欢

热点阅读