Spring Boot 员工管理项目(一)— 导入静态资源、首页、国际化

本文详细介绍了如何在SpringBoot项目中整合Thymeleaf模板引擎,并利用Lombok简化实体类,模拟数据库操作。接着,通过创建自定义的国际化解析器,实现页面的中英文切换功能。步骤包括配置国际化文件、编写控制器、注入自定义解析器等。
摘要由CSDN通过智能技术生成

环境准备

  • 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.propertieslogin_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
在这里插入图片描述
点击中文在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值