目录
1.环境搭建
1.新建一个SpringBoot项目
删除无用的目录与文件
2.导入静态资源
链接:http://https://pan.baidu.com/s/1wzgdWQxHVFz0u_pePNOIjw
提取码:jsm3
根据资源目录中的名字放入包中即可
3.模拟数据库
创建数据库实体类
在主程序同级目录下新建pojo
包,用来存放实体类
在pojo
包下创建一个部门表Department
和一个员工表Employee
为了方便,我们导入lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
部门表:
//部门表
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
员工表:
//员工表
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;//0:女 1:男
private Department department;
private Date date;
}
编写dao层(模拟数据)
在主程序同级目录下新建dao包
然后分别编写DepartmentDao和EmployeeDao,并在其中模拟数据库的数据
DepartmentDao:
package com.jiang.dao;
import com.jiang.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
//注册到IOC容器中
@Repository
public class DepartmentDao {
//模拟数据库中的数据
private static Map<Integer, Department> departments = null;
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(int id) {
return departments.get(id);
}
}
EmployeeDao:
//注册到IOC容器中
@Repository
public class EmployeeDao {
//模拟数据库中员工表的数据
static private Map<Integer, Employee> employees;
@Autowired//自动
private DepartmentDao departmentDao;
static {
employees = new HashMap<>();//创建一个员工表
employees.put(1001, new Employee(1001, "zsr", "1234@qq.com", 1, new Department(101, "技术部"), new Date()));
employees.put(1002, new Employee(1002, "lyr", "1345@qq.com", 1, new Department(102, "市场部"), new Date()));
employees.put(1003, new Employee(1003, "gcc", "5665@qq.com", 0, new Department(103, "调研部"), new Date()));
employees.put(1004, new Employee(1004, "zyx", "7688@qq.com", 1, new Department(104, "后勤部"), new Date()));
employees.put(1005, new Employee(1005, "zch", "8089@qq.com", 1, new Department(105, "运营部"), new Date()));
}
//主键自增
private static Integer initialID = 1006;
//增加一个员工
public void addEmployee(Employee employee) {
if (employee.getId() == null)
employee.setId(initialID);
//修改部门的员工(通过部门id获得部门(通过这个员工的获得部门然后获得部门id)) 通过这个员工获得他的部门,然后在获得部门id来获得这个部门信息来修改员工信息
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
//增加员工(员工id,员工信息)
employees.put(employee.getId(), employee);
}
//查询全部员工信息
public Collection<Employee> getAllEmployees() {
return employees.values();
}
//通过id查询员工
public Employee getEmployeeByID(Integer id) {
return employees.get(id);
}
//通过id删除员工
public void deleteEmployeeByID(int id) {
employees.remove(id);
}
}
2.首页实现
在主程序同级目录下新建config包用来存放自己的配置类
在其中新建一个自己的配置类MyMvcConfig进行视图跳转
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
我们启动主程序访问测试一下,访问localhost:8080/
或者locahost:8080/index.html
出现以下页面则成功
上述测试可以看到页面有图片没有加载出来,且没有css和js的样式,这就是因为我们
html
页面中静态资源引入的语法出了问题,在SpringBoot中,推荐使用Thymeleaf
作为模板引擎,我们将其中的语法改为Thymeleaf
,所有页面的静态资源都需要使用其接管
注意所有html都需要引入Thymeleaf
命名空间
xmlns:th="http://www.thymeleaf.org"
然后修改所有页面静态资源的引入,使用@{...}
链接表达式
例如index.html
中:
注意:第一个/
代表项目的static的静态目录
其他页面亦是如此,再次测试访问,正确显示页面
3.页面国际化
1.统一properties编码
首先在IDEA中统一设置properties的编码为UTF-8
2. 编写i18n国际化资源文件
在resources
目录下新建一个i18n
包,其中放置国际化相关的配置
其中新建三个配置文件,用来配置语言:
login.properties
:无语言配置时候生效login_en_US.properties
:英文生效login_zh_CN.properties
:中文生效
命名方式是下划线的组合:文件名_
语言_
国家.properties;
以此方式命名,IDEA会帮我们识别这是个国际化配置包,自动绑定在一起转换成如下的模式:
绑定在一起后,我们想要添加更过语言配置,只需要在大的资源包右键添加到该绑定配置文件即可
此时只需要输入区域名
即可创建成功,比如输入en_US
,就会自动识别
这里安装一个可视化插件,这里我已经安装,未安装的在左侧MarKeolace安装即可
然后打开英文或者中文语言的配置文件,点击资源包进入可视化编辑页面
进入到可视化编辑页面后,点击加号,添加属性,首先新建一个login.tip
代表首页中的提示
然后对该提示分别做三种情况的语言配置,在三个对应的输入框输入即可(注意:IDEA2020.1可能无法保存,建议直接在配置文件中编写)
接下来再配置所有要转换语言的变量(注意:IDEA2020.1可能无法保存,建议直接在配置文件中编写)
三个配置文件的文本内容如下
login.properties
login.tip=请登录
login.password=密码
login.remember=记住我
login.btn=登录
login.username=用户名
login_en_US.properties
login.tip=Please sign in
login.password=password
login.remember=remember me
login.btn=login
login.username=username
login_zh_CN.properties
login.tip=请登录
login.password=密码
login.remember=记住我
login.btn=登录
login.username=用户名
3. 配置国际化资源文件名称
在Spring程序中,国际化主要是通过
ResourceBundleMessageSource
这个类来实现的Spring Boot通过
MessageSourceAutoConfiguration
为我们自动配置好了管理国际化资源文件的组件
我们在IDEA中查看以下MessageSourceAutoConfiguration
类
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = {};
@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;
}
//......
}
主要了解messageSource()这个方法:
public MessageSource messageSource(MessageSourceProperties properties);
可以看到,它的参数为MessageSourceProperties
对象,我们看看这个类
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";
/**
* Message bundles encoding.
*/
private Charset encoding = StandardCharsets.UTF_8;
我们翻译其注释:
逗号分隔的基名列表(本质上是完全限定的关路径位置)
每个都遵循ResourceBundle约定,并轻松支持基于斜杠的位置。
如果不包含包限定符(例如org . mypackage"),它将从类路径根目录中解析。
意思是:
- 如果你不在springboot配置文件中指定以.分隔开的国际化资源文件名称的话
- 它默认会去类路径下找messages.properties作为国际化资源文件
这里我们自定义了国际化资源文件,因此我们需要在SpringBoot配置文件application.properties中加入以下配置指定我们配置文件的名称
spring.messages.basename=i18n.login
其中i18n
是存放资源的文件夹名,login
是资源文件的基本名称。
4. 首页获取显示国际化值
利用#{...}
消息表达式,去首页index.html
获取国际化的值
重启项目,访问首页,可以发现已经自动识别为中文
5. 配置国际化组件实现中英文切换
1. 添加中英文切换标签链接
上述实现了登录首页显示为中文,我们在ind