文章目录
六、SpringBoot与Web开发
1.简介
使用SpringBoot进行Web开发;
1.创建一个SpringBoot应用,选中需要的模块
2.SpringBoot经默认将这些场景配置好了,只需要在配置文件中进行少量的配置就可以将程序运行起来。
3.编写业务代码
自动配置原理
SpringBoot究竟帮助我们配置了什么,是否可以修改,是否可以扩展,都是一些问题
而
xxAutoConfiguration帮我们给容器中自动装配组件
xxProperties帮我们封装组件的内容
2.SpringBoot对静态资源的映射规则
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
//可以设置和静态资源有关的参数,缓存时间等等
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
(getResourceLocations
(this.resourceProperties.getStaticLocations()))
.setCachePeriod
(this.getSeconds(cachePeriod))
.setCacheControl
(cacheControl));
}
}
}
1.所有/webjars/*都是从"classpath:/META-INF/resources/webjars/找资源
webjars:以jar的方式给工程导入一些资源
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
2./**访问当前项目的任何资源(静态资源文件夹)
<1>classpath:/META-INF/resources/
<2>classpath:/resource
<3>classpath:/static
<4>classpath:/public
3.配置欢迎页,静态资源文件夹下的所有index.html页面,也就是localhost:9999/
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping
(new TemplateAvailabilityProviders(applicationContext),
applicationContext, this.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
4.网页的图标也就是.ico文件,也要默认存放在静态资源文件夹下读取
3.模板引擎
我们以前所学过的jsp就是一种模板引擎,但是在这里我们介绍的是thymeleaf,SpringBoot推荐的它语法更简单,功能更强大
<1>引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<2>Thymeleaf使用方法
@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 String prefix = "classpath:/templates/";
private String suffix = ".html";
只要我们把HTML页面放到classpath:/templates/,thymeleaf就能自动渲染
使用步骤:
1.导入thymeleaf的名称空间到想要书写的html文件中
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2.使用thymeleaf语法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 语法提示↑-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!--th:text 将div里面的文本内容设置为我们指定的值-->
<div th:text="${hello}">Hello</div>
<!--如果要是应用了thymeleaf模板引擎,显示的是th:text的内容,如果不应用,就是显示的Hello-->
</body>
</html>
<3>Thymeleaf语法规则
1)th:任意属性;来替换原来属性的值,th:text是替换标签文本内容
就像这样
<div id="001" class="myDov" th:id="111" th:class="Doc" th:text="${hello}">Hello</div>
2)表达式语法
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#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.
${session.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: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表达式
<div th:insert="~{commons :: main}">...</div>
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: _
@RequestMapping("/success")
public String success(Map<String,Object> map){
map.put("hello", "<h1>你好</h1>");
map.put("users", Arrays.asList("zhangsan", "lisi", "wangwu"));
//classpath:/templates/success.html
return "success";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 语法提示↑-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!--th:text 将div里面的文本内容设置为我们指定的值-->
<div id="001" class="myDov" th:id="111" th:class="Doc" th:text="${hello}">Hello</div>
<!--如果要是应用了thymeleaf模板引擎,显示的是th:text的内容,如果不应用,就是显示的Hello-->
<br>
<div th:text="${hello}"></div><!--不转义,直接字符串是啥就是啥-->
<div th:utext="${hello}"></div><!--转义,字符串的特殊字符会被自动转换-->
<!--th:each每次遍历都会生成当前标签-->
<h2 th:text="${user}" th:each="user:${users}"></h2><!--相当于h4标签遍历了三遍-->
<hr/>
<h3>
<span th:each="user:${users}">[[${user}]] </span><!--相当于一个h3运行了三个span-->
</h3>
</body>
</html>
4.SpringMVC自动配置
SpringBoot自动配置好了SpringMVC,以下是对它的默认配置
- 1.自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定页面渲染的方法)
2.ContentNegotiatingViewResolver:组合所有的视图解释器的
3.如何定制:我们可以自己给视图添加一个视图解释器 - WebJars的静态资源访问路径
- index.html的首页访问
- .ico的网页图标
- 自动注册了Converter,GenericConverter,Formatter的beans
Converter:转换器;当我们提交给网页一段数据的时候要根据数据判断数据类型
Formatter:格式化器;2019-02-02==Date,主要是因为每个地方的时间格式不同 - 支持HttpMessageConverters:
HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User–json
而HttpMessageConverters则可以管理获取所有的HttpMessageConverter - 自动注册MessageCodeResolver定义错误代码生成规则
- 支持自动配置Web数据绑定器ConfigurableWebBindingInitializer
扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors><!--定义一个拦截器,拦截hello请求-->
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean/>
</mvc:interceptor>
</mvc:interceptors>
编写一个配置类(@Configuration)给springBoot添加我们自定义的功能,是WebMvcConfigurerAdapter类型,而不是@EnableWebMvc
//使用WebMvcConfigrerAdapter来扩展SpringMvc的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
// 浏览器发送/bean请求来到success
registry.addViewController("/bean").setViewName("success");
}
}
特点:既保留了所有的自动配置,也能用扩展的配置
全面接管SpringMVC
SpringBoot对SpringMVC自动配置不需要了,全都是自己配
我们需要在配置类中添加@EnableWebMvc即可,这样,所有的自动配置就都失效了
5.修改SpringMVC自动配置
- 自动配置的前提是用户没有自己配置,会首先扫描@Bean @Component,如果扫描到了,就用用户配置,如果没有才自己配置;如果有些组件支持多视图解释器,就可以把用户配置的和自己默认的组合起来
- 在Springboot中会有非常多的WebMvcConfigurer帮助我们进行扩展
下一篇文章来基于SpringBoot做一个简单的系统。