本文共 8247 字,大约阅读时间需要 27 分钟。
本人是个新手,写下博客用于自我复习、自我总结。 如有错误之处,请各位大佬指出。 学习资料来源于:尚硅谷
1)、创建SpringBoot应用,选中我们需要的模块;
2)、SpringBoot默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来; 3)、自己编写业务代码;先像前几篇文章一样,创建一个SpringBoot应用,这次选中web模块。
生成好之后,最基本的web的快速开发,只要像下面这样,建一个controller(实现了一个简单的helloworld),就可以完成,像之前一样。 HelloController.javapackage com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World" ; }}
然后在网页上,输入localhost:8080/hello,即可查看到Hello World。
那么对于CSS一类的文件,应该放在什么位置上,其实是有规定的,这就有关于SpringBoot对静态资源的映射规则。先来分析一段 WebMvcAutoConfiguration.class 中的一段代码:
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)); } } } //配置欢迎页 @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)); return welcomePageHandlerMapping; } //配置图标 @configuration @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguraion { public final ResourceProperties resourceProperties; public FaviconConfiguraion(ResourceProperties resourceProperties){ this.resourceProperties = resourceProperties; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler .setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } }
根据代码:
1)、所有 /webjars/** ,都去classpath:/META-INF/resources/webjars/ 下找资源;webjars:以jar包的方式引入静态资源;
进入webjars官网: 就可以将流行的前端框架,以maven依赖的方式导入进来。还可以选择对应版本。 之后在pom.xml文件中引入即可。比如,我想调用jquery的3.3.1版本,
就在pom.xml,dependencies标签中加入:(这段引入在官网中可以找到)org.webjars jquery 3.3.1
之后就可以找到:
也就是说,可以在网页中输入 localhost:8080/webjars/jquery/3.3.1/jquery.js ,它就可以找到这个文件。那么在访问的时候,只需要写webjars下面资源的名称即可。2)、"/**" 访问当前项目的任何资源,(静态资源的文件夹)
“classpath:/META-INF/resources/”
“classpath:/resources/” “classpath:/static/” “classpath:/public/” “/”:当前项目的根路径也就是说,只要文件无法处理,就会在这些文件夹中寻找。
在网页中输入localhost:8080/abc,只要无响应,就会去这些文件夹中寻找abc。3)、欢迎页;静态资源文件夹下的所有index.html文件;
输入localhost:8080/ 就会自动去寻找静态资源文件夹下的index页面
比如:
Title 首页
4)、配置图标;所有的 **/favicon.ico 都是在静态资源文件夹下寻找。
这样打开页面,就会发现出现图标。(是上面的那个小图标)5)、当然也可以手动修改路径,但是没必要。
在application.properties中:spring.resources.static-locations=classpath:/hello/,classpath:/guigu/
SpringBoot的项目是以jar包的形式,而且是嵌入式的tomcat,所以它默认是不支持JSP的。那么使用静态资源的方式,就会带来很多的麻烦。因此,SpringBoot就提供了模板引擎。就比如JSP、Velocity、Freemarker、Thymeleaf等都是模板引擎。模板引擎,就是我们先写一个静态模板,但是其中有一些值是动态的,这些值又会从一些指定数据中获得,那么将这些数据和模板交给模板引擎,由模板引擎来帮我们组装、解析、填充到指定的位置,最后将这个数据写出去。
SpringBoot推荐的是Thymeleaf,它语法更简单,功能更强大。
引入thymeleaf:
org.springframework.boot spring-boot-starter-thymeleaf
切换thymeleaf版本时需要注意,每一个thymeleaf都有对应的layout,具体对应版本,去github上直接搜索thymeleaf 和 thymeleaf-layout-dialect 或者去官网,可以查找。但是版本问题会经常出现(我尝试了好久),以下为我自己能用的版本号。
3.0.11.RELEASE 2.1.1
首先,从ThymeleafProperties.class中看到以下代码:
@ConfigurationProperties( prefix = "spring.thymeleaf")public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; ,,,,}
也就是说,只要我们把HTML页面放在classpath:/templates/ 下,thymeleaf就能自动渲染。
package com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World" ; } @RequestMapping("/success") public String success(){ return "success"; }}success.html:
Title 成功!
使用:
1、导入thymeleaf的名称空间2、使用thymeleaf语法(简例)
Title 成功!
这是显示欢迎信息
如果不经过模板引擎解析,直接访问,会显示前端写的数据:这是显示欢迎信息。
而通过引擎解析访问,它就会把它变成指定数据信息。 这样前后端的合作就可以实现了。3、具体的语法规则
像上面的,th:text;改变当前元素里面的文本内容;
th后,可加任意的html属性,来替换原生属性的值,比如:这是显示欢迎信息
那么,能用的用法就很多了,具体的可以参考usingthymeleaf.pdf文档查阅。
特征 | 属性 |
---|---|
片段包含(类似于jsp:include) | th:insert ,th:replace |
遍历(类似于c:forEach) | th:each |
条件判断(类似于c:if) | th:if,th:unless,th:switch,th:case |
声明变量(类似于c:set) | th:object,th:with |
任意属性修改(支持prepend,append) | th:attr,th:attrprepend,th:attrappend |
修改指定属性默认值 | th:value,th:href,th:src |
修改标签体内容 | th:text(转义特殊字符),th:utext(不转义特殊字符) |
声明片段 | th:fragment |
接下来考虑和表达式相关的问题。
几个表达式语法:
${...} :获取变量值。*{...} :在功能上和${...}一样。可以配合th:object="${session.user}"使用。:#{...} :取国际化内容@{...} :定义URL:@{/order/process(execID=${execId},execType='FAST')}~{...} :片段引用表达式:Name: Sebastian.
Surname: Pepper.
Nationality: Saturnn.
...
它还支持字面量、文本操作、数字运算、布尔运算、比较运算、条件运算、特殊符号。
package com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.Arrays;import java.util.Map;@Controllerpublic class HelloController { //查出一些数据,在页面展示 @RequestMapping("/success") public String success(Mapmap){ map.put("hello"," 你好
"); map.put("users", Arrays.asList("zhangsan","lisi","wangwu")); return "success"; }}
Title 成功!
这是显示欢迎信息
[[${user}]]
效果图:
其他的用法可以自己试验。转载地址:http://jayki.baihongyu.com/