使用springboot
使用
- 创建SpringBoot应用,选中我们需要的模块
- SpringBoot已经默认将这些场景配置好了,只需要在配置文件中制定少量配置就可以运行起来
- 自己编写业务代码
自动配置原理
- 这个场景SpringBoot帮我们配置了什么
- 能不能修改
- 能修改哪些配置
- 能不能扩展
xxxAutoConfiguration:帮我们给容器中自动配置组件
xxxProperties:配置类来封装配置文件的内容
对静态资源的映射规则
WebMvcAutoConfiguration
@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));
}
}
//设置和静态资源有关的参数,如缓存时间
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
- 所有 /webjars/**,都去classpath:/META-INF/resources/webjars/路径下找
- webjars网址
- 在pom.xml中加入依赖
<!-- 引入jquery的webjars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
- 此时可用/webjars/jquery.3.3.1/jquery.js访问了
- "/**"访问当前项目的任何资源(静态资源的文件夹)
- http://localhost:8080/bootstrap-3.3.7-dist/css/bootstrap.css
- 可在spring.resources.static-location= classpath:xxx配置
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
"/"
- 欢迎页:静态资源文件夹下的所有index.html
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
return welcomePageHandlerMapping;
}
- 所有的 **/favicon.ico 都是在静态资源文件下找
模板引擎
如JSP、Velociy、Freemarker、Thymeleaf
SpringBoot推荐Thymeleaf
引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 可以再properties里面改版本 -->
<thymeleaf.version>3.0.9</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
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";
- 所以在templates/下的html会被视图解析器找到
- 示例:前端跳到v1.html
@RequestMapping("/v1")
public String test(){
return "v1";
}
- 取值
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<!-- 所有的html元素都可以被thymeleaf替换接管: th:元素名 -->
<div th:text="${msg}"></div>
<div th:each="name:${list}" th:text="${name}"></div>
<div th:each="name:${list}">[[ ${name}]]</div>
</body>
Thymeleaf语法
${msg} --普通变量取值
@{url} -- 路径取值
#{msg} -- 国际变量取值
~{msg} -- 模块取值
扩展spring-mvc
- 自己写一个WebMvcConfigurer类,并标记为一个配置类
// 如果想diy(自定义)一些定制化的功能,只要写这个组件,然后将它交给springboot,springboot就会自动装配
//扩展springMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
- 自定义一个扩展的组件,已视图解析器为例
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
//实现了视图解析器接口的类,就可以把它看左视图解析器
// 定义了一个自己的视图解析器
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
- 官方推荐
/**
* 1. 不能加:@EnableWebMvc
* 2. 会导入一个类DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
* 3. 该类作用是从容器中获取所有的web-mvc-config
* 4. 由于WebMvcAutoConfiguration:@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
* 5. 所以一旦添加,其他崩盘
*/
//扩展springMVC,官方建议这么做
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//页面跳转器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/v2").setViewName("success");
}
}
原理
- WebMvcAutoConfiguration是SpringMVC的自动配置类
- 在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
- 该类会获取所有的WebMvcConfigurer,及会一起起作用
- 所以自定义的配置类也会起作用
- 效果:springmvc自动配置的和我们扩展配置的都会起作用
注意
- SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如
果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默
认的组合起来;- 在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
- 在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
国际化
常规步骤
- 编写国际化配置文件
- 使用ResourceBundleMessageSource管理国际化资源文件
- 在页面使用fmt:message取出国际化内容
Springboot
- 编写国际化文件
- Springboot自动配置好了管理国际化的资源文件的组件
public class MessageSourceAutoConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.messages")
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
@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;
}
//所以国际化文件可以放在类路径下默认叫messages.properties
public class MessageSourceProperties {
/**
* Comma-separated list of basenames (essentially a fully-qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
# 由注解得,我们需要在配置文件写默认值
spring.messages.basename=i18n/login
- 去页面获取国际化的值
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}"></h1>
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
- 默认的区域解析器
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
//默认的就是根据请求头带来的区域信息获取Locale进行国际化
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
- 自定义可通过按钮解析
/**
* 可以在连接上携带区域信息
* 自定义的区域解析器
*/
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;
}
//自定义springmvc扩展器添加组件
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
# 在html可以这么设置
# 效果等于/index.html?l=en_US
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>