Spring Boot学习笔记-4

Spring Boot学习笔记-4

一、Web开发

1.创建Spring Boot应用,选择相应模块
2.在配置文件指定相应配置(其它由SpringBoot自动配置)
3.编写业务代码


(1)静态资源映射

1.所有/webjars/,都去classpath:/META-INF/resources/webjars/下找相关资源
webjars:以jar包形式引入静态资源 (https://www.webjars.com/)

//WebMvcAutoConfiguration
if (!registry.hasMappingForPattern("/webjars/**")) {
	customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
    .addResourceLocations("classpath:/META-INF/resources/webjars/")
    .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

在这里插入图片描述
在这里插入图片描述

http://localhost:8080/webjars/jquery/3.5.1/jquery.js

2.无处理自动从下列文件夹查找静态资源
例如localhost:8080/abc若abc无处理则去下列目录查找

  1. “classpath:/META-INF/resources/”
  2. “classpath:/resources/”
  3. “classpath:/static/”
  4. “classpath:/public/”
  5. “/” 当前项目根路径

3.欢迎页(localhost:8080)从静态资源文件夹(见2)中查找index.html文件

//welcomePageHandlerMapping().getWelcomePage().getIndexHtml()
private Resource getIndexHtml(String location) {
	return this.resourceLoader.getResource(location + "index.html");
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
首页
</body>
</html>

在这里插入图片描述

以上为Spring Boot默认静态资源查询地址,可以在配置文件中修改:

spring.resources.static-locations=XXX

(2)模板引擎

将模板中动态值的表达式与数据结合输出
JSP,Velocity,Freemarker,Thymeleaf

在这里插入图片描述

Spring Boot推荐使用Thymeleaf

1.配置依赖+版本
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
//layout2以上版本才支持thymeleaf3
<properties>
    <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
2.取值
@EnableConfigurationProperties(ThymeleafProperties.class)
//ThymeleafProperties
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	public static final String DEFAULT_SUFFIX = ".html";
//将html文件放在classpath:/templates/下即可自动渲染
//导入thymeleaf名称空间(开启语法提示)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功~</h1>
<div id="div01" class="myDiv" th:id="${Hello}" th:class="${Hello}" th:text="${Hello}">欢迎信息</div>
</body>
</html>
@RequestMapping("/success")
public String success(Map<String,Object> map)
{
    map.put("Hello","你好");
    return "success";
}

静态页面

在这里插入图片描述

服务器启动:

在这里插入图片描述

3.语法规则
1)取值
//在div模块中
//用XXX替换该属性的原生值(一般是用"${XXX}"取值)
<div th:任意html属性 = "XXX"></div>

在这里插入图片描述

1.片段包含
2.遍历
3.条件判断
4.变量声明
5.任意属性修改(支持前后添加)
6.修改指定属性默认值
7.修改标签体内容(text转义特殊字符,utext不转义)
8.声明片段

2)表达式
Simple expressions:

    //OGNL,获取变量值
    Variable Expressions: ${...}    
        1.获取对象属性
            ${person.father.name}
            ${person['father']['name']}
            ${countriesByCode.ES}
            ${personsByName['Stephen Zucchini'].age}
            ${personsArray[0].name}

        2.调用方法
            ${person.createCompleteName()}
            ${person.createCompleteNameWithSeparator('-')}

        3.使用内置基本对象
            #ctx : the context object.
            #vars: the context variables.
            #locale : the context locale.
            #request : (only in Web Contexts) the HttpServletRequest object.
            #response : (only in Web Contexts) the HttpServletResponse object.
            #session : (only in Web Contexts) the HttpSession object.
            #servletContext : (only in Web Contexts) the ServletContext object.
            //使用方式见附录

        4.使用内置工具对象
            #execInfo : information about the template being processed.
            #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
            #uris : methods for escaping parts of URLs/URIs
            #conversions : methods for executing the configured conversion service (if any).
            #dates : methods for java.util.Date objects: formatting, component extraction, etc.
            #calendars : analogous to #dates , but for java.util.Calendar objects.
            #numbers : methods for formatting numeric objects.
            #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
            #objects : methods for objects in general.
            #bools : methods for boolean evaluation.
            #arrays : methods for arrays.
            #lists : methods for lists.
            #sets : methods for sets.
            #maps : methods for maps.
            #aggregates : methods for creating aggregates on arrays or collections.
            #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration)
            //使用方式见附录

    //选择表达式
    Selection Variable Expressions: *{...}
        <div th:object="${session.user}">
        //以下两种写法含义相同(与${}的不同):
        <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
        <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>

    //获取国际化内容
    Message Expressions: #{...}

    //定义URL
    Link URL Expressions: @{...}

    //片段引用表达式
    Fragment Expressions: ~{...}

//字面量
Literals:
    Text literals: 'one text' , 'Another one!' ,…
    Number literals: 0 , 34 , 3.0 , 12.3 ,…
    Boolean literals: true , false
    Null literal: null
    Literal tokens: one , sometext , main ,…

//文本操作
Text operations:
    String concatenation: +
    Literal substitutions: |The name is ${name}|

//数学运算
Arithmetic operations:
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -

//布尔运算
Boolean operations:
    Binary operators: and , or
    Boolean negation (unary operator): ! , not

//比较运算
Comparisons and equality:
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )

//条件运算
Conditional operators:
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

//特殊操作
Special tokens:
    No-Operation: _
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功~</h1>
<div th:text="${Hello}"></div>
<div th:utext="${Hello}"></div>
<hr/>
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>
<h4>
    <span th:text="${user}" th:each="user:${users}"></span>
</h4>
</body>
</html>

在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值