目录
SpringBoot Web
一、首先要解决的问题
- 导入静态资源
- 首页
- jsp–模板引擎 Thymeleaf
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 国际化–中英翻译
二、静态资源处理
2.1、什么是webjars
WebJars是将web前端资源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式对web前端资源进行统一依赖管理,保证这些Web资源版本唯一性。WebJars的jar包部署在Maven中央仓库上。
2.2、方式一(webjars一般不使用这种方式)
使用/webjars/**
方式对静态资源进行访问!
2.3、方式二
2.4、方式三(自定义资源路径)
可以通过配置SpringBoot的默认配置文件,来自定义静态资源路径
三、首页
首页,静态资源文件夹下的所有 index.html 页面;被 /** 映射;比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html
新建一个 index.html ,在我们上面的3个目录中任意一个;然后访问测试 http://localhost:8080/ 看结果!
四、Thymeleaf(模板引擎)
4.1、引入
- 前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
- jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
- 那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢?
4.2、模板引擎
SpringBoot推荐使用模板引擎来进行开发,基本思想参考下图:
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。
4.3、引入Thymeleaf
-
Thymeleaf 官网:https://www.thymeleaf.org/
-
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
-
Spring官网找到对应的pom依赖,也可以说是thymeleaf场景启动器
<!--thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
4.4、Thymeleaf自动配置类:ThymeleafProperties
//部分代码
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 boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
//前缀
private String prefix = "classpath:/templates/";
//后缀
private String suffix = ".html";
}
- 从源码可以发现,这些代码和我们之前学习的SpringMVC的视图解析器配置很相似
- 可以看到视图解析器默认的前缀和后缀
- 只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!
4.5、测试
@Controller
public class TestController {
@RequestMapping("/test")
public String test(){
return "test";
}
@RequestMapping("/test01")
public String test01(Model model){
model.addAttribute("msg","<h2>Hello,SpringBoot!</h2>");
model.addAttribute("msg2","<h2>Hello,SpringBoot!</h2>");
return "test";
}
@RequestMapping("/test02")
public String test02(Model model){
model.addAttribute("array", Arrays.asList("麻","腾","飞"));
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Hello</h2>
<!--th:text就是将div中的内容设置为它指定的值,和之前学习的Vue一样-->
<div th:text="${msg}"></div>
<div th:utext="${msg2}"></div>
<hr>
<h2 th:each="a:${array}" th:text="${a}"></h2>
</body>
</html>
具体的thymeleaf基本语法格式,还需要我们参考thyleaf官方文档进行不断的练习。
五、MVC自动配置原理
Spring MVC Auto-configuration
// Spring Boot为Spring MVC提供了自动配置,它可以很好地与大多数应用程序一起工作。
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
// 自动配置在Spring默认设置的基础上添加了以下功能:
The auto-configuration adds the following features on top of Spring’s defaults:
// 包含视图解析器
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
// 支持静态资源文件夹的路径,以及webjars
Support for serving static resources, including support for WebJars
// 自动注册了Converter:
// 转换器,这就是我们网页提交数据到后台自动封装成为对象的东西,比如把"1"字符串自动转换为int类型
// Formatter:【格式化器,比如页面给我们了一个2019-8-10,它会给我们自动格式化为Date对象】
Automatic registration of Converter, GenericConverter, and Formatter beans.
// HttpMessageConverters
// SpringMVC用来转换Http请求和响应的的,比如我们要把一个User对象转换为JSON字符串,可以去看官网文档解释;
Support for HttpMessageConverters (covered later in this document).
// 定义错误代码生成规则的
Automatic registration of MessageCodesResolver (covered later in this document).
// 首页定制
Static index.html support.
// 图标定制
Custom Favicon support (covered later in this document).
// 初始化数据绑定器:帮我们把请求数据绑定到JavaBean中!
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
/*
如果您希望保留Spring Boot MVC功能,并且希望添加其他MVC配置(拦截器、格式化程序、视图控制器和其他功能),则可以添加自己
的@configuration类,类型为webmvcconfiguer,但不添加@EnableWebMvc。如果希望提供
RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义
实例,则可以声明WebMVCregistrationAdapter实例来提供此类组件。
*/
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration
(interceptors, formatters, view controllers, and other features), you can add your own
@Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide
custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or
ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
// 如果您想完全控制Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc进行注释。
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
5.1、解析器分析
ContentNegotiatingViewResolver
-
ContentNegotiatingViewResolver类中有两个方法:
@Nullable public View resolveViewName(String viewName, Locale locale) throws Exception { RequestAttributes attrs = RequestContextHolder.getRequestAttributes(); Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes"); List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest()); if (requestedMediaTypes != null) { //获取所选的视图对象 List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes); //选择一个最合适的视图对象,并把它返回 View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs); if (bestView != null) { return bestView; } }
protected void initServletContext(ServletContext servletContext) { // 这里它是从beanFactory工具中获取容器中的所有视图解析器 // ViewRescolver.class 把所有的视图解析器来组合的 Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.obtainApplicationContext(), ViewResolver.class).values(); ViewResolver viewResolver; if (this.viewResolvers == null) { this.viewResolvers = new ArrayList(matchingBeans.size()); } // ............... } //既然它是在容器中去找视图解析器,我们是否可以猜想,我们就可以去实现一个视图解析器了呢?
结论:
- ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的
5.2、自定义视图解析器
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//如果想要自己定义一些功能,只要写个组件,然后把它交给SpringBoot,SpringBoot就会自动装配
//扩展SpringMVC
//interface ViewResolver:实现了视图解析器接口的类,就可以看做是视图解析器
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
/*
* 自定义了一个自己的视图解析器MyViewResolver
* 1、实现视图解析器接口:ViewResolver
* 2、重写接口中的方法
* */
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
5.3、转换器和格式化器
5.4、修改SpringBoot的默认配置
这么多的自动配置,原理都是一样的,通过这个WebMVC的自动配置原理分析,我们要学会一种学习方式,通过源码探究,得出结论;这个结论一定是属于自己的,而且一通百通;
SpringBoot的底层,大量用到了这些设计细节思想,所以,没事需要多阅读源码!得出结论;
SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(如果用户自己配置@bean),如果有就用用户配置的,如果没有就用自动配置的;
如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来;
5.5、扩展SpringMVC
5.6、全面接管SpringMVC
全面接管:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置!只需在我们的配置类中要加一个@EnableWebMvc。
六、国际化
准备工作
先在IDEA中统一设置.properties的编码格式为UTF-8
配置文件编写
-
我们在resource资源文下新建一个i18n目录,来存放国家化配置文件
-
建立一个
login.properties
文件,还有一个login_zh_CN.properties
;发现IDEA自动识别
配置文件生效探究
-
MessageSourceAutoConfiguration
spring.messages.basename=i18n.login
配置页面国际化
配置国际化解析(中英切换)
在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!