本文是接上一篇:学习SpringBoot(精华文章一)
使用springboot
1.创建springboot应用,选中我们需要的模块;
2.springboot默认已经将这些场景配置好了,只需在配置文件中指定少量的配置就可以运行起来。
3.自己编写业务代码
自动配置原理?详见二.8
1.xxxAutoConfiguration:帮我们给容器中自动配置组件
2.xxxProperties:配置类来封装配置文件的内容
添加资源映射:
@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));
}
}
//欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext),
applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
//设置自己喜欢的图标
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled",
matchIfMissing = true)
public static class FaviconConfiguration implements ResourceLoaderAware {
private final ResourceProperties resourceProperties;
private ResourceLoader resourceLoader;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@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(resolveFaviconLocations());
return requestHandler;
}
/webjars/**:以jar包的方式引入静态资源。webjars官网
访问路径:localhost:8080/webjars/jquery/3.3.1/jquery.js
在访问的时候,只需要写webjars下面的资源名称即可。
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.3.1version>
dependency>
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/
"/":当前项目的根目录
访问路径下的任何东西,如:localhost:8080/abc,如果没人处理,默认都去访问类路径下的静态资源:
localhost:8080/abc === 去静态资源找abcclasspath:/resources/
localhost:8080/,默认就找静态资源文件的下面。
不管是访问任意路径层下面的favicon.ico,图标都是在静态资源文件下
在application.properties中,指定hello和bootcrud的文件夹。
spring.resources.static-locations=classpath:/hello/,classpath:/bootcrud/
spring.resources.static-locations是数组,所以再指定多路径的时候需要加逗号。
Jsp、Velocity、Freemarker、Thymeleaf
模板引擎很多,但是思想都是一样的:
SpringBoot推荐的模板引擎:Thymeleaf。被称为高级语言的模板引擎。
语法更简单,功能更强大。
怎么引:对于springboot来说,都是starter就OK了。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
因为springboot默认的thymeleaf版本是2.1.6,所以:
修改依赖版本的方法:
<properties>
<java.version>1.8java.version>
<thymeleaf.version>3.0.9.RELEASEthymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1thymeleaf-layout-dialect.version>
properties>
规则:
@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就会自动帮我们渲染
1.导入Thymeleaf的名称空间:(作用:语法提示)
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2.使用Thymeleaf语法:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>成功!h1>
<div th:text="${hello}">div>
body>
html>
controller:
@RequestMapping("/success")
public String success(Map<String,Object> map){
map.put("hello","你好");
return "success";
}
th: 任意的HTML属性,来替换原生的值
thymeleaf官方网站:找到Using Thymeleaf,下载文档
Simple expressions:
Variable Expressions: ${...} -----> 获取变量值:OGNL表达式。也是用得最多最强大的表达式
1.可以获取对象的属性值,可以调用方法
2.能使用的内置对象有:
#ctx : the context object.(当前上下文对象)
#vars: the context variables.(当前上下文对象里面的值)
#locale : the context locale.(区域信息)
web环境下:
#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.
例:
${person.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: *{...} -----> 变量的选择表达式,和${...}的功能是一样的。
注:有一个补充的功能:主要是配合${...},如:(参见thymeleaf文档4.3)
例:
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn.
*就等于${session.user},可以直接取出session.user下面的firstName、lastName
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: _
例:
比如三元运算符:
if判断如果成立用then,不成立用else,如果不想做什么操作,直接_
controller:
@RequestMapping("/success")
public String success(Map<String,Object> map){
map.put("hello","你好
");
map.put("name", Arrays.asList("陈二狗","王境泽","二营长"));
return "success";
}
在classpath:/templates/下的success.html:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>成功!h1>
<div th:text="${hello}">div>
<hr/>
<div th:utext="${hello}">div>
<hr/>
<h4 th:text="${names}" th:each="names:${name}">h4>
<hr/>
<h1>
<span th:each="names:${name}">[(${names})]span>
h1>
body>
html>
最后的运行效果:
总结:
第一个hr线:
th:text为转义特殊字符,所以它会直接把整个字符串给输出出来。
th:utext为不转义字符,所以会按照它(h1标签)自己原本的意思显示出来。h1在html中是表示什么,就给值上样式。
第二个hr线:
把th:each写在h4上,所以页面会显示三个h4,遍历了这个数组。h4标签的内容就是th:text的值。
第三个hr线:
把数组遍历在span标签上,所以再h1标签下会有三个span标签,span里面的值就是(${name})输出的值。