• 八、Spring Boot - 国际化、登录功能实现 (4)


    一、项目搭建

    准备阶段最终结构:

    在这里插入图片描述

    1.1 根据上节删掉不需要的

    首先,我们搭建一个普通的SpringBoot项目,回顾一下HelloWorld程序!

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述
    导入依赖: pom.xml

    
    <dependency>
        <groupId>org.thymeleafgroupId>
        <artifactId>thymeleaf-spring5artifactId>
    dependency>
    <dependency>
        <groupId>org.thymeleaf.extrasgroupId>
        <artifactId>thymeleaf-extras-java8timeartifactId>
    dependency>
    
    
    <dependency>
       <groupId>org.projectlombokgroupId>
       <artifactId>lombokartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    根据上节,现在只留下面这些,是一个干净的空项目:

    在这里插入图片描述

    1.2 导入静态资源

    获取静态资源

    在这里插入图片描述

    1.3 创建实体

    1. 创建包 com.zql.pojo,并分别创建实体 Department.javaEmployee.java

    Department.java

    package com.zql.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     * 部门表
     */
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Department {
    
        private Integer id;
        private String departmentName;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    Employee.java

    package com.zql.pojo;
    
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     * 员工表
     */
    @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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    1.4 创建dao

    • (因没有数据库表,所以直接这里写了,建议直接copy代码到你工程中)
    1. 创建包 com.zql.dao,并分别创建 DepartmentDao.javaEmployeeDao.java

    DepartmentDao.java

    package com.zql.dao;
    
    import com.zql.pojo.Department;
    import org.springframework.stereotype.Repository;
    
    import java.util.Collection;
    import java.util.Map;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     * 部门dao
     */
    @Repository
    public class DepartmentDao {
    
        //模拟数据库中的数据
        private static Map<Integer, Department> departments = null;
    
        static {
    		
    		departments = new HashMap<Integer, Department>();
    		 
            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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    EmployeeDao.java

    package com.zql.dao;
    
    import com.zql.pojo.Department;
    import com.zql.pojo.Employee;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     * 员工Dao
     */
    @Repository
    public class EmployeeDao {
    
        //模拟数据库中的数据
        private static Map<Integer, Employee> employees = null;
        //员工所属的部门
        @Autowired
        private  DepartmentDao departmentDao;
    
        static {
    
            employees = new HashMap<Integer,Employee>();//创建一个部门表
    
            employees.put(101,new Employee(1001,"AA","A198247@qq.com",0,new Department(101,"教学部")));
            employees.put(102,new Employee(1002,"AB","B198247@qq.com",1,new Department(102,"市场部")));
            employees.put(103,new Employee(1003,"AC","C198247@qq.com",0,new Department(103,"教研部")));
            employees.put(104,new Employee(1004,"AD","D198247@qq.com",1,new Department(104,"运营部")));
            employees.put(105,new Employee(1005,"AE","E198247@qq.com",0,new Department(105,"后勤部")));
    
        }
    
        //主键自增
        private static  Integer initId = 1006;
        //增加一个员工
        public void save(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 delete(Integer id){
            employees.remove(id);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    二、首页实现

    首页配置:注意点,所有页面的静态资源都需要使用thymeleaf接管;@{ }

    1. 视图层 MyMvcConfig.java

    在这里插入图片描述

    package com.zql.config;
    
    import org.springframework.context.annotation.Configuration;
    
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
    
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index.html").setViewName("index");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    1. 修改页面

    在这里插入图片描述

    (2)

    在这里插入图片描述

    清除缓存,配置项目路径

    在这里插入图片描述

    #清除模板引擎缓存
    spring.thymeleaf.cache=false
    
    #修改配置项目路径,是url的一部分
    server.servlet.context-path=/daniel
    
    • 1
    • 2
    • 3
    • 4
    • 5

    启动主启动类测试:http://localhost:8080/daniel/

    在这里插入图片描述

    三、国际化

    3.1 首页修改为中文显示

    前提:修改 IDEA 编码规则在这里插入图片描述

    1. 在resources下面创建一个文件夹 i18n(国际化缩写,首尾字母,中间18个字母,类似得还有K8S)
    2. 创建 login.properties,login_zh_CN.properties,则自动生成如下所示,

    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

    结果自动生成:

    在这里插入图片描述
    全局搜索 MessageSourceProperties 类可以查看源码,而后在application.properties 中做如下配置

    在这里插入图片描述

    #我们配置文件得真实位置
    spring.messages.basename=i18n.login
    
    • 1
    • 2

    修改 index.html 页面

    在这里插入图片描述

    启动程序运行查看:

    在这里插入图片描述

    3.2 中英文切换显示

    1. 首页 index.html 添加链接

    在这里插入图片描述

    <a class="btn btn-sm" th:href="@{/index.html(1='zh_CN')}">中文a>
    <a class="btn btn-sm" th:href="@{/index.html(1='en_US')}">Englisha>
    
    • 1
    • 2
    1. 在包com.zql.config下面创建类 MyLocaleResolver.java
    package com.zql.config;
    
    import org.springframework.cglib.core.Local;
    import org.springframework.web.servlet.LocaleResolver;
    import org.thymeleaf.util.StringUtils;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Locale;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public class MyLocaleResolver implements LocaleResolver {
    
        //解析请求
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
    
            String language = request.getParameter("1");
    
            System.out.println("Debug==>"+language);
    
            Locale locale = Locale.getDefault();//如果没有就使用默认得;
    
            //如果请求得链接携带了国际化得参数
            if (!StringUtils.isEmpty(language)){
    
                //zh_CN
                String[] split = language.split("_");
                //国家,地区
                locale = new Locale(split[0], split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    1. 添加到类 MyMvcConfig.java

    在这里插入图片描述

    //自定义得国家化组件就生效了!
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    重启测试:http://localhost:8080/daniel/

    点击中文显示得:

    在这里插入图片描述
    点击 English 显示得:

    在这里插入图片描述

    四、登录功能实现

    4.1 登录功能实现

    1. 修改index.html 前端页面:

    在这里插入图片描述

    1. 后端实现(在com.zql.controller下面创建 LoginController.java
    package com.zql.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.thymeleaf.util.StringUtils;
    
    import javax.jws.WebParam;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    
    @Controller
    public class LoginController {
    
        @RequestMapping("/user/login")
        public String login(
                @RequestParam("username") String username,
                @RequestParam("password") String password,
                Model model){
    
            if(!StringUtils.isEmpty(username) && "123".equals(password)){
    
                return "redirect:/main.html";
            }else{
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    1. 修改 MyMvcConfig.java 登录映射在这里插入图片描述

    4.前端 index.html 修改

    在这里插入图片描述

    测试:用户名随意输入,密码:123,登录不成功显示

    在这里插入图片描述

    登录成功显示(直接跳到 dashboard.html 页面)

    在这里插入图片描述

    4.2 登录拦截器

    1. 在 LoginController.java中修改
      在这里插入图片描述

    2. 在 com.zql.config报下创建 LoginHandlerInterceptor.java

    package com.zql.config;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @Author:Daniel
     * @Version 1.0
     */
    public class LoginHandlerInterceptor  implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            //登录成功,应该有用户得 session
    
            Object loginUser = request.getSession().getAttribute("loginUser");
    
            if(loginUser == null){  //没有登录
    
                request.setAttribute("msg","没有权限,请先登录");
    
                request.getRequestDispatcher("/index.html").forward(request,response);
    
                return false;
            }else{
    
                return true;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    1. 映射到容器

    MyMvcConfig.java

    在这里插入图片描述

    //自定义得国家化组件就生效了!
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/*","/img/**","/js/**");
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    启动测试,被拦截

    在这里插入图片描述

    1. 显示登录名

    在这里插入图片描述

    1. 最终测试(登录成功显示):

    在这里插入图片描述

  • 相关阅读:
    JavaScript 对于 ?. 和 ?? 的认识及理解
    Qt EventFilter 事件过滤器 及传递 鼠标键盘事件捕捉
    露营热度大涨,户外露营企业如何进行软文营销
    期末Java题库--判断题之错误篇2
    Wireshark CLI | Mergecap 篇
    UE4 Niagara 关卡3.1官方案例解析二
    Java8新特性—四大内置函数式接口
    Leetcode101对称的二叉树
    iperf3交叉编译
    FX粒子(Niagara系统)、潮湿贴花——简单雨和雨后潮湿
  • 原文地址:https://blog.csdn.net/weixin_42171159/article/details/126916550