默认Spring Security会提供登录页面,但有时登录页面似乎并不合乎我们满意,本章将介绍如何通过Thymeleaf定制化登录页面
引入依赖
添加的依赖
- spring-boot-starter-thymeleaf - 用于引入thymeleaf
- org.webjars -> bootstrap - CSS框架内容
- org.webjars -> webjars-locator-core - 帮助定位web资源
依赖代码
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.5.5'
// https://mvnrepository.com/artifact/org.webjars/bootstrap
implementation group: 'org.webjars', name: 'bootstrap', version: '5.1.1'
// https://mvnrepository.com/artifact/org.webjars/webjars-locator-core
implementation group: 'org.webjars', name: 'webjars-locator-core', version: '0.48'
添加MVC映射
添加config实现MVC Configurer
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// ...
}
添加静态文件映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/")
.resourceChain(false);
registry.setOrder(1);
}
添加视图映射
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(HIGHEST_PRECEDENCE);
}
添加视图层内容
- login页面采用thymeleaf模板并使用国际化配置
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title th:text="#{login.page.title}">