Spring Boot(三)—— web 开发

一、简介

使用SpringBoot;

1)、创建SpringBoot应用,选中我们需要的模块;

2)、SpringBoot 已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

3)、自己编写业务代码;

二、Spring Boot 对静态资源的映射规则

image-20210818115611217

WebMvcAutoConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
        return;
    }
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
        customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                             .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
}

(1)、所有 /webjars/,都在 classpath:/META /resources/webjars/ 找资源

webjars:以jar包的方式引入资源

<!--引入 jquery 的webjar-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

image-20200804214331748

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

(2)、“/**“访问当前项目的任何资源,添加自定义的资源文件

image-20200804215533438

获取静态资源路径,追溯方法,得到:

image-20200804215656301

将静态资源放在以下一个文件夹中,项目就能访问到

"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/" 
"/": 当前项目的根路径

// classpath就是创建项目自带的resources文件夹

(3)、欢迎页,静态资源文件夹下的所有 index.html页面

在上面任意一个静态资源文件夹下,写 index.html 文件。localhost:8080访问出现的首页就是这个文件

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

(4)、图标文件,静态资源文件夹下的 favicon.ico 文件

访问时,图标不出来?重启项目,clean,浏览器中 ctrl+f5。一套走完

image-20210818120735482

(5)、配置静态资源文件夹路径

spring.resources.static-locations=classpath:/hello/,classpath:/world/

配置后,默认的静态资源文件夹路径,将不再生效

三、模板引擎

1. Thymeleaf使用 和 语法

@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 就能自动渲染

导入 Thymeleaf 名称空间:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

语法:

(1)、语法规则

(官方文档usingthymeleaf,10 Attribute Precedence)

th:text,替换当前元素里面的文本属性

th:任意html属性,来替换原生属性的值

image-20200805140939045

例:

    <!--  转义特殊字符  -->
    <div th:text="${hello}"></div>
    <!--  不转义特殊字符  -->
    <div th:utext="${hello}"></div>
    <hr>
    <!-- 循环遍历 -->
    <h4 th:text="${user}" th:each="user:${users}"></h4>
    <hr>
    <h4>
        <!-- 行内写法 -->
        <span th:each="user:${users}">[[${user}]]</span>
    </h4>
(2)、表达式

(官方文档usingthymeleaf,4 Standard Expression Syntax)

Simple expressions: (表达式语法)
    Variable Expressions: ${...}	获取变量值
    	1)、获取对象的属性、调用方法
    	2)、使用内置的基本对象
    	#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.
        例:
        	${session.foo} // Retrieves the session atttribute 'foo'
            ${session.size()}
            ${session.isEmpty()}
            ${session.containsKey('foo')}
            ...
       	3)、内置的工具对象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in 	the same way as theywould 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).
		例:
		${#strings.isEmpty(name)}
        ${#strings.arrayIsEmpty(nameArr)}
        ${#strings.listIsEmpty(nameList)}
        ...
        
    Selection Variable Expressions: *{...}	选择表达式,和${}在功能上是一样的
    	补充:配合 th:object="${session.user}"
    	<div th:object="${session.user}">
            <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
            <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
            <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
        </div>
    Message Expressions: #{...}	获取国际化内容
    Link URL Expressions: @{...}	定义URL
    	<a href="details.html"			  		th:href="@{/order/details(orderId=${o.id},order2=${o.name})}">view</a>
    Fragment Expressions: ~{...}	片段文档引用
    	<div th:insert="~{common :: #topbar}"></div>
    
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: _
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值