参考博客
Web开发探究
使用SpringBoot的步骤:
1、创建一个SpringBoot应用,选择需要的模块,SpringBoot会默认将需要的模块自动配置好
2、手动在配置文件进行部分配置,项目便可以运行
3、专注编写业务代码,不需要考虑以前那样一大堆的配置了。
要熟悉掌握开发,之前学习的自动配置的原理一定要搞明白!
比如SpringBoot到底帮我们配置了什么?我们能不能修改?我们能修改哪些配置?我们能不能扩展?
-
向容器中自动配置组件 :xxxAutoconfiguration
-
自动配置类,封装配置文件的内容:xxxProperties
Web要解决的问题:
- 导入静态资源(image,css,js)
- 首页
- jsp,模板引擎Thymeleaf
- 配置扩展SpringMVC
- 增删改查业务编写
- 拦截器
- 国际化
静态资源处理
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 配置类里面,WebMvcAutoConfigurationAdapter 中有很多配置方法。
addResourceHandlers 添加资源处理
@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();
// webjars文件夹
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));
}
}
比如所有 /webjars/**的路径 , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;
什么是webjars ?
Webjars本质就是以jar包的方式引入静态资源 , 以前要导入一个静态资源文件,直接导入即可。
使用SpringBoot需要使用Webjars,网站:https://www.webjars.org
使用jQuery(引入jQuery对应版本的pom依赖即可)
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
目录结构:
、
访问:只要是静态资源,SpringBoot就会去对应的路径寻找改静态资源,我们这里访问:http://localhost:8080/webjars/jquery/3.6.0/jquery.js
其他自动配置的静态资源映射规则
项目中要是使用自己的静态资源该如何导入呢?
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (servletContext != null) {
registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
}
});
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
由代码可得,在staticPathPattern发现另一种映射规则 :/** , 访问当前项目的任意静态资源,会去找 WebProperties类。
WebProperties可以设置和静态资源有关的参数;这里指明了寻找静态资源的文件夹,即上面数组的内容。
结论:
以下四个目录存放的静态资源可以被我们识别:
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
因此,可以在resources根目录下新建对应的文件夹,来存放静态资源文件。
自定义静态资源路径
可以通过配置文件来指定一下静态资源路径,在application.properties中配置;
spring.resources.static-locations=classpath:/coding/,classpath:/qqa/
注意:一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!
首页处理
源代码
@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;
}
private Resource getWelcomePage() {
for (String location : this.resourceProperties.getStaticLocations()) {
Resource indexHtml = getIndexHtml(location);
if (indexHtml != null) {
return indexHtml;
}
}
ServletContext servletContext = getServletContext();
if (servletContext != null) {
return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
}
return null;
}
private Resource getIndexHtml(Resource location) {
try {
Resource resource = location.createRelative("index.html");
if (resource.exists() && (resource.getURL() != null)) {
return resource;
}
}
catch (Exception ex) {
}
return null;
}
由此可见,欢迎页就是静态资源文件夹下的所有 index.html 页面;映射路径为/** 。
比如,访问 http://localhost:8080/ ,就会映射到静态资源文件夹下的 index.html。
Thymeleaf
模板引擎
前端请求给后台的页面是html(静态)页面。以前的后端开发,需要转成jsp页面,jsp好处就是当我们在数据库查出一些数据后,转发到JSP页面,可以轻松的实现数据的显示及交互等。
jsp支持非常强大的功能,包括能写Java代码。
但是,目前,第一,SpringBoot是以jar包的方式打包,而不是war包;第二,服务器还是嵌入式的Tomcat,而Tomcat现在不支持jsp的。
那不支持jsp,如果直接用纯静态页面的方式,会给开发会带来非常大的麻烦,那怎么办?
SpringBoot推荐使用模板引擎:
模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot推荐的是Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,如下图:
模板引擎的作用就是一个页面模板,但其中有些值是动态的,使用表达式表示的。这些值的具体取值,就是后台封装一些数据。将模板(Template)和数据(Data)交给模板引擎,模板引擎会按照数据把表达式解析、填充到我们指定的位置,然后数据最终形成了一个我们想要的内容给我们返回出去,这就是模板引擎。不管是jsp还是其他模板引擎,都是这个思想。只不过,不同的模板引擎之间,语法有点不一样。Thymeleaf模板引擎,是一个高级语言的模板引擎,他的语法更简单,功能更强大。
引入Thymeleaf
对于springboot来说,所有功能场景都是一个starter,在项目中引入一下即可。
<!--Thymeleaf 模板引擎,基于3.x开发-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf自动配置及使用
按照SpringBoot的自动装配原理,查看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";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
/**
* Prefix that gets prepended to view names when building a URL.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Suffix that gets appended to view names when building a URL.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
*/
private String mode = "HTML";
/**
* Template files encoding.
*/
private Charset encoding = DEFAULT_ENCODING;
/**
* Whether to enable template caching.
*/
private boolean cache = true;
}
结论:
可以看到默认的前缀和后缀,因此只需要把html页面放在项目路径下的templates文件夹下,thymeleaf就可以帮助我们自动渲染页面了。
总之,使用thymeleaf不需要配置任何东西,只需要将html页面放在指定的文件夹下即可!
Thymeleaf 语法学习
要学习语法,还是参考官网文档最为准确,我们找到对应的版本看一下。Thymeleaf 官网:https://www.thymeleaf.org/ , 简单看一下官网!我们去下载Thymeleaf的官方文档!
前提:使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。
可以在官方文档的#3中找命名空间:
xmlns:th="http://www.thymeleaf.org"
1、可以使用任意的 th:attr 来替换Html中原生属性的值,类比jsp。
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: _