学习进度条

今日所花时间:一个半小时
今日代码量:150行
博客量:一篇
了解到的知识点:手机端开发
课堂极限测试
在手机端实现新课程添加。
(1)新课程信息必须唯一,如有重复,提示用户“课程名称重复,重新录入”;
(2)要求判断任课教师为王建民、刘立嘉、刘丹、杨子光、张云霞、武永亮、高飞、孙静、黄荣峰九位教师的其中一位。
(3)要求上课地点开头为“一教、二教、三教、基教”中的一种;
(4)将新课程信息添加入远程数据库(笔记本上的库)
web端成功完成
建表语句

-- 创建数据库
create database Course_events;

-- 使用数据库
use Course_events;

CREATE TABLE courses (
                         id INT AUTO_INCREMENT PRIMARY KEY,
                         course_name VARCHAR(255) NOT NULL UNIQUE,
                         teacher VARCHAR(255) NOT NULL,
                         location VARCHAR(255) NOT NULL
);

controller层代码

package com.example.day0307demo.controller;

import com.example.day0307demo.mapper.CourseMapper;
import com.example.day0307demo.pojo.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/courses")
@CrossOrigin
public class CourseController {

    @Autowired
    private CourseMapper courseMapper;

    // 允许的教师名单
    private final List<String> validTeachers = Arrays.asList("王建民", "刘立嘉", "刘丹", "杨子光", "张云霞", "武永亮", "高飞", "孙静", "黄荣峰");

    // 允许的地点前缀
    private final List<String> validLocationPrefixes = Arrays.asList("一教", "二教", "三教", "基教");

    // 添加新课程
    @PostMapping("/add")
    public ResponseEntity<String> addCourse(@RequestBody Course course) {
        // 检查课程名称是否重复
        if (courseMapper.findByCourseName(course.getCourseName()) != null) {
            return ResponseEntity.badRequest().body("课程名称重复,重新录入");
        }

        // 检查任课教师是否在允许的名单中
        if (!validTeachers.contains(course.getTeacher())) {
            return ResponseEntity.badRequest().body("无效的任课教师");
        }

        // 检查上课地点是否以允许的前缀开头
        boolean validLocation = validLocationPrefixes.stream()
                .anyMatch(prefix -> course.getLocation().startsWith(prefix));
        if (!validLocation) {
            return ResponseEntity.badRequest().body("无效的上课地点");
        }

        // 插入课程到数据库
        courseMapper.insertCourse(course);
        return ResponseEntity.ok("课程添加成功");
    }

    // 获取所有课程
    @GetMapping("/all")
    public ResponseEntity<List<Course>> getAllCourses() {
        List<Course> courses = courseMapper.findAllCourses();
        return ResponseEntity.ok(courses);
    }
}

mapper层代码

package com.example.day0307demo.mapper;

import com.example.day0307demo.pojo.Course;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CourseMapper {

    @Insert("INSERT INTO courses (course_name, teacher, location) VALUES (#{courseName}, #{teacher}, #{location})")
    void insertCourse(Course course);

    @Select("SELECT * FROM courses WHERE course_name = #{courseName}")
    Course findByCourseName(String courseName);

    @Select("SELECT * FROM courses")
    List<Course> findAllCourses();
}

实体类代码

package com.example.day0307demo.pojo;


import jakarta.persistence.*;

@Entity
@Table(name = "courses")
public class Course {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "course_name", nullable = false, unique = true)
    private String courseName;

    @Column(name = "teacher", nullable = false)
    private String teacher;

    @Column(name = "location", nullable = false)
    private String location;

    // 默认构造函数
    public Course() {}

    // 带参数的构造函数
    public Course(String courseName, String teacher, String location) {
        this.courseName = courseName;
        this.teacher = teacher;
        this.location = location;
    }

    // Getters and Setters

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    // toString方法(可选,用于调试)
    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", courseName='" + courseName + '\'' +
                ", teacher='" + teacher + '\'' +
                ", location='" + location + '\'' +
                '}';
    }
}

前端页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课程管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 400px;
        }
        h1, h2 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #218838;
        }
        #message {
            margin-top: 15px;
            text-align: center;
            color: #dc3545;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>课程管理系统</h1>
    <form id="courseForm">
        <div class="form-group">
            <label for="courseName">课程名称:</label>
            <input type="text" id="courseName" name="courseName" required>
        </div>
        <div class="form-group">
            <label for="teacher">任课教师:</label>
            <input type="text" id="teacher" name="teacher" required>
        </div>
        <div class="form-group">
            <label for="location">上课地点:</label>
            <input type="text" id="location" name="location" required>
        </div>
        <button type="submit">添加课程</button>
    </form>
    <div id="message"></div>
    <h2>课程列表</h2>
    <table id="courseTable">
        <thead>
        <tr>
            <th>课程名称</th>
            <th>任课教师</th>
            <th>上课地点</th>
        </tr>
        </thead>
        <tbody>
        <!-- 课程数据将通过JavaScript动态插入 -->
        </tbody>
    </table>
</div>
<script>

    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('courseForm');
        const messageDiv = document.getElementById('message');
        const courseTableBody = document.querySelector('#courseTable tbody');

        // 获取所有课程并显示
        fetch('http://localhost:8080/courses/all')
            .then(response => response.json())
            .then(data => {
                courseTableBody.innerHTML = '';
                data.forEach(course => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${course.courseName}</td>
                        <td>${course.teacher}</td>
                        <td>${course.location}</td>
                    `;
                    courseTableBody.appendChild(row);
                });
            });

        // 表单提交事件
        form.addEventListener('submit', function (event) {
            event.preventDefault();

            const course = {
                courseName: document.getElementById('courseName').value,
                teacher: document.getElementById('teacher').value,
                location: document.getElementById('location').value
            };

            fetch('http://localhost:8080/courses/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(course)
            })
                .then(response => response.text())
                .then(message => {
                    messageDiv.textContent = message;
                    if (message === '课程添加成功') {
                        // 清空表单
                        form.reset();
                        // 重新加载课程列表
                        fetch('http://localhost:8080/courses/all')
                            .then(response => response.json())
                            .then(data => {
                                courseTableBody.innerHTML = '';
                                data.forEach(course => {
                                    const row = document.createElement('tr');
                                    row.innerHTML = `
                                    <td>${course.courseName}</td>
                                    <td>${course.teacher}</td>
                                    <td>${course.location}</td>
                                `;
                                    courseTableBody.appendChild(row);
                                });
                            });
                    }
                });
        });
    });</script>
<script>

</script>
</body>
</html>

如何在手机端实现还需要继续学习。

posted @ 2025-03-07 21:58  haoyinuo  阅读(28)  评论(0)    收藏  举报