springboot07-springboot与web开发

一、web开发

1、使用SpringBoot步骤:

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

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

3、自己编写业务代码;

自动配置原理:

XXXAutoConfiguration:帮我们给容器中自动配置组件;
xxxxxProperties:配置类来封装配置文件的内容;

2、SpringBoot对静态资源的映射规则

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

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

1)、所有/webjars/**,都去classpath:/META-INF/resources/webjars/下去找找资源;

​ webjars:以jar包的方式引入静态资源;https://www.webjars.org/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w88omsPA-1583755399526)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308144014481.png)]

添加到pow中即可:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6DcyrAMJ-1583755399537)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308144336645.png)]

所以如果我们要访问jQuery的资源文件:

localhost:8080/webjars/jquery/3.3.1/jquery.js就可以得到jq的资源文件

2)、“/**”访问当前项目的任何资源,(静态资源的文件夹)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pNCKkO1x-1583755399541)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308145654989.png)]

resources是根目录;

resources/resources第二个,依次

**比如:**我们现在要访问localhost:8080/abc 这样就是在静态资源下去找这个资源abc

3)、 欢迎页的设置:静态资源文件下的所有index.html页面;被“/**”映射;

​ localhost:8080/ 找到首页index.html

4)、 所有的**/favicon.ico都是在静态资源文件下去找。

3、模版引擎


JSP、Velocity、Freemarket、Thymeleaf;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XDeVsdqo-1583755399544)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308152101111.png)]

模版+数据 —>View

SpringBoot推荐使用Thymeleaf;

1、引入thymeleaf

<properties>
        <!--切换版本-->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <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和layout要适配。可以查看github上的对应

https://github.com/thymeleaf/thymeleaf

2、themleaf的使用语法

默认规则都封装在ThymeleafProperties这个class下面:

@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";
    //只要我们把html放到classpath:/templates/ ,这样thymeleaf就可以给我们自动渲染了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KCTQU6sQ-1583755399547)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308155621967.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r2QMtquv-1583755399549)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308155115509.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HyjI1vVF-1583755399552)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308155847810.png)]

只要我们把html放到classpath:/templates/ ,这样thymeleaf就可以给我们自动渲染了。

1、导入thymeleaf的名称空间

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

2、使用thymeleaf语法

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
成功
    <!--将div里面的文本内容设置为我们指定的值-->
    <div th:text="${hello}">
        这是显示欢迎信息
    </div>
</body>
</html>

3、语法规则


1)、th:text=“${}” 我们可以用我们后端传来的数据全部替换前端的显示;

<div th:text="${hello}" th:class="${}" th:align="${}">
        这是显示欢迎信息
    </div>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jqi6XWSH-1583755399554)(C:\Users\ouguangji\AppData\Roaming\Typora\typora-user-images\image-20200308160943497.png)]

th:each 遍历的
th:if /unless/switch/case 判断的
th:object 声明变量的
th:attr/attprepend/attrappend 任意属性修改,支持prepend 和append 前面添加 和后面添加
th:value/href/src 修改属性默认值
th:text/utext tex是转义的 utext是不转义的

2)、我们可以使用哪些表达式

Simple expressions:  //(表达式语法)
	Variable Expressions: ${...}  
		//获取变量值
		//1)、获取对象的属性、调用方法
		//2)、使用内置的对象:
			// #ctx: the context object.
			// #vars: the context variables.
			// #locale: the context locale.
			// #httpServletRequest: (only in Web Contexts) the HttpServletRequest object.
			// #httpSession: (only in Web Contexts) the HttpSession object.
		//3)、获取工具对象
#dates: utility methods for java.util.Date objects: formatting, component extraction, etc.
#calendars: analogous to #dates, but for java.util.Calendar objects.
#numbers: utility methods for formatting numeric objects.
#strings: utility methods for String objects: contains, startsWith, prepending/appending, etc.
#objects: utility methods for objects in general.
#bools: utility methods for boolean evaluation.
#arrays: utility methods for arrays.
#lists: utility methods for lists.
#sets: utility methods for sets.
#maps: utility methods for maps.
#aggregates: utility methods for creating aggregates on arrays or collections.
#messages: utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{} syntax.
#ids: utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
 
Selection Variable Expressions: *{...}  //配合th:object来获取*{name}=${person.name}
Message Expressions: #{...}            // 国际化
Link URL Expressions: @{...}          //定义url的
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)
发布了65 篇原创文章 · 获赞 29 · 访问量 6481

猜你喜欢

转载自blog.csdn.net/qq_41617848/article/details/104759901