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 整合、容器配置等进阶内容。

相关推荐
知识分享小能手10 小时前
Flask入门学习教程,从入门到精通, Flask模板 — 完整知识点与案例代码 (3)
python·学习·flask
kgduu10 小时前
ethers.js学习笔记
javascript·笔记·学习
星幻元宇VR10 小时前
VR国防教育学习机:沉浸式国防教育新模式
科技·学习·安全·vr·虚拟现实
罗超驿10 小时前
1.JavaEE初阶学习安排+介绍计算机是如何工作的
java·学习·java-ee
会编程的土豆10 小时前
Docker 日常操作笔记(开发最常用命令)
笔记·docker·容器
05候补工程师10 小时前
【考研英语一·翻译专攻】长难句翻译的“分治策略”:从底层拆分到逻辑重构(1997-2010真题高频陷阱与红笔纠偏)
经验分享·笔记·考研·重构
有味道的男人10 小时前
Open Claw对接小红书笔记详情
数据库·笔记
楼田莉子11 小时前
C#学习:分支与循环
服务器·后端·学习·c#
KaSuo幻影11 小时前
电生理项目学习笔记
学习·电生理实验