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));
}

Spring Boot学习笔记-4_第1张图片
Spring Boot学习笔记-4_第2张图片

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");
}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页title>
head>
<body>
首页
body>
html>

Spring Boot学习笔记-4_第3张图片

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

spring.resources.static-locations=XXX

(2)模板引擎

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

Spring Boot学习笔记-4_第4张图片

Spring Boot推荐使用Thymeleaf

1.配置依赖+版本

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
//layout2以上版本才支持thymeleaf3
<properties>
    <thymeleaf-layout-dialect.version>2.2.2thymeleaf-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名称空间(开启语法提示)

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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";
}

静态页面

Spring Boot学习笔记-4_第5张图片

服务器启动:

Spring Boot学习笔记-4_第6张图片

3.语法规则

1)取值
//在div模块中
//用XXX替换该属性的原生值(一般是用"${XXX}"取值)
div>

Spring Boot学习笔记-4_第7张图片

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: *{...}
        
//以下两种写法含义相同(与${}的不同):

Name: Sebastian.

Name: Sebastian.

//获取国际化内容 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: _

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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>

Spring Boot学习笔记-4_第8张图片


你可能感兴趣的:(SpringBoot学习笔记,java,spring,boot)