Spring Boot的初步Web开发

更多信息:

本篇算是学习笔记

视频
尚硅谷
配置文件的信息
官方说明文档

编辑器:IntelliJ IDEA 2020.1



Web开发

创建SpringBoot应用,选中根据情况选择自己需要的模块;

在这里插入图片描述
SpringBoot已经默认帮我们把环境自动配置好了,只需要在配置文件中指定少量配置就可以运行起来。
然后根据自己的需要编写代码。

注意:这个过程的难点就是,你对Spring Boot帮你自动配置的原理是否了解,清楚Spring Boot的自动配置会对你的程序造成什么影响,再根据自己的程序适当的对Spring Boot的自动配置进行修改和扩展。

自动配置包
在这里插入图片描述
web模块
在这里插入图片描述
xxxxProperties:配置类来封装配置文件的内容;
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


SpringBoot对静态资源的映射规则

第一种映射规则

在这里插入图片描述
我们可以以webjar导入静态资源
https://www.webjars.org/
在这里插入图片描述

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

将要导入的代码选中,导入到项目的pom.xml文件中,然后再Reimport一下项目,就可以导入相关的jar包了。
在这里插入图片描述
在这里插入图片描述
其文件正好是符合/webjar/的结构的,所有 /webjars/ ,都去 classpath:/META-INF/resources/webjars/ 找资源;

例如:项目启动后,我们可以访问localhost:8080/webjars/jquery/3.4.0/jquery.js
localhost:8080/webjars/jquery/3.4.0/jquery.slim.js

第二种映射规则

ResourceProperties.class

在这里插入图片描述

getStaticPathPattern()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
第二种映射规则:如果没人处理,"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

静态资源文件夹

“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”,
“/”:当前项目下的根路径
在这里插入图片描述

在这里插入图片描述

@Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
            return welcomePageHandlerMapping;
        }

getWelcomePage()

private Optional<Resource> getWelcomePage() {
            String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

在这里插入图片描述
getResourceLocations()在这里插入图片描述
欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射

​localhost:8080/ 也符合"/**",静态资源文件夹下找index页面

#自己定义静态文件目录,以前的默认配置静态文件目录路径就不行了
spring.resources.static-locations=classpath:/hello/,classpath:/atguigu/

模板引擎

例子:JSP、Velocty、Thymeleaf
在这里插入图片描述

Thymeleaf

Thymeleaf is a modern server-side Java template engine for both web
and standalone environments.

Thymeleaf’s main goal is to bring elegant natural templates to your
development workflow — HTML that can be correctly displayed in
browsers and also work as static prototypes, allowing for stronger
collaboration in development teams.

With modules for Spring Framework, a host of integrations with your
favourite tools, and the ability to plug in your own functionality,
Thymeleaf is ideal for modern-day HTML5 JVM web development — although
there is much more it can do.

作用

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

导入Thymeleaf的启动器

Github: https://github.com/thymeleaf/thymeleaf/releases

版本切换
<properties>
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
		<!-- thymeleaf2   layout1-->
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

启动器
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在这里插入图片描述

在这里插入图片描述

Thymeleaf的使用和语法

自动配置下的Thymeleaf
在这里插入图片描述
在这里插入图片描述
ThymeleafAutoConfiguration在这里插入图片描述
ThymeleafProperties在这里插入图片描述
Thymeleaf使用文档
链接:https://pan.baidu.com/s/1HplunU3OVn323_xp6f8dcA
提取码:1854

例子

HelloController 提供hello的数据

package com.atguigu.springboot04webrestfulcrud.controller;


import com.atguigu.springboot04webrestfulcrud.exception.UserNotExistException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Map;

@Controller
public class HelloController {

    /*
    @RequestMapping({"/","/index.html"})
    public String index(){
        return "index";
    }
    */

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(@RequestParam("user") String user) {
        if (user.equals("aaa")) {
            throw new UserNotExistException();
        }
        return "Hello World";
    }

    /**
     * 查出用户数据,在页面展示
     */
    @RequestMapping("/success")
    public String success(Map<String, Object> map) {
        map.put("hello", "<h1>hello</h1>");
        map.put("users", Arrays.asList("zhangsan", "lisi", "wangwu"));
        /*classpath:templates/success.html
        在ThymeleafProperties的属性里面定义了
        */
        return "success";
    }
}

在这里插入图片描述

语法规则

th:任意html属性;
作用:用数据来源去替换原生属性的值;

在这里插入图片描述
表达式语法

Simple expressions:(表达式语法)
	//比较常用
    Variable Expressions: ${...}:获取变量值;OGNL;
    		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}
            3)、内置的一些工具对象:
#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: *{...}:选择表达式:和${}在功能上是一样;
    	补充:配合 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;
    		@{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表达式
    		<div th:insert="~{commons :: main}">...</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、付费专栏及课程。

余额充值