FreeMarker
在 FreeMarkerProperties 类中规定了 web 相关文件需要放到名为 templates 的包下
public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
同时,也规定了后缀为 .ftlh ,这个是可以修改的
public static final String DEFAULT_SUFFIX = ".ftlh";
在配置文件中修改(web文件的路径、前缀、编码等也是可以改的)
# profile配置
spring:
freemarker:
# 修改freemarker里规定的后缀
suffix: .ftl
# 文件路径
template-loader-path: classpath:/templates/
# 编码
charset: utf-8
Thymeleaf
和freemarker类似,自带缓存,建议关闭,动静分离
spring:
thymeleaf:
encoding: UTF-8
suffix: .html
prefix: classpath:/templates/
# 页面缓存
cache: false
常用语法讲解
<h1 th:text="${value}">默认的文本</h1>
在后端未传递数据时,标签内显示默认的文本,接收到相应的动态数据后默认文本被渲染成 value 对应的值
<meta th:content="${content}" content="默认的content">
动态调整 content 的值
<div th:object=${obj}>
div标签接收对象,标签内可用*{value}
取对象的变量
<p th:if="${value}">文本</p>
如果 value 是true就显示文本,是false就不显示
<p th:each="abc:${list}" th:rext="${abc}"></p>
遍历list,里面的每一个元素叫abc
这段用p标签遍历输出每一个abc
<link rel="stylesheet" th:href="@{a.css}">
用@取静态资源,js同理
静态资源
资源配置类的源码里有这样一段话
Locations of static resources. Defaults to classpath:[/META-INF/resources/, /resources/, /static/, /public/].
所以在资源目录 resources 下新建/META-INF/resources/
或者/resources/
或者 /static/
或者/public/
可以存放静态资源,否则访问静态资源会报 404 错误
当然也可以自己修改默认的静态资源路径
spring:
resources:
# 静态资源路径
static-locations: 路径写在这里
打包和部署
打包
在maven里,不论通过什么方式,执行: 1. 清空 2. 编译 3. 打包
如果是java项目默认打 jar 包,快照版本1.0,生成在 target 目录下
如果想要打包 web 项目,打成 war 包,可以在 pom.xml 里修改
注意!!!
但是!!!war 包需要在 tomcat 容器里运行,springboot 自带 tomcat,所以需要在打包时忽略掉内嵌的 tomcat
在依赖里修改 tomcat 的作用域,provide 的意思是只在编译和测试时使用,运行时会变得无效
<!--打包忽略tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
打 war 的名字也是可以手动修改的:
<build>
<finalName>springboot</finalName>
</build>
部署
jar包
用cmd调用命令,path是jar包的绝对路径
java -jar path
war
在 tomcat 里打开war包。
由于web项目在ssm里是通过web.xml启动的,springboot里没有,所以需要以下操作:
- 启动类(注解为@SpringBootApplication)继承 SpringBootServletInitializer 类
- 重写方法
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Starter.class);
}
返回值的意思是告诉web容器(builder)要读取的资源(sources)的启动类是什么(Starter.class)