Complete a SpringBoot project - employee management system

SpringBoot project - employee management system

该系统为一个springboot项目——员工管理系统的代码,前端使用的模板是thymeleaf,数据写在了dao层,没有用数据库,完全可以实现增删改查


Table of contents

Table of contents
1. Front-end static resources
2. Project preparation work
3. Code operation: 1. Front-end code operation 2. Dependency import pom.xml file 3. Write configuration file 4. Page internationalization configuration 5. Back-end code writing
4. Start testing

1. Front-end static resource extraction path

这是提供的没有修改过的静态资源

Link: https://pan.baidu.com/s/1kYIa_B4XOGXrdFTTTyC_Rg
Extraction code: 6bmy

这是项目完成的资源包

Link: https://pan.baidu.com/s/1Bt-t6y8RCyMbyzeudyPXtw
Extraction code: 1n3j


2. Project preparation work

SpringBoot+idea tool

1.Create project

First, idea creates a springboot project, file——new——project——next

Insert image description here

Fill in your own content. The Java version I chose is 8. It is best to know the project name clearly.

Insert image description here

I have no choice here, just go to next——finish

Insert image description here

Create some file packages you need, as follows:

Insert image description here

注:准备工作基本完成,下面就是代码的操作了


3. Code operation

1. Front-end code operation

Here, the relevant front-end code files are placed in their respective folders.

Insert image description here

Note: These HTML pages need to add th="http://www.thymeleaf.org" and are hosted by thymeleaf

Insert image description here

1》index.html Modify content

Insert image description here

2》dashboard.html Modify content

Insert image description here
Insert image description here

3》commons.html Modify content

Insert image description hereInsert image description here

4》add.html Modify content

Insert image description here

5》list.html Modify content

Insert image description here

6》update.html Modify content

Insert image description here
Insert image description here

7》404.html Modify content

Insert image description here

前端搞完,就该搞后端以及配置了,顺序不分先后


2. Dependency import pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- 基本设置 The Basics -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--定义了项目属于哪个组,风向标,坐标,是本地仓库中的路径-->
    <groupId>com.study</groupId>
    <!--项目名称-->
    <artifactId>springboot_management_system</artifactId>
    <!--当前的版本号-->
    <version>0.0.1-SNAPSHOT</version>
    <!--元素声明了一个对用户更为友好的项目名称-->
    <name>springboot_management_system</name>
    <!--项目描述-->
    <description>Demo project for Spring Boot</description>

    <properties>
        <!--java版本-->
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--thymeleaf(模板)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--JDBC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--test(测试)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <!--lombok(方面set,get方法)-->
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--Druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--log4j(日志)-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

    </dependencies>

    <build>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.Write configuration file

这里编写了.properties 和 .yml 文件,两者都可用

application.properties

#thymeleaf配置
spring.thymeleaf.cache=false

#国际化配置
spring.messages.basename=i18n.login

#数据源配置,连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/student?useUnicode=true\
  &characterEncoding=UTF-8\
  &useSSL=true\
  &serverTimezone=UTC
  
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#访问页面相关配置
server.servlet.context-path=/yun
server.port=8002

#mybatis配置,扫描路径
mybatis.type-aliases-package=com.study.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

application.yml

#thymeleaf配置
spring:
  thymeleaf:
    cache: false
#国际化配置
  messages:
    basename: i18n.login

#数据源配置,连接数据库
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root1234
    url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource

#访问页面配置
server:
  servlet:
    context-path: /yun
  port: 8002

#mybatis配置,扫描路径
mybatis:
  type-aliases-package: com.study.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

4. Page internationalization configuration

这里介绍下如何配置国际化

Insert image description here
1. Ensure that the encoding language in the idea is UTF-8

Insert image description here

  1. Create three files under i18n, right-click and add

Insert image description here

As shown below

Insert image description here

3. Fill in the content of the page

Insert image description here

login.properties

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

login_en_US.properties

login.tip=Please sign in
login.password=password
login.remember=remember me
login.btn=login
login.username=username

login_zh_CN.properties

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

4. The login page configures the content of the international page**

Insert image description here

5. Add configuration information to the application.properties configuration file, and also add the project path server.servlet.context-path

Insert image description here
Insert image description here
6. Switch between Chinese and English on the page

Insert image description here


5. Back-end code writing

  1. Code under the config package

LoginHandlerInterceptor login interceptor class

/**
 * @Author liuyun
 * @Date 2023/2/21 18:37
 * @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;
        }

    }
}

MyLocaleResolver internationalization class (satisfies the switching display of Chinese and English on the login page)

/**
 * 国际化
 */

public class MyLocaleResolver implements LocaleResolver {
    
    
    //解析请求z
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
    
    
        //获取请求中的语言参数
        String lan = request.getParameter("l");
        Locale locale = Locale.getDefault(); //如果没有就使用默认的

        //如果请求的链接携带了国际化的参数
        if (!StringUtils.isEmpty(lan)) {
    
    
            String[] split = lan.split("_");
            //国家,地区
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
    

    }
}

MyMvcConfig configuration class

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

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

	//拦截器注册类登记
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login", "/asserts/**");
    }
}
  1. Code under the control layer controller package

LoginController login class

/**
 * @Author liuyun
 * @Date 2023/2/21 18:06
 * @Version 1.0
 * 登录注销
 */

@Controller
@Slf4j
public class LoginController {
    
    

    @RequestMapping("/user/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model,
            HttpSession session
    ) {
    
    
        //具体的业务
        if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
    
    
            session.setAttribute("loginUser", username);
            return "redirect:/main.html";
        } else {
    
    
            //告诉用户你登录失败了
            model.addAttribute("msg", "用户名或者密码错误");
            return "index";
        }
    }

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

}

EmployeeController employee list

/**
 * @Author liuyun
 * @Date 2023/2/22 16:33
 * @Version 1.0
 * 员工列表操作
 */

@Controller
public class EmployeeController {
    
    

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    EmployeeMapper employeeMapper;
    
    @RequestMapping("/emps")
    public String list(Model model){
    
    
        //查出员工的所有信息
        Collection<Employee> result = employeeMapper.getAll();
        model.addAttribute("emps", result);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAdd(Model model) {
    
    
        //查出部门的所有信息
        Collection<Department> departments = departmentMapper.getDepartment();
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String add(Employee employee) {
    
    
        System.out.println(employee);
        //员工添加的操作
        employeeMapper.save(employee);
        return "redirect:/emps";
    }

    //去员工的修改页面
    @GetMapping("/upemp/{id}")
    public String toupdataEmp(@PathVariable("id") Integer id, Model model) {
    
    
        //通过id查询员工数据
        Employee employee = employeeMapper.getEmployeeById(id);
        model.addAttribute("emp", employee);
        //查询所有部门信息
        Collection<Department> departments = departmentMapper.getDepartment();
        model.addAttribute("departments", departments);

        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updataEmp(Employee employee) {
    
    
        employeeMapper.save(employee);
        return "redirect:/emps";
    }

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

}

3. Code under the data layer mapper package

这里没有连接数据库,直接在dao层制造的数据

DepartmentMapper department class

/**
 * @Author liuyun
 * @Date 2023/2/21 12:19
 * @Version 1.0
 * 部门mapper
 */

@Repository
public class DepartmentMapper {
    
    
    //模拟数据库的数据

    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> getDepartment() {
    
    
        return departments.values();
    }

    //通过ID的到部门
    public Department getDepartmentById(Integer id) {
    
    
        return departments.get(id);
    }
}

EmployeeMapper employee class


/**
 * @Author liuyun
 * @Date 2023/2/21 12:34
 * @Version 1.0
 * 员工Mapper
 */

@Repository
//员工Dao
public class EmployeeMapper {
    
    
    //模拟数据中的信息
    private static Map<Integer, Employee> employees = null;
    //员工有所属的部门
    @Autowired
    private DepartmentMapper departmentMapper;

    static {
    
    
        //创建一个员工表
        employees = new HashMap<Integer, Employee>();

        employees.put(1001,new Employee(1001,"小a","[email protected]",1,new Department(101,"教学部")));
        employees.put(1002,new Employee(1002,"小s","[email protected]",0,new Department(102,"市场部")));
        employees.put(1003,new Employee(1003,"小f","[email protected]",0,new Department(103,"教研部")));
        employees.put(1004,new Employee(1004,"小t","[email protected]",0,new Department(104,"运营部")));
        employees.put(1005,new Employee(1005,"小y","[email protected]",1,new Department(105,"后勤部")));
        employees.put(1006,new Employee(1006,"小e","[email protected]",0,new Department(102,"市场部")));
        employees.put(1007,new Employee(1007,"小w","[email protected]",1,new Department(103,"教研部")));
        employees.put(1008,new Employee(1008,"小q","[email protected]",1,new Department(104,"运营部")));
        employees.put(1009,new Employee(1009,"小j","[email protected]",1,new Department(105,"后勤部")));
        employees.put(1010,new Employee(1010,"小m","[email protected]",0,new Department(101,"教学部")));
    }

    //主键自增加
    private static Integer initId = 1006;

    //增加一个员工
    public Integer save(Employee employee) {
    
    
        try {
    
    
            if (employee.getId() == null) {
    
    
                employee.setId(initId++);
            }
            employee.setDepartment(departmentMapper.getDepartmentById(employee.getDepartment().getId()));

            employees.put(employee.getId(), employee);
            if(employee!=null){
    
    
                return 1;
            }else {
    
    
                return 0;
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
            return null;
        }
    }

    //查询全部的员工信息
    public Collection<Employee> getAll() {
    
    
        return employees.values();
    }

    //通过ID查询员工
    public Employee getEmployeeById(Integer id) {
    
    
        return employees.get(id);
    }

    //通过ID删除员工
    public Integer delete(Integer id) {
    
    
        Employee result = employees.remove(id);
        if (result!=null){
    
    
            return 1;
        }else{
    
    
            return 0;
        }
    }
}

4. Code under the entity class pojo package

Department department table

/**
 * @Author liuyun
 * @Date 2023/2/21 12:05
 * @Version 1.0
 * 部门表
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
//部门表
public class Department {
    
    
    private Integer id;
    private String departmentName;

}

Employee employee table


/**
 * @Author liuyun
 * @Date 2023/2/21 12:08
 * @Version 1.0
 * 员工表
 */

@Data
@NoArgsConstructor
//员工表
public class Employee {
    
    
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private Department department;
    private Date birth;

    public Employee(int 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();
    }
}

Finished writing, start testing

Insert image description here
Employee list page

Insert image description here


Reference: Article , Mad God Said


Hope it helps you

~感谢您的光临~

Guess you like

Origin blog.csdn.net/m0_50762431/article/details/129139656