Spring Boot的最大特点:自动装配。思考:
web开发要使用的问题:
开发web项目时,main文件夹下应该会有名为webapp的文件夹。但是现在Spring Boot中没有此文件夹,而是通过打包成jar的方式。这种情况下Spring Boot如何进行web的开发呢?
进入WebMvcAuotConfiguration
:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//静态资源文件夹映射
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(
this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
所有/webjars/**
,都去classpath:/META-INF/resources/webjars/
找资源;
范例:引入jquery:
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.5.1version>
dependency>
找到项目maven库中的jquery:
如果看到的目录与图片不同,请在project的设置中更改:
这里不选中Compact Middle Packages
。
重启项目,访问jquery:
http://localhost:8080/webjars/jquery/3.5.1/jquery.js
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
//可以设置和静态资源有关的参数,缓存时间等
/**
:访问当前项目的任何资源,都去(静态资源的文件夹)找映射
“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”
“/”:当前项目的根路径
范例:把资源放在classpath:/static/中:
访问:http://localhost:8080/asserts/js/Chart.min.js
进入WebMvcAuotConfiguration
:
//配置欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
ResourceProperties resourceProperties) {
return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
欢迎页是:静态资源文件夹下的所有index.html页面,被/**
映射;
localhost:8080/
,进入index页面
/**
因为静态文件夹下目前没有index.html,会有404错误。
public文件夹下创建index.html
再次访问localhost:8080/
:
何为图标?
所有的**/favicon.ico
都是在静态资源文件下找;
//配置喜欢的图标
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
//所有 **/favicon.ico
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler
.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
在配置文件application.properties中添加:
#关闭默认图标
spring.favicon.enabled=false
在classpath:/resource/
下添加自己想要更改的图标:
运行主程序,访问localhost:8080,可以看到图标变化。
前端交给我们的是html页面,在过去的开发过程中需要把它转换为jsp页面。
所以推荐使用:模板引擎Thymeleaf
模板引擎的作用:写一个模板(template),模板中有表达式,表达式的数据来自data。模板引擎按照模板表达式和数据生成想要的内容。
Thymeleaf:
pom文件添加依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
开发使用的是Thymeleaf3.0以上版本,这里会自动下载。
@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";
// 只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
范例:使用Thymeleaf
@Controller // 注意这里不能用@RestController
public class HelloController {
@ResponseBody // 访问/hello需要
@RequestMapping("/hello")
public String hello() {
return "Hello World";
}
@RequestMapping("/success")
public String success() {
// classpath:/templates/success.html
return "success";
}
}
编写classpath:/templates/下success.html文件:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>运行成功!h1>
body>
html>
在classpath:/templates/下success.html文件上导入Thymeleaf的名称空间。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
范例:简单使用
@Controller
public class HelloController {
// 需求:查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map) {
map.put("hello","你好");
return "success";
}
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>Thymeleaf成功!h1>
<div th:text="${hello}"> div>
body>
html>
th:text
:改变当前元素里面的文本内容;
th:任意html属性="${xxx}"
:替换原生属性的值(比如id、class等) <div th:id="${hello}" th:class="${hello}" th:text="${hello}"> div>
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: *{...}:选择表达式:和${}在功能上是一样;
补充功能:配合 th:object="${session.user}:
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: _
@Controller
public class HelloController {
// 需求:查出一些数据,在页面展示
@RequestMapping("/success")
public String success(Map<String,Object> map) {
map.put("hello","你好
");
map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
return "success";
}
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>Thymeleaf成功!h1>
<div th:id="${hello}" th:class="${hello}" th:text="${hello}"> div>
<hr/>
<div th:text="${hello}">div>
<div th:utext="${hello}">div>
<hr/>
<h4 th:text="${user}" th:each="user:${users}">h4>
<hr/>
<h4>
<span th:each="user:${users}"> [[${user}]] span>
h4>
body>
html>