SpringBoot全网最详细学习笔记05

SpringBoot学习笔记05

员工管理系统

1. 准备工作

  1. 静态资源下载

    网址: https://pan.baidu.com/s/1kkr_TNtmMkKBJr1DYMguAw

    提取码: zyr2

    下载解压得到下图文件:

    image-20210516164635603

  2. 导入SpringBoot项目中

    • 将html页面全部导入到templates中
    • 将asserts里的文件全部导入到static中
  3. 编写pojo类

    部门类:

    package com.zyr.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @Author: ZYR
     * @Date: 2021/5/16 11:44
     * @Version 1.0
     */
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Department {
    
        private Integer id;
        private String departmentName;
    }
    

    员工类:

    package com.zyr.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    /**
     * @Author: ZYR
     * @Date: 2021/5/16 11:47
     * @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();
        }
    }
    
  4. 模拟数据库数据以及Dao层编写:

    编写DepartmentDao

    package com.zyr.dao;
    
    import com.zyr.pojo.Department;
    import org.springframework.stereotype.Repository;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @Author: ZYR
     * @Date: 2021/5/16 11:52
     * @Version 1.0
     */
    
    @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(101, "市场部"));
            departments.put(103, new Department(101, "教研部"));
            departments.put(104, new Department(101, "运营部"));
            departments.put(105, new Department(101, "后勤部"));
        }
    
        //获得所有部门信息
        public Collection<Department> getDepartments(){
            return departments.values();
        }
    
        //通过id得到部门
        public Department getDepartmentById(Integer id){
            return departments.get(id);
        }
    
    }
    
    

    编写EmployeeDao

    package com.zyr.dao;
    
    import com.zyr.pojo.Department;
    import com.zyr.pojo.Employee;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @Author: ZYR
     * @Date: 2021/5/16 12:18
     * @Version 1.0
     */
    
    @Repository
    public class EmployeeDao {
        //模拟数据库中的数据
        private static Map<Integer, Employee> employees = null;
    
        //员工有所属的部门
        @Autowired
        private DepartmentDao departmentDao;
    
        static {
            employees = new HashMap<Integer, Employee>();
            employees.put(1001, new Employee(1001, "AA", "A123456@qq.com", 0, new Department(101,"后勤部")));
            employees.put(1002, new Employee(1002, "BB", "B123456@qq.com", 1, new Department(102,"后勤部")));
            employees.put(1003, new Employee(1003, "CC", "C123456@qq.com", 0, new Department(103,"后勤部")));
            employees.put(1004, new Employee(1004, "DD", "D123456@qq.com", 1, new Department(104,"后勤部")));
            employees.put(1005, new Employee(1005, "EE", "E123456@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);
        }
    
    }
    

2. 首页实现

templates无法直接访问, 首页配置访问有两种方式:

  1. 编写Controller

    在controller中编写IndexController

    @Controller
    public class IndexController {
    
        @RequestMapping({"/", "/index.html"})
        public String index(){
            return "index";
        }
    
    }
    
  2. 拓展SpringMVC

    编写config包下的MyMvcConfig

    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index.html").setViewName("index");
        }
    }
    

样式加载问题

  1. 在前端页面导入thymeleaf模板引擎命名空间

    xmlns:th="http://www.thymeleaf.org"
    

    相应标签根据thymeleaf语法修改<在线连接不必修改, url用@{}接管>

  2. 在application.yaml中关闭thymeleaf模板引擎缓存

    spring:
      thymeleaf:
        cache: false
    
  3. 完成修改

3. 页面国际化

1. 检查idea的编码格式

设置为UTF-8

image-20210517110736296

2. 配置文件编写
  1. 我们在resources资源文件下新建一个i18n目录,存放国际化配置文件

  2. 建立一个login.properties文件,还有一个login_zh_CN.properties;发现IDEA自动识别了我们要做国际化操作;文件夹变了!

    image-20210517120759995

  3. 我们可以在这上面去新建一个文件

    image-20210517120937804

    image-20210517120955216

  4. 接下来,我们就来编写配置,我们可以看到idea下面有另外一个视图:

    image-20210517121234869

    这个视图我们点击 + 号就可以直接添加属性了;我们新建一个login.tip,可以看到边上有三个文件框可以输入:

    image-20210517121510167

    我们添加一下首页的内容!

    然后去查看我们的配置文件:

    login.properties :默认

    login.btn=登录
    login.password=密码
    login.remember=记住我
    login.tip=请登录
    login.username=用户名
    

    英文:

    login.btn=Sign in
    login.password=Password
    login.remember=Remember me
    login.tip=Please sign in
    login.username=Username
    

    中文

    login.btn=登录
    login.password=密码
    login.remember=记住我
    login.tip=请登录
    login.username=用户名
    

    OK,配置文件步骤搞定!

3. 配置文件生效探究

我们去看一下SpringBoot对国际化的自动配置!这里又涉及到一个类:MessageSourceAutoConfiguration

里面有一个方法,这里发现SpringBoot已经自动配置好了管理我们国际化资源文件的组件 ResourceBundleMessageSource;

// 获取 properties 传递过来的值进行判断
@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;
}

我们真实 的情况是放在了i18n目录下,所以我们要去配置这个messages的路径;

spring:
  messages:
    basename: i18n.login
4. 配置页面国际化值

去页面获取国际化的值,查看Thymeleaf的文档,找到message取值操作为:#{…}。我们去页面测试下:

IDEA还有提示,非常智能的!

image-20210517194715090

我们可以去启动项目,访问一下,发现已经自动识别为中文的了!

image-20210517194740619

但是我们想要更好!可以根据按钮自动切换中文英文!

5. 配置国际化解析

在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!

我们去我们webmvc自动配置文件,寻找一下!看到SpringBoot默认配置:

@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 Locale resolveLocale(HttpServletRequest request) {
    Locale defaultLocale = this.getDefaultLocale();
    // 默认的就是根据请求头带来的区域信息获取Locale进行国际化
    if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
        return defaultLocale;
    } else {
        Locale requestLocale = request.getLocale();
        List<Locale> supportedLocales = this.getSupportedLocales();
        if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
            Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
            if (supportedLocale != null) {
                return supportedLocale;
            } else {
                return defaultLocale != null ? defaultLocale : requestLocale;
            }
        } else {
            return requestLocale;
        }
    }
}

那假如我们现在想点击链接让我们的国际化资源生效,就需要让我们自己的Locale生效!

我们去自己写一个自己的LocaleResolver,可以在链接上携带区域信息!

修改一下前端页面的跳转连接:

<!-- 这里传入参数不需要使用 ?使用 (key=value)-->
<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>

我们去写一个处理的组件类!

package com.zyr.config;


import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @Author: ZYR
 * @Date: 2021/5/17 20:12
 * @Version 1.0
 */

public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String language = request.getParameter("l");
        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 request, HttpServletResponse response, Locale locale) {

    }
}

为了让我们的区域化信息能够生效,我们需要再配置一下这个组件!在我们自己的MvcConofig下添加bean;

//自定义的国际化组件就生效了
@Bean
public LocaleResolver localeResolver(){
   return new MyLocaleResolver();
}

我们重启项目,来访问一下,发现点击按钮可以实现成功切换!搞定收工!

4. 登录功能实现

1. 登录跳转实现
  1. 在index.html中编写表单提交跳转位置

    image-20210517203835387

  2. 编写一个LoginController

    用于接收登录请求, 先进行测试能否成功跳转

    package com.zyr.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * @Author: ZYR
     * @Date: 2021/5/17 20:21
     * @Version 1.0
     */
    
    @Controller
    public class LoginController {
    
        @RequestMapping("/user/login")
        @ResponseBody
        public String login(){
            return "OK";
        }
    
    }
    

    运行,随意输入用户名密码, 点击登录, 成功!

    image-20210517204105091

2. 登录业务设计
  1. 在index.html中添加username&password

    image-20210517204244239

    在LoginControlller中添加相应内容

    @Controller
    public class LoginController {
    
        @RequestMapping("/user/login")
        public String login(@RequestParam("username") String username,
                            @RequestParam("password") String password, 
                            Model model){
            
            //具体的业务
            if(!StringUtils.isEmpty(username) && "123456".equals(password)){
                return "dashboard";
            }else {
                //告诉用户登录失败
                model.addAttribute("msg", "用户名或密码错误");
                return "index";
            }
        }
    
    }
    

    运行, 登录成功跳转成功, 登陆失败跳转到首页

  2. 登录失败回显

    在index.html中添加回显标签

    image-20210517205621460

    设置显示条件<如果msg为空不显示>:

    image-20210517205830692

    运行, 测试成功:

    image-20210517205945623

  3. 设置较标准的url

    添加MyMvcConfig内容

    image-20210517210217399

  4. LoginController也要做相应修改

    image-20210517210405288

  5. 成功

    image-20210517210459619

  6. 出现问题, 无论登不登录都能进入后台页面.需要拦截器处理.

3. 登录拦截器
  1. 在config中新建一个LoginHandlerInterceptor

    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;
            }
            
        }
    }
    

    接收到的登录session从LoginController传递而来

    image-20210518095443181

  2. 在MyMvcConfig中配置拦截器

     @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginHandlerInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/index.html", "/", "/user/login", "/css/**", "/js/**", "/img/**");
        }
    

    image-20210518095828729

  3. 运行, 测试, 拦截成功

    image-20210518100021420

  4. 登录成功左上角用户名回显

    修改dashboard.html

    image-20210518100223872

  5. 登录测试, 成功

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5hFEOPXr-1621856671752)(https://zyr-img.oss-cn-hangzhou.aliyuncs.com/img/SpringBoot学习笔记05/image-20210518100312124.png)]
    …(img-BQkXAPJg-1621856671749)]

  6. 在MyMvcConfig中配置拦截器

     @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginHandlerInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/index.html", "/", "/user/login", "/css/**", "/js/**", "/img/**");
        }
    

    [外链图片转存中…(img-WrgH9wOK-1621856671750)]

  7. 运行, 测试, 拦截成功

    [外链图片转存中…(img-mPa3IGk4-1621856671750)]

  8. 登录成功左上角用户名回显

    修改dashboard.html

    [外链图片转存中…(img-DrhSETiJ-1621856671751)]

  9. 登录测试, 成功

    [外链图片转存中…(img-5hFEOPXr-1621856671752)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值