Spring Boot学习
官网:https://spring.io/projects/spring-boot#overview
文档:https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/html/
参考视频:【狂神说Java】SpringBoot最新教程IDEA版通俗易懂_哔哩哔哩_bilibili
项目完整参考代码:lexiaoyuan/SpringBootStudy: My Spring Boot study notes (github.com)、SpringBootStudy: 我的Spring Boot学习笔记 (gitee.com)
员工管理系统
准备工作
- 新建一个Spring Boot项目,并添加Web依赖。
- 将静态资源导入(将文件粘贴到文件夹下)到static目录和templates目录下
静态资源文件可参考项目完整代码:https://github.com/lexiaoyuan/SpringBootStudy/tree/main/springboot_study/springboot_04_system、https://gitee.com/lexiaoyuan/spring-boot-study/tree/master/springboot_study/springboot_04_system
- 在pom.xml中导入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
- 在
Springboot04SystemApplication.java
同级目录新建如下目录,并在resources目录下新建public和resources目录用于后面保存不同类型的静态资源。
- 在pojo目录下新建实体类
Department.java
和Employee.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
@Data
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; // 0:女, 1:男
private Department department;
private Date birth;
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
// 默认生成日期
this.birth = new Date();
}
}
- 在dao目录下新建
DepartmentDao.java
和EmployeeDao.java
@Repository
public class DepartmentDao {
// 模拟数据库中数据
private static Map<Integer, Department> departments;
static {
departments = new HashMap<>(); //创建一个部门表
departments.put(101, new Department(101, "外交部"));
departments.put(102, new Department(102, "工信部"));
departments.put(103, new Department(103, "教育部"));
departments.put(104, new Department(104, "公安部"));
departments.put(105, new Department(105, "财政部"));
}
// 操作数据库
// 获得所有部门的信息
public Collection<Department> getDepartments() {
return departments.values();
}
// 通过id查询部门信息
public Department getDepartmentById(Integer id) {
return departments.get(id);
}
}
@Repository
public class EmployeeDao {
// 模拟数据库中数据
private static Map<Integer, Employee> employees;
@Autowired
private DepartmentDao departmentDao; //每个员工有一个所属部门
static {
employees = new HashMap<>(); // 创建一个员工表
employees.put(1001, new Employee(1001, "AA", "A10012345@qq.com", 0, new Department(101, "外交部")));
employees.put(1002, new Employee(1002, "BB", "B10012345@qq.com", 1, new Department(101, "工信部")));
employees.put(1003, new Employee(1003, "CC", "C10012345@qq.com", 0, new Department(101, "教育部")));
employees.put(1004, new Employee(1004, "DD", "D10012345@qq.com", 1, new Department(101, "公安部")));
employees.put(1005, new Employee(1005, "EE", "E10012345@qq.com", 0, new Department(101, "财政部")));
}
// 操作数据库
// id自增
private static Integer initId = 1006;
// 增加一名员工
public void addEmployee(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
// 查询全部员工信息
public Collection<Employee> getAll() {
return employees.values();
}
// 通过id查询员工
public Employee getEmployeeById(Integer id) {
return employees.get(id);
}
// 通过id删除员工
public void deleteEmployeeById(Integer id) {
employees.remove(id);
}
}
定制首页
- 在config目录下新建
MyMvcConfig.java
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 转到index.html
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
-
修改
index.html
- 首先需要添加thymeleaf的命名空间
xmlns:th="http://www.thymeleaf.org"
- 同时需要修改链接,要使用
@{...}
<!DOCTYPE html>
<html lang="en" 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">
<meta name="description" content="">
<meta name="author" content="">
<title>Sign in Template for Bootstrap</title>
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<p style="color: red"></p>
<label class="sr-only"></label>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<label class="sr-only"></label>
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2020-</p>
<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>
</form>
</body>
</html>
- 访问:http://localhost:8080/ 或 http://localhost:8080/index.html
- 如果更改后访问没有更新,可能是thymeleaf模板引擎有缓存,可以在
application.properties
中设置
# 关闭模板引擎的缓存
spring.thymeleaf.cache=false
- 还可以给访问增加一个目录,只需要修改
application.properties
# 浏览器中所有的访问都需要加上/lexiaoyuan
server.servlet.context-path=/lexiaoyuan
首页配置的注意点:所有页面的静态资源都需要使用thymeleaf接管
页面国际化配置
- 首先在设置里修改一下项目的编码!统一设置为UTF-8
- 编写国际化配置文件,在resources目录下新建i18n目录。然后在i18n目录下新建
login.properties
、login_zh_CN.properties
、login_en_US.properties
文件
补充:可以看到IDEA会自动识别并更新了一个文件夹。
快捷操作:
- 编写配置文件,可以通过可视化窗口编写
- 也可以直接在文件中编辑
- 配置好的文件
login.properties
:
login.password=密码
login.remember=记住我
login.signin=登录
login.tip=请登录
login.username=用户名
login_en_US.properties
:
login.password=password
login.remember=Remember me
login.signin=Sign in
login.tip=Please sign in
login.username=Username
login_zh_CN.properties
:
login.password=密码
login.remember=记住我
login.signin=登录
login.tip=请登录
login.username=用户名
- 配置国际化的配置文件路径。在
application.properties
中
# 配置国际化的配置文件路径
spring.messages.basename=i18n.login
- 在页面中得到配置的值
在thymeleaf中,通过添加
th:text=#{...}
属性获取值,或者通过[[#{...}]]
方式获取
<form class="form-signin">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">[[#{login.tip}]]</h1>
<label class="sr-only"></label>
<input type="text" name="username" class="form-control my-3" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only"></label>
<input type="password" name="password" class="form-control my-3" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.signin}]]</button>
<p class="mt-5 mb-3 text-muted">© 2020-2060</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
通过点击按钮切换语言
- 首先在config目录下新建自定义的国际化配置类
MyLocaleResolver.java
@Configuration
public class MyLocaleResolver implements LocaleResolver {
// 解析请求
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getParameter("lang");
Locale locale = Locale.getDefault(); // 没有参数就使用默认的
// 请求带有语言参数
if(!StringUtils.isEmpty(language)){
// 语言_地区
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
- 在
MyMvcConfig.java
中注入自定义的组件
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 转到index.html
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
// 往容器中注入自定义的组件
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
- 在前端
index.html
页面中增加请求
在thymeleaf中使用
@{...}
表示链接,使用()
携带参数
<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
- 访问:http://localhost:8080/index.html
- 点击English
- OK!完成了国际化操作!
未完待续……