Spring Boot Web开发
四、Web开发
使用Spring Boot:
1)、创建Spring Boot应用,选中我们需要的模块。
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码
自动配置原理?
这个场景Spring Boot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?XXXXX
XXXXAutoConfigutation: 帮我们给容器自动配置组件
xxxxProperties: 这些配置了来封装配置文件的内容
2.Spring boot对静态资源的映射规则
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
//可以设置和静态资源有关的参数,缓存时间
添加资源映射
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));
}
}
}
1)、所有/webjars/**,都去/META-INF/resources/webjars/找资源
webjars: 就是以jar包的形式引入静态资源 https://www.webjars.org
http://localhost:8080/webjars/jquery/3.4.1/jquery.js
引入jquery-webjar在访问的时候只需要写webjars下面资源的名称即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
2)、/**访问当前项目下的任何资源,(静态资源的文件夹)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
Localhost:8080/abc == 去静态资源文件夹中去找abc
是来配置欢迎页映射的
@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;
}
3、欢迎页:静态资源文件夹下的所有index.html页面;被"/**"映射
Localhost:8080/ 找Index页面
3、模板引擎
JSP,Freemarker,Thyleaf
Spring Boot框架推荐的Thymeleaf:
语法更简单,功能更强大
- 引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
//默认使用3.0.11版本
</dependency>
切换thymeleaf版本
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!--更换thymeleaf版本-->
<properties>
<!--thymeleaf主程序-->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!--thymeleaf布局支持程序-->
<!--thymeleaf 版本3已经重写,thymeleaf-layout-dialect必须为2以上的版本-->
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
</properties>
- 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";
//只要我们把html页面放在classpath:/templates/,thymeleaf就能自动渲染
使用:
- 导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>This is a success.html</h1>
<!-- th:text="" 将div里面的文本内容设置为${xxx} -->
<div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>
- 语法规则
th:text改变当前元素的文本内容
th: 任意属性来替换原生属性的值
2)、/**访问当前项目下的任何资源,(静态资源的文件夹)
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
Page 20 of 106
#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: _
- 扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
编写一个配置类(@Configuration),是WebMvcConfiguration类型的;不能标注@EnableWebMvc注解
既保留了所有的自动配置,也能用我们扩展的配置
//使用WebMvcConfigurationSupport可以来扩展Spring MVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
//浏览器发送/tth请求,来到success
registry.addViewController("/tth").setViewName("success");
}
}
原理:
1)、WebMvcConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入:@import(EnableWebMvcConfiguration.class)
3)、容器中所有的WebMvcConfigurer都会一起起作用
4)、我们的配置类也会被调用
效果:SpringMVC的自动配置和我们的扩展配置都会起作用
3、全面接管SpringMVC
SpringBoot对Spring MVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效
我们需要在配置类中添加@EnableWebMvc即可
原理:
为什么@EnableWebMvc自动配置就失效了:
1)
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
2)、
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}
3)、
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
//容器中没有这个组件时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
3)、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
5)、导入的WebMvcConfigurationSupport只是SpringMVC的最基本功能
5、如何修改SpringBoot的默认配置
模式:
1)、Spring Boot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@bean,@Component),如果有,就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfiguration帮助我们进行扩展配置
2)、国际化
1)、编写国际化配置文件
2)、使用ResourceBundleMessageSource管理国际化资源文件
3)、在页面使用fmt:message取出国际化内容
步骤:
1)、编写国际化配置文件,抽取页面需要显示的国际化消息
2)、SpringBoot自动配置好了管理国际化资源文件的组件;
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils
.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
3)、去页面获取国家化的值
修改properties的值
效果,根据刘拉你语言的信息切换国际化
原理:
国家化Locale(区域信息对象):LocaleResolver(获取区域信息对象)
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
默认的就是根据请求头带来的区域信息获取Locale进行国际化
4)、点击连接切换国际化
package com.tth.springboot.component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Set;
/*
*可以在连接上携带国际化区域信息
*
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] s = l.split("_");
locale = new Locale(s[0], s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
3)、登录
开发期间模板引擎页面修改以后,要实时生效
1)、禁用模板引擎的缓存
#禁用模板引擎的缓存
spring.thymeleaf.cache=false
2)、页面修改完成以后ctrl+f9;重新编译
登录消息结果的显示
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
3)、拦截器进行登录检查
5)、CRUD-员工列表
实验要求:
- RestfulCRUD:满足Restful
- URI: /资源名称/资源标志 HTTP请求方式来区分对资源CRUD的操作
普通CRUD (Uri来区分操作)
查询 getEmp()
添加 addEmp?xxx
修改 updateEmp?id=xxx&yy=xxx
删除 deleteEmp?id=1
RestfulCRUD
查询 emp-GET
添加 emp-POST
修改 emp/{id}-PUT
删除 emp/{id}-DELETE
2)、实验的请求架构
|
请求 |
请求方式 |
查询所有员工 |
emps |
GET |
查询某个员工(来到修改页面) |
Emp/{id} |
GET |
来到添加页面 |
Emp |
GET |
添加员工 |
Emp |
POST |
来到修改页面(查处员工进行信息回显) |
Emp/{id} |
GET |
修改员工 |
emp |
PUT |
删除员工 |
Emp/{id} |
DELETE |
3)、员工列表
Thymeleaf公共页面元素抽取
- 抽取公共片段
<div th:fragment=”copy”>
© 2011 The Good Thymes Virtual Grocery
</div>
- 引入公共片段
<div th:insert="footer :: copy">
~{templatename :: selector} : 模板名 :: 选择器
~{templatename :: fragment} : 模板名 :: 片段名
</div>
- 默认效果
Insert的功能片段在div标签中
如果使用th:insert等属性进行引入可以不写~{};
行内写法必须加上:[[~{}]]; [(~{})]
三种引入功能片段的th属性:
- th:insert:将公共片段整个插入到声明引入的元素中
- th:replace:将声明引入的元素替换为公共片段
- th:include:将被引入的片段的内容包含进这个标签中
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
引入方式
<body>
...
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
</body>
效果
<body>
...
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
</body>
引入片段的时候传入参数:
提交的数据格式不对:生日日期:
2012-12-12;2017/12/12;2012.12.12
日期的格式化:SpringMVC将页面提交的值需要转换为指定的类型
2012-12-12-Date;类型转换,格式化
默认日期是按照/的方式
Spring Boot的默认错误处理机制
默认效果:
1)、返回一个默认的错误页面
2)、如果是其他客户端相应,