狂神。SpringBoot员工管理系统项目练习。

SpringBoot 员工管理系统

看b站狂神 SpringBoot 员工管理系统项目练习。

代码链接:

链接:https://pan.baidu.com/s/1kO9xdr5vACs-xKlyOkoT4g
提取码:7xyc

1、准备工作

1.1、新建项目

首先,我们新建一个 springboot 项目。

然后,在 resources/stastic 下导入 img、js、css 静态资源;在 resources/templates 下导入 html 静态资源。

导入后我们的项目目录如下所示:(i18n是国际化的配置文件,后面再说;templates 下有的 html 放在了包里,方便管理)

在这里插入图片描述

在 src/main/java/com/kuang 下新建我们需要的包:config、controller、pojo、dao。

目录如下图所示:

在这里插入图片描述

然后,我们在 pom 文件中导入我们需要的的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  
    <!--webjars-->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.4.1</version>
    </dependency>
  
    <!--thymeleaf-->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  
		<!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

接下来,我们伪造一个数据库。pojo当作数据库的表,dao层来模拟数据库中的数据。

1.2、编写实体类pojo

我们在pojo下新建了一个部门类(Department)和一个员工类(Employee)来当作数据库的表。

这里不要忘了在 pom 文件中引入 lombok(我们在开头已经引入了)。

部门类 Department:

package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

//部门表
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {

    private Integer id;
    private String departmentName;

}

员工类 Employee:

package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

//员工表
@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.3、编写dao层

我们在 dao 下新建了一个 DepartmentDao 和一个 EmployeeDao 来模拟数据库中的数据。

DepartmentDao:

package com.kuang.dao;

import com.kuang.pojo.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//部门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);
    }

}

EmployeeDao:

package com.kuang.dao;

import com.kuang.pojo.Department;
import com.kuang.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;

//员工dao
@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、首页实现

2.1、编写 MyMvcConfig

我们在 config 新建一个 MyMvcConfig ,用来视图跳转。

我们访问 localhost:8080/ 或者 locahost:8080/index.html 都可以跳转到主页 index.html 。

package com.kuang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
  
}

2.2、使用 thymeleaf

这里不要忘了在 pom 文件中引入 thymeleaf 的依赖和启动器。(我们在开头已经引入了)。

首先,我们在 application.properties 中配置关闭模版引擎的缓存:

# 关闭模版引擎的缓存
spring.thymeleaf.cache=false

# 如果我们加上这个配置,可以使访问的url路径变为 localhost:8080/kuang/index.html
# server.servlet.context-path=/kuang

然后,我们在所有 html 页面都需要引入 Thymeleaf 命名空间:

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

然后,修改所有页面静态资源的引入,修改为 @{...} 链接表达式,使所有的静态资源都需要使用 thymeleaf 接管。

例如在首页 index.html 中:

在这里插入图片描述

最后,启动程序,访问 localhost:8080/ 或者 locahost:8080/index.html 查看主页面:

在这里插入图片描述

访问主页成功!

3、页面国际化

我们的网站有时候需要去涉及中英文甚至多语言的切换,这时候我们就需要国际化了!

3.1、编码设置

我们先在IDEA中统一设置 properties 的编码问题!否则会出现乱码情况!

在这里插入图片描述

3.2、配置文件编写

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

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

在这里插入图片描述

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

在这里插入图片描述

弹出如下页面,我们再添加一个英文的。

在这里插入图片描述

这样就快捷多了!

在这里插入图片描述

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

这个视图我们点击 + 号就可以直接添加属性了,我们新建一个login.tip,可以看到边上有三个文件框可以输入。我们添加一下首页的内容,然后依次添加其他页面内容即可!(我这个版本idea添加不了,不知道为啥,但是可以直接在配置文件中添编写。)

在这里插入图片描述

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

login.properties(默认):

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

login_en_US.properties(英文):

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

login_zh_CN.properties(中文):

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

OK,配置文件步骤搞定!

3.3、配置文件生效探究

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

里面有一个 messageSource 方法,这里发现 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 目录下,所以我们要去 application.properties 配置文件中配置这个 messages 的路径:

# 我们的配置文件的真实位置
spring.messages.basename=i18n.login

3.4、配置页面国际化值

去页面获取国际化的值,Thymeleaf 的message取值操作为:#{...}

我们去 index.html 页面测试下:

在这里插入图片描述

我们发现我们在修改的时候idea是有提示的!

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

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

3.5、配置国际化解析

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

我们去我们 WebMvcAutoConfiguration 自动配置文件找一下!看到 SpringBoot 的默认配置:

@Override
@Bean
@ConditionalOnMissingBean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
public LocaleResolver localeResolver() {
  // 容器中没有就自己配,有的话就用用户配置的。
  if (this.webProperties.getLocaleResolver() == WebProperties.LocaleResolver.FIXED) {
    return new FixedLocaleResolver(this.webProperties.getLocale());
  }
  // 接收头国际化分解。
  AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
  localeResolver.setDefaultLocale(this.webProperties.getLocale());
  return localeResolver;
}

AcceptHeaderLocaleResolver 这个类中有这样一个方法:

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

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

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

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

<!-- l是传递的参数。这里传入参数不用 ?   使用(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>

我们在 config 下去写一个处理的组件类 MyLocaleResolver:

package com.kuang.config;

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;

public class MyLocaleResolver implements LocaleResolver {

    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {

        //获取请求中的语言参数。
        String language = request.getParameter("l");

        //如果没有就使用默认的。
        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 request, HttpServletResponse response, Locale locale) {

    }

}

为了让我们的区域化信息能够生效,我们需要再配置一下这个组件!在我们自己的 MyMvcConfig 下添加 bean,使它注入到容器中:

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

我们重新运行项目,发现点击按钮可以实现成功切换:

在这里插入图片描述

在这里插入图片描述

4、登录和注销功能的实现

4.1、登陆功能

我们的目的当我们点击登陆的时候,会进入到主页面 dashboard 。

  1. 我们在 index.html 中的表单中编写一个提交的地址 /user/login。并给用户名和密码的输入框添加 name 属性,目的是为了传递参数:

在这里插入图片描述

  1. 在 controller 下编写一个 LoginController:
package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
  
    //登陆
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,Model model, HttpSession session){

        //具体的业务:username任意,password为123456.
        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("LoginUser",username);
            return "dashboard";
        }else {
            //告诉用户,你登录失败了!
            model.addAttribute("msg","用户名或密码错误!");
            return "index";
        }
    }
  
}
  1. 然后我们在 index.html 首页中加一个 p 标签用来显示 controller 返回的信息 msg :
<!--如果msg的值为空,则不显示消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  1. 我们测试一下,启动项目,如果我们输入符合条件的的用户名和密码,回来到 dashboard 页面:

在这里插入图片描述

如果我们输入的密码不正确,会显示提示信息:

在这里插入图片描述

  1. 此时我们的 url 为http://localhost:8080/user/login?username=admin&password=123456,在实际的开发中,我们需要优化一下它。

我们在自定义的配置类 MyMvcConfig 中加一句代码:

// 访问 /main.html 页面就跳转到 dashboard 页面。
registry.addViewController("/main.html").setViewName("dashboard");

然后我们把 LoginController 中的 return "index" ; 改成了 return "redirect:/main.html" ;

当登录成功时,就会重定向到 main.html 页面,也就跳转到了 dashboard 页面。

我们再次重启测试,登陆成功后,这是我们的url为 http://localhost:8080/main.html.

此时我们会出现一个问题,就是在我们每登录成功的时候,直接访问 http://localhost:8080/main.html ,这是也会跳转到 dashboard 页面,这时我们就需要编写一个拦截器来解决这个问题。

4.2、注销功能

首先,我们在头部导航栏的注销标签处添加一个 href 属性,点击请求 /user/logout.

在这里插入图片描述

然后,我们在 LoginController 中编写一个 logout 方法处理请求,使它重定向到登陆页面:

//注销
@RequestMapping("/user/logout")
public String logout(HttpSession session){
    session.invalidate();
    return "redirect:/index.html";
}

最后,我们启动程序,登陆成功后,点击注销成功返回到登陆页面,测试成功!

5、登录拦截器

为了解决上一节所述的问题,我们需要自定义一个拦截器。拦截器的目的在于当我们没有登陆成功时,直接访问主页会被弹回到登陆页面。

  1. 在 config 目录下,新建一个登录拦截器类 LoginHandlerInterceptor :
package com.kuang.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //登陆成功之后,应该有用户的sesion:
        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. 然后在 MyMvcConfig 配置类中重新关于拦截器的方法,把我们编写的拦截器注入进去。这里我们需要编写需要拦截的路径和不需要拦截的路径,注意不要拦截静态资源和主页相关的请求。
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
 		.excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
    //   /* 是拦截所有的文件夹,不包含子文件夹 ; /** 是拦截所有的文件夹及里面的子文件夹/.
}
  1. 我们在后台的导航栏,可以获取用户登录的信息。

在这里插入图片描述

  1. 重新启动项目,直接访问http://localhost:8080/main.html,此时发现会被拦截:

在这里插入图片描述

如果我们正常登陆的话,再访问 http://localhost:8080/main.html 则不会被拦截!

6、展示员工列表

6.1、实现员工列表视图跳转

我们在 templates 目录下新建一个 emp 包,用来放所有关于员工信息的页面,我们将 list.html 页面移入该包中,方便管理。

首先,我们在 dashboard.html 页面中员工管理部分标签添加 th:href 属性,实现点击标签后,请求 /emps 路径跳转到 list.html 展示所有的员工信息。

在这里插入图片描述

然后,我们编写对应大的 controller ,在 controller 下新建一个 EmployeeController 来处理请求。

EmployeeController:

package com.kuang.controller;

import com.kuang.dao.DepartmentDao;
import com.kuang.dao.EmployeeDao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;

@Controller
public class EmployeeController {

    //自动装配
    @Autowired
    EmployeeDao employeeDao;

    //展示全部的员工
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emps/list";
    }

}

然后,我们重启项目进行测试,登陆成功后,我们点击员工管理,成功跳转到员工页面。

但是我们想要实现在侧边栏点击哪个标签,哪个标签就高亮。这个我们在第 3 小节介绍。

6.2、Thymeleaf 实现页面公共部分提取

Thymeleaf 可以这样实现页面公共部分提取:

  1. 使用 th:fragment="模版名" 来抽取公共片段。

  2. 使用 th:replace="~{······}" 来引入公共片段。(也可以使用 th:insert

具体实现:

我们在 templates 目录下新建一个 commons 包,再在这个包下新建一个 commons.html 用来编写页面公共部分的代码。

commons.html:利用 th:fragment 来抽取页面的公共部分,我们提取的是头部导航栏侧边栏

在这里插入图片描述

然后,我们删除 dashboard.html 和 list.html 中头部导航栏侧边栏的代码,再在 dashboard.html 和 list.html 中删除的地方使用 th:replace 来插入提取出来的公共部分 topbar 和 sidebar 。

在这里插入图片描述

再次重启项目进行测试,登陆成功后,可以看到头部导航栏侧边栏,代表我们插入成功!

6.3、 点击高亮处理

在页面中,使标签高亮的代码是class="nav-link active"我们发现加上 active 就会高亮

我们可以使用传递参数来实现判断该标签是否高亮。

首先在 dashboard.html 和 list.html 的侧边栏标签传递一个参数 active。

<!--侧边栏-->
<!--传递参数给组件-->
<!--dashboard.html:-->
<div th:replace="~{commons/commons::sidebar(active='main.html')}"></div>

<!--侧边栏-->
<!--list.html:-->
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>

然后我们在 commons.html 页面对应标签部分使用 ${} 来接收参数,并使用三元运算符进行判断是否需要高亮。

在这里插入图片描述

再次重启项目进行测试,登录成功后,我们发现默认首页高亮,再点击员工管理员工管理高亮而首页不再高亮,测试成功!

在这里插入图片描述

6.4、显示所有的员工信息

修改 list.html 页面,使表格展示的是我们的员工信息。

在这里插入图片描述

注意:

  • 我们从 emp 中取值有两种方法:使用 th:text="${}"[[${}]]
  • 性别:0代表女,1代表男。
  • 我们这里为日期显示设置了固定的格式。
  • thymeleaf 使用 # 来使用方法。
  • 我们还添加了删除和编辑两个标签,方便后面使用。

修改完成后,重新启动项目,查看所有员工信息,测试成功:

在这里插入图片描述

7、增加员工实现

7.1、实现跳转到增加员工页面

首先在 list.html 页面增添一个添加员工的按钮,点击该按钮时发起一个请求/epp

在这里插入图片描述

然后,编写对应的 controller 来处理我们的请求。

这里通过 get 方式提交请求,在 EmployeeController 中添加一个方法 toAddpage 用来处理请求,并返回 add .html 页面:

@Autowired
DepartmentDao departmentDao;

//添加新的员工
@GetMapping("/emp")
public String toAddpage(Model model){
    //查出所有部门的信息。
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emps/add";
}

然后,我们编写 add.html 页面,在 templates/emp下新建一个 add.html,并把 list.html 页面的内容复制进来。

然后把 main 标签里的内容改为以下表单:

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">

  <!--这里用post提交方式,Restfull风格-->
  <form th:action="@{/emp}" method="post" >
    <div class="form-group" ><label>LastName</label>
      <input class="form-control" placeholder="kuangshen" type="text" name="lastName">
    </div>
    <div class="form-group" ><label>Email</label>
      <input class="form-control" placeholder="24736743@qq.com" type="email" name="email">
    </div>
    <div class="form-group"><label>Gender</label><br/>
      <div class="form-check form-check-inline">
        <input class="form-check-input" name="gender" type="radio" value="1">
        <label class="form-check-label"></label>
      </div>
      <div class="form-check form-check-inline">
        <input class="form-check-input" name="gender" type="radio" value="0">
        <label class="form-check-label"></label>
      </div>
    </div>
    <div class="form-group" ><label>department</label>
      <!--我们在controller接收的是一个Employee,所以我们需要提交的是其中一个属性!-->
      <select class="form-control" name="department.id">
        <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
      </select>
    </div>
    <div class="form-group" >
      <label >Birth</label>
      <input class="form-control" placeholder="kuangstudy" type="text" name="birth">
    </div>
    <button class="btn btn-primary" type="submit">添加</button>
  </form>

</main>

注意:

  • 我们的表单用 post 方式提交,实现请求相同,请求方式不同。
  • 我们需要在每个元素上加上 name 。
  • 我们在 controller 接收的是一个 Employee,所以我们需要提交的是其中一个属性!
<select class="form-control" name="department.id">
  <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" 		   
          th:value="${dept.getId()}"></option>
</select>

最后,重新启动项目进行测试,点击添加员工,成功跳转到 add.html 页面成功!

在这里插入图片描述

7.2、实现具体的添加功能

我们的目的是在 add.html 页面,填上所有的信息之后,点击添加按钮,添加成功并返回到 list.html 页面!

首先,我们以 post 方式发出一个请求:

<form th:action="@{/emp}" method="post" >

然后,在 EmployeeController 中添加一个 addEmp 方法来处理请求:

//添加的操作。请求方式不同。
@PostMapping("/emp")
public String addEmp(Employee employee){
    employeeDao.save(employee); //调用地底层业务方法。保存员工信息
    return "redirect:/emps";
}

这里,SpringMVC默认日期是按照 / 的方式提交,比如 2022/01/01 。如果我们想要改成 2022-01-01 的格式,我们可以在 application.properties 中配置一下:

# 时间日期格式化!
spring.mvc.format.date=yyyy-MM-dd HH:mm:ss

最后,我们重启项目进行测试,添加新员工成功!

8、修改员工信息

8.1、实现跳转到修改员工页面

我们的目的是当我们点击编修改时,会跳到 update.html 页面,修改完信息后,点击修改,会重新跳到 list.html 页面并显示修改后的信息!

首先,我们将 list.html 页面的修改标签添加 href 属性,实现点击请求 /edit/{id参数} 到修改页面:

<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">修改</a>

然后,我们在 EmployeeController 添加一个 toUpdateEmp 方法来处理请求,并跳转到 update.html 页面:

//到员工的修改页面。
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
    //查出原来的数据。
    Employee employee = employeeDao.getEmployeeById(id);
    model.addAttribute("employee",employee);
    //查出所有部门的信息。
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emps/update";
}

接下来,我们编写 update.html 页面,在 templates/emp 下新建一个 update.html 页面,复制 add.html 中的代码并修改 main 标签中的代码:

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">

  <form th:action="@{/updateEmp}" method="post" >
    <!--添加一个隐藏域,如果没有id的话,id会自增-->
    <input type="hidden" name="id" th:value="${employee.getId()}">
    <div class="form-group" ><label>LastName</label>
      <input th:value="${employee.getLastName()}" class="form-control" placeholder="kuangshen" type="text" name="lastName">
    </div>
    <div class="form-group" ><label>Email</label>
      <input th:value="${employee.getEmail()}" class="form-control" placeholder="24736743@qq.com" type="email" name="email">
    </div>
    <div class="form-group"><label>Gender</label><br/>
      <div class="form-check form-check-inline">
        <input th:checked="${employee.getGender()==1}" class="form-check-input" name="gender" type="radio" value="1">
        <label class="form-check-label"></label>
      </div>
      <div class="form-check form-check-inline">
        <!--checked为布尔值-->
        <input th:checked="${employee.getGender()==0}" class="form-check-input" name="gender" type="radio" value="0">
        <label class="form-check-label"></label>
      </div>
    </div>
    <div class="form-group" ><label>department</label>
      <!--我们在controller接收的是一个Employee,所以我们需要提交的是其中一个属性!-->
      <select class="form-control" name="department.id">
        <!--selected为布尔值-->
        <option th:selected="${dept.getId()==employee.getDepartment().getId()}"
            th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
      </select>
    </div>
    <div class="form-group" >
      <label >Birth</label>
      <input th:value="${#dates.format(employee.getBirth(),'yyyy-MM-dd HH:mm:ss')}" class="form-control" placeholder="kuangstudy" type="text" name="birth">
    </div>
    <button class="btn btn-primary" type="submit">修改</button>
  </form>

</main>

重新启动项目进行测试,成功跳转到编辑页面!

8.2、实现具体的修改功能

我们的目的是在 update.html 页面,修改完所有的信息之后,点击修改按钮,修改成功并返回到 list.html 页面!

首先,提交表单时发出一个请求:

<form th:action="@{/updateEmp}" method="post" >

然后,在 EmployeeController 中添加一个 addEmp 方法来处理请求:

//修改信息
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
    employeeDao.save(employee);
    return "redirect:/emps";
}

然后,添加一个隐藏域来传递id参数:(因为我们在dao层的代码中判断有没有员工的id,有的话修改,没的话增加一个)

<!--如果没有id的话,id会自增-->
<input type="hidden" name="id" th:value="${employee.getId()}">

最后,我们重启项目进行测试,任意修改一个员工的信息(注意我们自己设置的日期格式),修改成功!


**注意:**如果idea中使用 thymeleaf 时爆红按以下方法设置一下:

在这里插入图片描述

如果还爆红但能运行的话,不用管他!

9、删除员工实现

首先,我们将 list.html 页面的删除标签添加 href 属性,实现点击请求 /delemp/{id参数} 到修改页面:

<a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${emp.getId()}">删除</a>

然后,我们在 EmployeeController 添加一个 deleteEmp 方法来处理请求:

//删除员工
@GetMapping("/delemp/{id}")
public String deleteEmp(@PathVariable("id") int id){
    employeeDao.delete(id);
    return "redirect:/emps";
}

重新启动项目进行测试,删除成功!

10、404页面定制

我们只需要在 templates 目录下新建一个 error 包,然后将 404.html 页面放进去,SpringBoot就会自动找到这个页面!

我们启动项目进行测试,登陆成功后,随便访问一个不存在的页面:

在这里插入图片描述

测试成功!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值