SpringBoot学习:4、SpringBoot与Web开发

总体步骤

1、创建SpringBoot应用,选中我们需要的模块;
2、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来了
3、自己编写业务代码

静态资源映射规则

1、所有/webjars/**,都去classpath:/META-INF/resources/webjars/ 里去找资源

什么是webjars?web libraries in jars,jar包形式的web资源,https://www.webjars.org/

示例:

首先引入依赖:

<!-- 引入jquery的webjar -->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

然后我们看jar包的目录结构,访问/webjars/jquery/3.3.1/jquery.js即可
在这里插入图片描述
2、"/**"访问当前项目的任何资源

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/

3、欢迎页

静态资源文件夹下的所有index.html页面,被/**映射。不过我们一般放在/resources/static下

4、页面图标,会找所有的**/favicon.ico,也就是说在所有的静态资源文件夹下找。一般放在/resources下或者/resources/static/下

模版引擎

JSP、Velocity、Freemarker、Thymeleaf;

模版引擎的作用:
在这里插入图片描述
SpringBoot推荐的Thymeleaf:语法更简单,功能更强大

1、引入thymeleaf

<!-- 引入thymeleaf模版引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

为了使用高级版的thymeleaf,需要在properties标签中添加相关属性设置

<properties>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

thymeleaf3主程序,layout2以上版本

2、thymeleaf语法

在这里插入图片描述
1、默认前缀classpath:/templates/,默认后缀.html,也就是说,只要我们把html页面放到classpath:/templates/下面,thymeleaf就能自动渲染了。

注意:此时如果想让thymeleaf渲染,不要加@RequestBody

@RequestMapping("/success")
public String success() {
    return "success";
}

这样的话,输入localhost:8080/success的时候就能转到访问templates下面的success.html页面了。

2、使用thymeleaf

  • 导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • 导入thymeleaf语法
<!-- th:text将div的内容设置为指定内容 -->
 <div th:text=${msg}></div>

Thymeleaf语法

1、th:text:改变当前元素里面的文本内容

其实th:html任意属性都可以用来替换html的原生属性,例如th:idth:class分别可以用来替换id属性的值和class属性的值

2、表达式

${}:

  • 获取对象的属性、调用方法
  • 使用内置的基本对象
  • 使用内置的一些工具对象

*{}:和${}功能一样,只是增加了一个功能,就是选择对象的功能,要配合th:object进行使用,这个功能可以帮助节省代码。

#{}:获取国际化的内容

@{}:用来定义超链接的

~{}:片段引用的表达式

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值