环境准备
- jdk1.8
- maven 3.3.9
- SpringBoot 2.1.8
导入静态资源
百度网盘链接
提取码:wrbg
将asserts目录下的css、img、js等静态资源放置static目录下
将html静态资源放置templates目录下
创建项目
- File-New-Project-Spring Initializr快速创建Spring Boot项目,修改Group名,注意Java Version版本的选择为8。
- 引入依赖,选择Web-Spring Web,Template Engines-Thymeleaf,Lombok,如图所示。
模拟数据库
1. 创建数据库实体类
新建 pojo 包,用来存放实体类
在 pojo 包下创建一个部门表Department和一个员工表Employee
部门表:
@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();
}
}
由于导入了lombok依赖,使用@Data注解即可get属性,@AllArgsConstructor有参构造,@NoArgsConstructor无参构造。
2. 编写Dao层
模拟数据库,完成对员工的增删改查任务。
部门Dao
@Repository
public class DepartmentDao {
//模拟数据库中的数据
private static Map<Integer, Department> department = null;
static{
department = new HashMap<>();//创建一个部门表
department.put(1, new Department(1, "市场部"));
department.put(2, new Department(2, "教学部"));
department.put(3, new Department(4, "运营部"));
}
//获得所有部门信息
public Collection<Department> getDepartment(){
return department.values();
}
//通过id获得部门
public Department getDepartmentById(int id){
return department.get(id);
}
}
员工Dao
@Repository
public class EmployeeDao {
//模拟数据库中的数据
private static Map<Integer, Employee> employees = null;
//
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap<>();//创建一个部门表
employees.put(101, new Employee(101, "张晓明","vdx342@qq.com", 1, new Department(1, "市场部")));
employees.put(102, new Employee(102, "黄校长", "qas261@162.com",0, new Department(2,"教学部")));
employees.put(103, new Employee(103,"王例子", "edf123261@162.com",0, new Department(3,"运营部")));
employees.put(104, new Employee(104,"安吉拉", "wd561@162.com",1, new Department(4,"运营部")));
}
//主键自增
private static Integer initId = 104;
//增加一个员工
public void addEmployee(Employee emp){
if(emp.getId() == null){
emp.setId(initId++);
}
//emp部门由调用DepartmentDao包中的getDepartmentById()方法得到
emp.setDepartment(departmentDao.getDepartmentById(emp.getDepartment().getId()));
employees.put(emp.getId(), emp);
}
//查询全部员工信息
public Collection<Employee> getAll(){
return employees.values();
}
//通过id查询员工
public Employee getEmpById(Integer id){
return employees.get(id);
}
//删除员工
public void delete(Integer id){
employees.remove(id);
}
}
具体实现
(一) 默认访问首页
在controller类可以使用RequestMapping,浏览器发送 “/” 请求来到 templates 下的 index.html 页面。
@Controller
public class IndexController {
@RequestMapping({"/","/index.html"})
public String index(){
return "index";
}
}
但这样每次都定义一个空方法比较麻烦,在MyMvcConfig 类中写webMvcConfigurer方法使所有组件一起起作用。修改引入的index.html 名为 login.html。
@Configuration
//@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
//添加视图映射
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
将html文件其中的语法改为Thymeleaf,所有页面的静态资源都需要使用其接管。注意所有html都需要引入Thymeleaf命名空间。
xmlns:th="http://www.thymeleaf.org"
例如,在 index.html
中
其他页面亦是如此,再次测试访问,正确显示页面
在application.properties修改url路径
server.servlet.context-path=/kuang
运行,显示首页为
(二)国际化
1)、编写国际化配置文件,抽取页面需要显示的国际化消息
在resources 下新建 i18n 包,包中新建配置文件login.properties
和login_en_US.properties
,自动生成如下形式:
右键选择Add …
下方 + 添加新语言,输入zh_CN
自动生成 login_zh_CN.properties
在 Settings/Preferences 中找到 File Encodings,选为UTF8,并勾选自动转为ascii码。(此次是一个坑,不这样设置后面页面显示会出现乱码。)
添加属性:
配置好的文件如图
2)、Spring Boot自动配置好了管理国际化资源文件的组件
我们的配置文件可以直接放在类路径下叫messages.properties。现在把配置文件放在i18n下,只需在application.properties下修改包名。
spring.messages.basename=i18n/login
3)、去页面获取国际化的值(#{})
在index.html 文件的相应位置用th:**="#{}"
修改
此时显示页面为
此时,根据浏览器语言设置的信息即可切换中英文显示页面
4)、点击链接切换国际化
上述实现了登录首页显示为中文,我们在index.html页面中可以看到两个标签
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
也就对应着视图中的
那么我们怎么通过这两个标签实现中英文切换呢?
首先在这两个标签上加上跳转链接并带上相应的参数
此时点击中文链接,url为
点击英文链接,显示页面为
但还没有实现点击链接切换。
先分析一下源码,首先搜索WebMvcAutoConfiguration,可以在其中找到关于一个方法 localeResolver()
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
//如果用户配置了,则使用用户配置好的
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
//用户没有配置,则使用默认的
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
再点开默认地区解析器的AcceptHeaderLocaleResolver对象,点击此类查看源码
public class AcceptHeaderLocaleContextResolver implements LocaleContextResolver {
private final List<Locale> supportedLocales = new ArrayList(4);
@Nullable
private Locale defaultLocale;
public AcceptHeaderLocaleContextResolver() {
}
可以发现它继承了LocaleResolver接口,实现了地区解析
类似地,我们只需要编写一个自己的地区解析器,继承LocaleResolver接口,重写其方法即可。
编写区域解析器
并重写resolveLocale
方法,对应着index.html 文件中请求参数 l
- 如果点击中文按钮,则跳转到/index.html(l=‘zh_CN’)页面
- 如果点击English按钮,则跳转到/index.html(l=‘en_US’)页面
public class MyLocalResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//如果获取请求中的语言参数链接,就构造一个自己的
String language = request.getParameter("l");//l对应着index.html文件中的跳转链接
// System.out.println(language);
//如果没有就使用默认
Locale locale = Locale.getDefault();
//如果请求的链接携带了国际化参数,就构造一个自己的
if(!StringUtils.isEmpty(language)){
String[] s = language.split("_");//zh_CN
//国家、地区
locale = new Locale(s[0], s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
注入容器
向容器中注入自定义的国际化组件才能生效
在MyMvcConfig
中添加代码
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
重启项目即可实现国际化切换!
点击Engilsh
点击中文