springboot web开发与thymeleaf


springboot web开发

1、静态资源

1.在springboot,我们可以使用以下方式处理静态资源

  • webjars
    localhost: 8080/webjars/
  • public, static, /**, resources
    localhost: 8080/

2.优先级: resources>static (默认) >public

以下四个目录存放的静态资源可以被我们识别

"classpath:/META-INF/resources/"
"classpath:/resources/" (一般这里放 上传 的资源文件)
"classpath:/static/"(一般这里放 静态 的资源文件,图片,js等)
"classpath:/public/"(一般这里放 公共 的资源文件,大家都会访问的)

优先级 : 由上到下

我们可以在resources根目录下新建对应的文件夹,都可以存放我们的静态文件

访问 : http://localhost:端口号/上述路径下的文件名即可,不需要具体的 static、public 这一级的文件夹名

2.自定义静态资源路径

也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置

   spring.resources.static-locations=classpath:/coding/,classpath:/self/

一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了

3.首页处理

templates目录下的所有页面,只能通过controller来跳转!这个需要模板引擎的支持! thymeleaf
继续向下看源码!可以看到一个欢迎页的映射,就是我们的首页!

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // getWelcomePage 获得欢迎页
        this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;
}

点进去继续看

private Optional<Resource> getWelcomePage() {
    String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
    // ::是java8 中新引入的运算符
    // Class::function的时候function是属于Class的,应该是静态方法。
    // this::function的funtion是属于这个对象的。
    // 简而言之,就是一种语法糖而已,是一种简写
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
// 欢迎页就是一个location下的的 index.html 而已
private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

::是java8 中新引入的运算符

结论:欢迎页,静态资源文件夹下的所有 index.html 页面;被 / 映射
比如访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html

4、关于网站图标说明

与其他静态资源一样,Spring Boot在配置的静态内容位置中查找favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。

关闭SpringBoot默认图标

#关闭默认图标
spring.mvc.favicon.enabled=false

Thymeleaf

1、模板引擎

  1. 在 Spring 及之前,更加倾向于使用 jsp 页面。
  2. 但是在 SpringBoot 中,推荐使用 HTML 页面。
  3. SpringBoot这个项目首先是以jar的方式,不是war,第二,我们用的还是嵌入式的Tomcat
    但是HTML页面不能写JAVA代码,那么怎么与后端交互呢?
  4. SpringBoot推荐你可以来使用模板引擎:
    其实jsp就是一个模板引擎,还有用的比较多的freemarker等
    SpringBoot给我们推荐的Thymeleaf

模板引擎的思想都是一样的,如下图:
在这里插入图片描述

2、引入Thymeleaf

Thymeleaf 官网

Thymeleaf 在Github 的主页

Spring官方文档:找到我们对应的版本

找到对应的pom依赖:可以适当点进源码看下本来的包!

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二种方式
 <!--thymeleaf模板-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>

Maven会自动下载jar包,我们可以去看下下载的东西;

3、Thymeleaf分析

Thymeleaf的自动配置类:ThymeleafProperties

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
}
  1. 我们可以在其中看到默认的前缀和后缀!
  2. 我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。
  3. 使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!

4、thymeleaf简单使用

测试

1、编写一个TestController

package com.zhu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

//在templates目录下的所有页面,只能通过controller来跳转
//这个需要模板引擎的支持!thymeleaf
@Controller
public class IndexController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hello,springboot");
        return "test";
    }
}
  • templates目录下的所有页面,只能通过controller来跳转
  • 这个需要模板引擎的支持!thymeleaf

2、使用thymeleaf,需要在html文件中导入命名空间的约束

xmlns:th="http://www.thymeleaf.org"

3、编写一个测试页面 test.html 放在 templates 目录下

  • 所有的html元素都可以被thymeleaf替换接管: th:元素名
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--所有的html元素都可以被thymeleaf替换接管:    th:元素名-->
<div th:text="${msg}"></div>
</body>
</html>

5、Thymeleaf 语法学习

1、可以使用任意的th:attr来替换Html中原生属性的值!
在这里插入图片描述

2、我们能写哪些表达式呢?

Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
    1)、获取对象的属性、调用方法
    2)、使用内置的基本对象:#18
         #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.

    3)、内置的一些工具对象:
      #execInfo : information about the template being processed.
      #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.
==================================================================================

  Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
  Message Expressions: #{...}:获取国际化内容
  Link URL Expressions: @{...}:定义URL;
  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: _

练习测试:

1、 我们编写一个Controller,放一些数据

   @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","<h1>hello,springboot</h1>");
        model.addAttribute("users", Arrays.asList("ztb","java","C++"));
        return "test";
    }

2、测试页面取出数据

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--所有的html元素都可以被thymeleaf替换接管:    th:元素名-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
<hr>
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值