SpringBoot プロジェクトを完了する - 従業員管理システム

SpringBoot プロジェクト - 従業員管理システム

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


目次

目次
1. フロントエンドの静的リソース
2. プロジェクトの準備作業
3. コード操作: 1. フロントエンド コード操作 2. 依存関係インポート pom.xml ファイル 3. 設定ファイルの書き込み 4. ページ国際化設定 5. バックエンド コードの書き込み
4. テストを開始する

1. フロントエンド静的リソース抽出パス

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

リンク: https://pan.baidu.com/s/1kYIa_B4XOGXrdFTTTyC_Rg
抽出コード: 6bmy

这是项目完成的资源包

リンク: https://pan.baidu.com/s/1Bt-t6y8RCyMbyzeudyPXtw
抽出コード: 1n3j


2. プロジェクトの準備作業

SpringBoot+アイデアツール

1.プロジェクトの作成

まず、idea は springboot プロジェクト、file——new——project——next を作成します。

ここに画像の説明を挿入します

独自の内容を入力してください。私が選択した Java バージョンは 8 です。プロジェクト名を明確に知っておくことが最善です。

ここに画像の説明を挿入します

ここでは選択の余地はありません。次へ進みます——終了

ここに画像の説明を挿入します

次のように、必要なファイル パッケージをいくつか作成します。

ここに画像の説明を挿入します

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


3. コード操作

1. フロントエンドコードの操作

ここでは、関連するフロントエンド コード ファイルがそれぞれのフォルダーに配置されます。

ここに画像の説明を挿入します

注: これらの HTML ページは th="http://www.thymeleaf.org" を追加する必要があり、thymeleaf によってホストされています。

ここに画像の説明を挿入します

1》index.html 内容を変更する

ここに画像の説明を挿入します

2》dashboard.html コンテンツの変更

ここに画像の説明を挿入します
ここに画像の説明を挿入します

3》commons.html コンテンツの変更

ここに画像の説明を挿入しますここに画像の説明を挿入します

4》add.html 内容を変更

ここに画像の説明を挿入します

5》list.html 内容を変更する

ここに画像の説明を挿入します

6》update.html 内容を修正

ここに画像の説明を挿入します
ここに画像の説明を挿入します

7》404.html 内容の変更

ここに画像の説明を挿入します

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


2. 依存関係インポート pom.xml ファイル

<?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.設定ファイルの書き込み

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

アプリケーションのプロパティ

#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

アプリケーション.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. ページの国際化設定

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

ここに画像の説明を挿入します
1. アイデアのエンコード言語が UTF-8 であることを確認します。

ここに画像の説明を挿入します

  1. i18n の下に 3 つのファイルを作成し、右クリックして追加します

ここに画像の説明を挿入します

以下に示すように

ここに画像の説明を挿入します

3. ページの内容を入力します

ここに画像の説明を挿入します

ログイン.プロパティ

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. ログイン ページは国際ページのコンテンツを構成します**

ここに画像の説明を挿入します

5. 構成情報を application.properties 構成ファイルに追加し、プロジェクト パス server.servlet.context-path も追加します。

ここに画像の説明を挿入します
ここに画像の説明を挿入します
6. ページ上で中国語と英語を切り替えます

ここに画像の説明を挿入します


5. バックエンドコードの記述

  1. config パッケージ内のコード

LoginHandlerInterceptor ログイン インターセプタ クラス

/**
 * @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 国際化クラス (ログインページの中国語と英語の切り替え表示に対応)

/**
 * 国际化
 */

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
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. 制御層コントローラーパッケージの下のコード

LoginController ログイン クラス

/**
 * @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 従業員リスト

/**
 * @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. データ層マッパー パッケージの下のコード

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

DepartmentMapper 部門クラス

/**
 * @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 従業員クラス


/**
 * @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. エンティティクラス pojo パッケージの下のコード

部門部門テーブル

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

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

}

従業員テーブル


/**
 * @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();
    }
}

書き終わったのでテスト開始

ここに画像の説明を挿入します
社員一覧ページ

ここに画像の説明を挿入します


参考:記事Mad God Said」


これがお役に立てば幸いです

~感谢您的光临~

おすすめ

転載: blog.csdn.net/m0_50762431/article/details/129139656