SCRUM1

昨天的成就:
在昨天我大概总结这整个项目的大纲,完成了项目里web端的登录功能,与主界面包括下拉菜单的展示,大概花费了我5到6小时的时间。
展示:
LoginController.java

package com.example.demo.controller;

import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController {
    
    @Autowired
    private UserService userService;

    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(
        @RequestParam String id,
        @RequestParam String password,
        HttpSession session
    ) {
        try {
            Integer userId = Integer.parseInt(id);
            String result = userService.login(userId, password, session);
            // 返回 JSON 格式
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", result
            ));
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "账号格式错误"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }

    // 获取当前用户信息接口
    @GetMapping("/current-user")
    public ResponseEntity<?> getCurrentUser(HttpSession session) {
        Integer permissionLevel = (Integer) session.getAttribute("permissionLevel");
        if (permissionLevel == null) {
            return ResponseEntity.status(401).body(Map.of("message", "未登录"));
        }
        return ResponseEntity.ok(Map.of(
            "permissionLevel", permissionLevel
        ));
    }
}

PageController.java

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PageController {
    // 主登录页面
    @GetMapping("/")
    public String index() {
        return "index.html";
    }

    // 公司主界面
    @GetMapping("/home")
    public String home() {
        return "home.html";
    }
}

User.java

package com.example.demo.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String password;
    
    @Column(name = "permission_level") // 关键修复:映射下划线列名
    private Integer permissionLevel;
    private String position;
    private String department;    // 所属部门
    private Integer positionLevel;// 职级

    // -------------------- Getters --------------------
    public Integer getId() {
        return id;
    }

    public String getPassword() {
        return password;
    }

    public Integer getPermissionLevel() {
        return permissionLevel;
    }

    public String getPosition() {
        return position;
    }
    
    public String getDepartment() {
        return department;
    }

    // -------------------- Setters --------------------
    public void setId(Integer id) {
        this.id = id;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setPermissionLevel(Integer permissionLevel) {
        this.permissionLevel = permissionLevel;
    }

    public void setPosition(String position) {
        this.position = position;
    }
    
    public void setDepartment(String department) {
        this.department = department;
    }
}

UserRepository.java:

package com.example.demo.repository;

import java.util.*;
import org.springframework.data.jpa.repository.*;

import com.example.demo.entity.User;

public interface UserRepository extends JpaRepository<User, Integer> {
    // 根据 id 查询用户
    Optional<User> findById(Integer id);
}

UserService.java:

package com.example.demo.service;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;

import jakarta.servlet.http.HttpSession;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public String login(Integer id, String password, HttpSession session) {
        Optional<User> userOptional = userRepository.findById(id);
        System.out.println("用户查询结果:" + userOptional);

        if (!userOptional.isPresent()) {
            throw new RuntimeException("账号不存在");
        }

        User user = userOptional.get();
        System.out.println("数据库密码:" + user.getPassword());
        System.out.println("输入的密码:" + password);

        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }

        session.setAttribute("permissionLevel", user.getPermissionLevel());
        System.out.println("Session 中保存的权限等级:" + session.getAttribute("permissionLevel"));
        
        return "登录成功!权限等级:" + user.getPermissionLevel();
    }
}

index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登录 - 人力资源管理系统</title>
    <style>
        .container {
            width: 300px;
            margin: 100px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        input {
            width: 100%;
            margin: 10px 0;
            padding: 8px;
        }
        button {
            width: 100%;
            padding: 10px;
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>用户登录</h2>
        <form id="loginForm">
            <input type="text" id="id" placeholder="账号" required>
            <input type="password" id="password" placeholder="密码" required>
            <button type="button" onclick="login()">登录</button>
        </form>
        <div id="message" style="color: red; margin-top: 10px;"></div>
    </div>

	<script src="/js/login.js"></script>
</body>
</html>

home.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>公司管理系统</title>
    <style>
        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", sans-serif;
        }

        /* 菜单容器 */
        .menu-container {
            background: #2c3e50;
            color: white;
            padding: 0 20px;
        }

        /* 一级菜单 */
        .main-menu {
            display: flex;
            list-style: none;
        }

        .menu-item {
            position: relative;
            padding: 15px 25px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .menu-item:hover {
            background: #34495e;
        }

        /* 二级菜单 */
        .sub-menu {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            background: #34495e;
            list-style: none;
            min-width: 200px;
            box-shadow: 0 3px 6px rgba(0,0,0,0.2);
        }

        .sub-menu li {
            padding: 12px 25px;
            transition: background 0.3s;
        }

        .sub-menu li:hover {
            background: #3b4f63;
        }

        /* 显示二级菜单 */
        .show-submenu .sub-menu {
            display: block;
        }

        /* 内容区域 */
        .content-area {
            padding: 20px;
        }

        /* 当前选中样式 */
        .active-menu {
            background: #3498db;
        }
    </style>
</head>
<body>
    <nav class="menu-container">
        <ul class="main-menu">
            <!-- 组织架构管理 -->
            <li class="menu-item" onclick="toggleSubmenu(this)">
                组织架构管理
                <ul class="sub-menu">
                    <li onclick="loadContent('企业信息')">企业信息</li>
                    <li onclick="loadContent('组织架构')">组织架构</li>
                    <li onclick="loadContent('编制管理')">编制管理</li>
                    <li onclick="loadContent('部门管理')">部门管理</li>
                </ul>
            </li>

            <!-- 员工管理 -->
            <li class="menu-item" onclick="toggleSubmenu(this)">
                员工管理
                <ul class="sub-menu">
                    <li onclick="loadContent('职位管理')">职位管理</li>
                    <li onclick="loadContent('职级体系')">职级体系</li>
                    <li onclick="loadContent('入职发展')">入职发展</li>
                    <li onclick="loadContent('调动管理')">调动管理</li>
                </ul>
            </li>

            <!-- 合同档案 -->
            <li class="menu-item" onclick="toggleSubmenu(this)">
                合同档案
                <ul class="sub-menu">
                    <li onclick="loadContent('合同管理')">合同管理</li>
                    <li onclick="loadContent('档案管理')">档案管理</li>
                </ul>
            </li>

            <!-- 考核健康 -->
            <li class="menu-item" onclick="toggleSubmenu(this)">
                考核健康
                <ul class="sub-menu">
                    <li onclick="loadContent('绩效考核')">绩效考核</li>
                    <li onclick="loadContent('体检管理')">体检管理</li>
                </ul>
            </li>

            <!-- 系统管理 -->
            <li class="menu-item" onclick="toggleSubmenu(this)">
                系统管理
                <ul class="sub-menu">
                    <li onclick="loadContent('通知中心')">通知中心</li>
                    <li onclick="loadContent('操作日志')">操作日志</li>
                </ul>
            </li>
        </ul>
    </nav>

    <div class="content-area" id="content">
        <h2 id="content-title">欢迎使用公司管理系统</h2>
        <div id="dynamic-content">
            <!-- 动态内容将在此处加载 -->
        </div>
    </div>

    <script>
        // 切换二级菜单显示状态
        function toggleSubmenu(element) {
            // 关闭其他打开的菜单
            document.querySelectorAll('.menu-item').forEach(item => {
                if(item !== element) {
                    item.classList.remove('show-submenu');
                }
            });
            
            // 切换当前菜单状态
            element.classList.toggle('show-submenu');
        }

        // 加载内容
        function loadContent(menuName) {
            // 更新标题
            document.getElementById('content-title').textContent = menuName;
            
            // 清除旧内容
            const contentDiv = document.getElementById('dynamic-content');
            contentDiv.innerHTML = `
                <div style="padding: 20px; background: #f5f6fa; border-radius: 5px;">
                    <h3>${menuName} 功能模块</h3>
                    <p style="margin-top: 10px; color: #666;">
                        ${menuName} 功能正在建设中...
                    </p>
                </div>
            `;

            // 添加活动状态
            document.querySelectorAll('.menu-item').forEach(item => {
                item.classList.remove('active-menu');
            });
            event.target.parentElement.parentElement.classList.add('active-menu');
        }

        // 点击页面其他区域关闭菜单
        document.addEventListener('click', function(e) {
            if(!e.target.closest('.menu-item')) {
                document.querySelectorAll('.menu-item').forEach(item => {
                    item.classList.remove('show-submenu');
                });
            }
        });
    </script>
</body>
</html>

login.js:

async function login() {
    const id = document.getElementById('id').value;
    const password = document.getElementById('password').value;
    const messageDiv = document.getElementById('message');
    messageDiv.innerText = '';

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `id=${encodeURIComponent(id)}&password=${encodeURIComponent(password)}`
        });

        // 直接解析 JSON
        const result = await response.json();
        
        if (result.success) {
            window.location.href = '/home';
        } else {
            messageDiv.innerText = result.message;
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        messageDiv.innerText = '网络错误,请检查控制台';
    }
}

遇到的困难:
在我建立登录系统的过程中,代码中未报错,而在我输入已经准备好的id与密码时却始终无法成功登入。显示如下:Hibernate: select u1_0.id,u1_0.password,u1_0.permission_level,u1_0.position from user u1_0 where u1_0.id=?
我初步断定可能是我密码输入错误,或者在登录时,其中有个数据返回null值,我添加了一部分的异常处理,但仍然无法解决。最后我查看了浏览器的开发者工具,找到 /api/login 请求,

再加上与其相关了一些内容,我判定了原因其实是:后端登录接口返回的是纯文本(text/plain),但前端 login.js 代码尝试将响应解析为 JSON(response.json()),导致解析失败。
最后我修改,并完成了登录系统。

今天的任务:
因为我大概已经把web端的主界面做出,但没有做出具体到功能,我今天大概需要完成员工管理系统,包括职位和职级管理体系,入职发展和调动管理。

posted @ 2025-04-19 20:57  老汤姆233  阅读(8)  评论(0)    收藏  举报