SpringBoot 入门学习笔记(二)Web 开发基础

1 Web 开发简介

使用 SpringBoot 进行 Web 开发流程:

  1. 创建项目,勾选所需业务模块
  2. 框架自动完成场景默认配置,仅需少量自定义配置
  3. 编写自身业务代码

可探究方向:默认配置细节、配置修改方式、功能扩展实现。

2 静态资源映射规则

底层依靠ResourcePropertiesWebMvcAutoConfiguration实现静态资源管控,可自定义缓存周期等参数。

逻辑

java 复制代码
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
     if (!this.resourceProperties.isAddMappings()) {
           logger.debug("Default resource handling disabled");
           return;
      } 
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
     customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
     .addResourceLocations("classpath:/META‐INF/resources/webjars/")
     .setCachePeriod(cachePeriod));
} 
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
      customizeResourceHandlerRegistration(registry
      .addResourceHandler(staticPathPattern)
      .addResourceLocations(this.resourceProperties.getStaticLocations())
      .setCachePeriod(cachePeriod));
}
}

1 webjars 资源访问

匹配路径:/webjars/** 资源真实位置:classpath:/META-INF/resources/webjars/ 以 jar 包引入前端依赖,官网:http://www.webjars.org/

引入 jQuery 示例依赖

XML 复制代码
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

访问地址:localhost:8080/webjars/jquery/3.3.1/jquery.js

2 普通静态资源访问

路径/**匹配全局请求,依次检索以下目录

  • classpath:/META‐INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/
  • 项目根路径

3 欢迎页规则

静态资源目录下index.html为默认首页,访问项目根路径自动匹配跳转。

网站图标配置

默认开启图标拦截,匹配**/favicon.ico请求,可通过配置关闭该功能。

3 模板引擎

常见模板引擎:JSP、Velocity、Freemarker、Thymeleaf SpringBoot 主推Thymeleaf,语法简洁易用。

1 引入依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

项目启动自动加载ThymeleafAutoConfiguration完成自动配置。

默认配置规则

java 复制代码
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

页面默认存放templates目录,后缀固定.html,配置文件可修改前缀、后缀、编码、缓存等参数。

基础使用演示

  1. html 页面引入命名空间
html 复制代码
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  1. 控制器封装数据
java 复制代码
@RequestMapping("/success")
public String hello(Model model){
    model.addAttribute("hello","<h1>zhangsan</h1>");
    return "success";
}
  1. 模板页面取值
XML 复制代码
<div  th:text="${hello}"> </div>

2 Thymeleaf 语法

1 标准表达式
  1. 变量表达式:${session.user.name} 获取域内数据
  2. 选择表达式:*{customer.name} 配合th:object使用
html 复制代码
<div th:object="${book}"> 
 <span th:text="*{title}">...</span> 
</div>
  1. 国际化表达式:#{main.title} 读取国际化配置文件
  2. URL 表达式:@{/order/list} 自动拼接路径,支持传参
html 复制代码
<a th:href="@{/order/details(id=${orderId})}"></a>
2 表达式支持语法
  • 字面量:文本、数字、布尔、null
  • 文本操作:字符串拼接、文本替换
  • 算术运算:加减乘除取模
  • 逻辑运算:与、或、非
  • 比较运算:大于、小于、等于判断
  • 条件运算:三元表达式、默认值赋值

示例

java 复制代码
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
3 常用标签汇总
关键字 作用 示例
th:id 替换元素 id <input th:id="'xxx' + ${collect.id}"/>
th:text 纯文本渲染 <p th:text="${collect.description}">
th:utext 解析 html 标签文本 <p th:utext="${htmlcontent}">
th:object 绑定实体对象 <div th:object="${session.user}">
th:value 表单赋值 <input th:value="${user.name}" />
th:each 循环遍历 <tr th:each="user:${users}">
th:if 条件判断展示 <a th:if="${userId == collect.userId}">
th:unless 反向条件判断 <a th:unless=${session.user != null}>Login</a>
th:href 跳转链接 <a th:href="@{/login}">
th:switch/th:case 多分支判断 多条件场景匹配
th:src 资源路径引入 <img th:src="@{/img/logo.png}" />
th:action 表单提交地址 <form th:action="@{/subscribe}">

标签综合测试页面

html 复制代码
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Title</title>
</head>
<body>
<div  th:text="${hello}" th:id="${hello.toUpperCase()}">xxxx</div>
<input th:value="${user.getUsername()}">
<hr>
<div th:object="${user}">
<span th:text="*{username}"></span>
</div>

<a th:if="${user.getAge() == 2}" >年龄</a>
<a  th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a>

<p th:if="${user.score >= 60 and user.score < 85}">B</p>
<p th:if="${user.score < 60}">C</p>
<p th:if="${user.score > 85}">优秀</p>

<span th:switch="${user.gender}">
    <p th:case="1">男</p>
    <p th:case="2">女</p>
</span>

<table>
    <tr th:each="a,aState:${uList}">
        <td th:text="${a.username}"></td>
        <td th:text="${a.password}"></td>
        <td th:text="${aState.index}"></td>
    </tr>
</table>
</body>
</html>

控制器数据封装代码

java 复制代码
@RequestMapping("/success")
public String hello(HttpServletRequest req, HttpSession httpSession, Model model){
    model.addAttribute("hello","<h1>renliang</h1>");
    User user = new User();
    user.setPassword("111");
    user.setUsername("renliang");
    user.setAge(1);
    user.setScore(78);
    user.setGender(2);
    List<User> uList = new ArrayList<>();
    for (int i = 0; i < 10; i++){
        User u = new User();
        u.setUsername("renliang"+i);
        u.setPassword("111"+i);
        uList.add(u);
    }
    model.addAttribute("user", user);
    model.addAttribute("uList", uList);
    return "success";
}

小结

本篇梳理了 SpringBoot Web 开发基础流程,讲解静态资源访问规则,同时完整学习 Thymeleaf 模板引擎的依赖引入、基础语法与常用标签用法,并搭配实操案例完成页面数据渲染,相关基础知识点到此结束,下篇继续讲解 SpringMVC 整合、容器配置等进阶内容。

相关推荐
小满Autumn11 分钟前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
袁小皮皮不皮7 小时前
1.HCIP BFD 学习笔记(优化版)
服务器·网络·笔记·网络协议·学习·智能路由器·ip
装不满的克莱因瓶7 小时前
【自动驾驶领域】学习 Cityscapes 数据集——城市街景语义理解的标准基准
人工智能·pytorch·python·深度学习·学习·机器学习·自动驾驶
一 乐8 小时前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
清辞8538 小时前
产品经理需求推进流程
大数据·深度学习·学习·产品经理
YM52e9 小时前
鸿蒙PC ArkTS 声明合并问题深度解析与最佳实践
学习·华为·harmonyos·鸿蒙·鸿蒙系统
海兰9 小时前
【实用程序】电商销售分析仪表盘 — 从零搭建一个AI参与的全栈数据洞察系统
人工智能·学习·算法
ken223210 小时前
在 Libreoffice Calc中输入自定义表情字符时,需要保存之后,才能正常显示
学习
zwenqiyu10 小时前
P5283 [十二省联考 2019] 异或粽子题解
c++·学习·算法
编程圈子10 小时前
电机驱动开发学习2. 直流无刷电机工作原理
驱动开发·学习