Spring Boot 3 + Vue 3 Course Selection System Replaces First-Come with Public-Seed Lottery
A ready-to-run registrar-grade course selection system: student-side wish submission and lottery results, teacher-side grade entry and publishing, admin-side draw console and batch reports, with the entire flow recomputable and auditable.
1. Why This Project
University course selection has two typical scenarios:
- First-come, first-served (real-time rush): depends on network speed and scripts; popular courses sell out in seconds, and there are frequent overselling and cache consistency issues.
- Wish + lottery: students submit wishes anytime during the filling period, seats are batch-allocated after the deadline, and results are independent of submission time or network speed; fairer and easier to explain.
This project has implemented both mechanisms. The current branch feature/wish-lottery-selection implements the "wish filling + unified lottery" approach: students submit a "wish order + investment points" during the filling period, and after the deadline the backend performs a one-time batch allocation. After R1 is published, drops are allowed; R2 results are final.
Several design points that were particularly emphasized:
- Zero seat competition: seats are written once at draw time; there is no concurrent decrement during operation, and no need to maintain cache remaining counts.
- Recomputability: the batch draw publishes a public
seed, which, together with the input snapshot (gzip + SHA-256), lets a third party independently recompute the draw. - Result audit trail: each wish records "hit / miss reason / placement order", not a black box.
- Downstream transparency: draw results still go into
course_selection, so timetable, grades, teacher lists, and exports require zero modifications.
This is a front-end/back-end separated project, and it also includes a native WeChat mini-program (timetable / grades / course evaluation) that reuses the same interfaces.
2. Tech Stack
Backend
| Component | Version | Description |
|---|---|---|
| Java | 21 | LTS, uses Text Block, Record, etc. |
| Spring Boot | 3.3.5 | Base framework |
| Spring Security | 6.x | Authentication and authorization |
| MyBatis-Plus | 3.5.7 | ORM, pagination, optimistic lock, logical delete |
| MySQL | 8.0 | Business data storage |
| Redis | 7.x | Token whitelist, draw lock, heat snapshot |
| JJWT | 0.12.6 | JWT token issuing and parsing |
| Knife4j | 4.5.0 | OpenAPI 3 API documentation |
| Hutool | 5.8.32 | General utility classes |
| Lombok | 1.18.34 | Simplify boilerplate code |
Frontend
| Component | Version | Description |
|---|---|---|
| Vue | 3.5 | Composition API |
| Vite | 5.4 | Build tool |
| Element Plus | 2.8 | UI component library |
| Pinia | 2.2 | State management |
| Vue Router | 4.4 | Routing and permission guards |
| Axios | 1.7 | HTTP request wrapper |
| ECharts | 5.5 | Data visualization |
| Day.js | 1.11 | Time handling |
Mini-program and Deployment
- Native WeChat mini-program (WXML / WXSS / JS, no build dependencies, base library 3.5.5+)
- Docker, Docker Compose, Nginx
3. System Architecture
┌──────────────────────────────────────────────────────────────┐
│ Browser / Client │
└──────────────────────────────┬───────────────────────────────┘
│ HTTP (JWT)
┌──────────────────────────────▼───────────────────────────────┐
│ Vue 3 Frontend (Nginx hosted) │
│ Element Plus · Pinia · Vue Router · Axios · ECharts │
└──────────────────────────────┬───────────────────────────────┘
│ /api/** reverse proxy
┌──────────────────────────────▼───────────────────────────────┐
│ Spring Boot 3 Backend │
│ ┌────────────┬────────────┬────────────┬──────────────────┐ │
│ │ Controller │ Service │ Mapper │ Security / AOP │ │
│ └────────────┴─────┬──────┴─────┬──────┴──────────────────┘ │
└──────────┬─────────┼────────────┼─────────────────────────────┘
│ │ │
┌───────▼──────┐ │ ┌────────▼────────┐
│ MySQL 8.0 │ │ │ Redis 7 │
│ Business data│ │ │ Token/Lock/Snapshot│
└──────────────┘ └───┴─────────────────┘
The backend is clearly layered: controller → service → mapper. The security layer handles JWT issuing and parsing. The aspect layer uses annotation-based @OperationLog + AOP asynchronous logging for auditing. The lottery execution is concentrated in LotteryServiceImpl (AUTO mode is triggered by phase queries, with no extra scheduler).
4. System Display
4.1 Interaction Animations
Student · Wish Filling: Browse courses, adjust wish order and investment points; the right side aggregates in real time.
Admin · Draw Report: From the draw console, open the current batch to view the seed, per-course seat allocation, and per-wish results.
Student · Timetable View: Weekly timetable rendering; click a course card to see class details.
Admin · Data Overview: Stat cards, charts, and course selection switches.
4.2 Student Side
Wish Filling: During the filling period, submit wishes with "wish order + investment points". Hard constraints like time conflicts and credit overages grey out courses with reasons; soft constraints only prompt without blocking. The right side aggregates points and wishes in real time.

Draw Results: Number of hit courses, random seed (copyable for recomputation), per-wish placement order and miss reasons; supports viewing by semester and round. Drops are allowed after R1 publication; R2 results are final.

My Courses: Semester / status / action filters, total credits filtered, drop and review entry points.

My Timetable: A 9-period × 7-day weekly timetable, including week range, period times, and classroom locations.

My Grades: Total credits / earned credits / average score / average GPA statistics and per-course grade details.

Teaching Evaluation: Two tabs for pending evaluations and my evaluations; four-dimension star ratings, quick labels, and anonymous submission.
4.3 Teacher Side
My Teaching: View courses by semester and selection progress; each course links directly to "Student List" and "Grade Entry".
Teaching Timetable: All courses arranged by period; schedule conflicts are immediately visible.
Grade Entry: Final grade automatically calculated as usual grade × 30% + final exam grade × 70%; supports batch fill, pagination, status filter, and "published / draft" count badges. Save drafts, publish/withdraw entire courses, and do per-student corrections (must provide a reason; before/after changes are audited). Also supports an "export grade sheet → Excel offline grading → import grades" loop.
Teaching Evaluation: Composite average score, four-dimension scores, and participant count for taught courses.

4.4 Admin Side
Data Overview: Student / teacher / course / selection / department statistics; department course distribution, grade distribution, top 10 popular courses, and the selection channel switch and filling time quick settings.
Lottery Management: Phase console (R1 filling → draw → publish → R2 → close), course selection switch, "recalculate selection counts", batch list, and per-batch seed/seat allocation reports.
Semester and Selection Settings: Semester start/end dates, wish filling window, evaluation open times, and "set as current".

Course Management: CRUD for courses, timetabling, batch import/export, and "recalculate selection counts".

Student Management: Student records, batch import / enable / disable / reset password, and registrar proxy selection and proxy drop.
Teacher Management: Teacher records, batch import, reset password, and account status.
Evaluation Management: Total evaluations / published / hidden / average score / participation rate statistics; supports publish, hide, delete, and batch operations.
Announcement Management: Pin, target role (student / teacher), publish/unpublish, and batch operations.
Basic Info: Dictionaries for departments, majors, and classrooms, with batch import.

Operation Logs: Annotation-based audit; records operator, duration, request parameters, and exception stack traces.

Login Lockout: Dual-dimension counting by account and source IP; admin can view failure counts, remaining time, and unlock with one click.

4.5 Common Pages
Login Page: Username/password login; consecutive failures trigger temporary lockout.

Public Info: Announcement center for students and teachers, unread markers, unread-only filter, and mark all as read.

Message Center: In-site messages for system announcements, grade publishing, evaluation audits, etc.; supports all / unread / read filters.
5. Core Mechanism: Wish Filling + Unified Lottery
5.1 A Full Selection Cycle
① Admin enables R1 filling (lottery_phase = R1_COLLECTING)
↓
② Students submit wishes during the filling period (whole-batch overwrite, idempotent upsert, no lock, no contention)
↓
③ Admin closes filling (R1_LOCKED)
↓
④ Admin executes draw (R1_DRAWING): read DB snapshot → in-memory batch computation → transactional persistence
↓
⑤ Publish results (R1_PUBLISHED): open R1 drop window
↓
⑥ R2: only courses with remaining seats can be re-filled; R2_PUBLISHED is final (no drops)
Execution is "auto" by default: after filling closes, the next page load automatically completes "close → draw → publish"; admins can switch to "manual" at any time and step through to verify cancelled courses and data.
5.2 Placement Rules
- Student-dimension placement: Sort by weight (
MIXED= points → earned credits →HMAC-SHA256(seed, studentId)); each student is processed only once, avoiding deadlocks from course-dimension rotation. - Wish order only applies within a student: the 1st wish takes priority over the 2nd; one student can hit multiple courses, no break.
- Hard constraints: no time conflict (with already selected/hit courses), no credit overage, no duplicate occupation, no re-selecting already-selected courses, and cancelled courses record
COURSE_CANCELLED. - Soft constraints: time conflicts between wishes only prompt, do not block — otherwise it would kill "if A misses, fallback to B".
- Adjustment: only for students with zero hits who accept adjustment, statically adjusted to similar courses / same department (or public electives), still subject to conflict and credit constraints.
- No over-issue: seats are decremented in memory; no external release before persistence.
5.3 Time Conflict Determination
Two timetable records are considered conflicting if all of these hold:
- Same day:
day_of_weekequal. - Period overlap:
startA ≤ endB && endA ≥ startB. - Week overlap:
[startWeekA, endWeekA]and[startWeekB, endWeekB]intersect. - Week type compatible: if either is "every week", then conflict; if "odd/even week", there must be a common odd/even week in the intersection.
Implemented in ScheduleConflictUtils, reused by "precheck before submission (/student/lottery/precheck)" and "registrar proxy selection"; the lottery batch computation uses the same rule set as a hard constraint.
5.4 Seat Quota Calculation
The remaining count is uniformly computed from the database:
remaining = max_capacity - selected_count -- not below 0
selected_count is maintained transactionally by draw persistence, drops, and registrar proxy selection; after the draw is published, it is recalculated from real course_selection records, and admins can trigger POST /admin/courses/selection/sync at any time.
Only one source of truth for remaining seats: the database, avoiding cache/DB number drift.
5.5 Drops
- Student drops reuse
POST /student/courses/{courseId}/drop. - Drops allowed after R1 publication; closed after
r1_drop_deadline; R2 results havedrop_locked = 1, and drops return3013. - Courses with published grades cannot be dropped (draft grades do not lock drops); registrar proxy drops are not subject to window limits (recovery scenario).
5.6 Redis Usage in This Version
| Redis Key | Type | Description |
|---|---|---|
elective:selection:switch |
String | Global filling channel switch (on/off), closed returns 3007 |
elective:auth:token:{userId} |
String | Token whitelist |
elective:lottery:draw:lock:{semesterId}:{round} |
String | Draw single-writer lock (10 minutes) |
elective:lottery:hot:{semesterId}:{round} |
String(JSON) | Filling heat snapshot (2 hours) |
Course remaining counts and selected sets do not use Redis.
5.7 Persistence and Reruns
- Result details
lottery_resultare batch-inserted in chunks of 500. - Hit records written to
course_selectionuse "reuse if exists, add if not", avoiding logical delete rows occupying unique keys. - Before a rerun, current round
select_type in (3,4)is reset to "dropped", and the old batch is set toSUPERSEDED(batch and details retained for archiving), so reruns are idempotent and history is traceable. - The draw uses a Redis single-writer lock; on failure it automatically reverts to
*_LOCKED.
5.8 Fairness and Verifiability
- Submission time does not participate in weighting; any time during the filling period is equivalent.
- On publication,
lottery_batch.seedis made public; with the wish snapshot a third party can independently recompute. - Each wish records "hit / miss reason / placement order", avoiding a black box.
- Heat shows only raw counts and bands, not rankings / hit rates / percentage probabilities; aggregated announcements go through a 2-hour snapshot to suppress herd effects.
5.9 Key Configuration
elective:
lottery:
enabled: true # master switch (emergency fallback)
weight-strategy: MIXED # RANDOM / POINTS / MIXED
force-adjust: true # force accept adjustment
max-wishes: 8 # max wishes per round
points-budget: 100 # total points per round
min-open-wish-count: 0 # minimum wishes to open a course (prod suggestion 15)
hot-cache-seconds: 7200 # heat snapshot cache
hot-threshold-medium: 1.0
hot-threshold-high: 2.0
hot-threshold-extreme: 4.0
draw-lock-seconds: 600 # draw single-writer lock
6. Database Design
There are 22 tables in total; the full DDL is in backend/src/main/resources/db/schema.sql. Core tables related to the lottery:
| Table name | Description | Key constraints |
|---|---|---|
semester |
Semester and filling window | semester_code unique; is_current marks current semester; lottery_phase drives draw phase |
course |
Course and offering info | (course_code, semester_id) unique; version optimistic lock |
course_selection |
Course selection records (draw / adjust / proxy results) | (student_id, course_id, semester_id) unique; lottery_round / drop_locked mark source and no-drop |
course_wish |
Draw wishes (per-round drafts) | (student_id, course_id, semester_id, round_no) unique; physical delete avoids unique key residues |
lottery_batch |
Draw batch (seed, stats, status, publish info) | (semester_id, round_no, attempt_no) unique; reruns/rollbacks only change status, history kept |
lottery_batch_snapshot |
Draw input snapshot (courses / students / wishes) | One per batch, gzip + SHA-256, supports independent recomputation |
lottery_result |
Per-wish hit/miss reason | Index (batch_id, student_id), (batch_id, course_id) |
Design details:
- Logical delete: except for
sys_logandcourse_review, all tables use adeletedfield handled by MyBatis-Plus. - Selection unique constraint:
course_selection's unique index is the final DB-level guard against duplicate selection; draws rerun by "update if exists, add if not" reusing the same row. - Grade calculation:
total_score = usual_score × 0.3 + exam_score × 0.7, GPA uses a 4.0 scale.
7. Quick Start
Environment Requirements
| Dependency | Minimum Version | Description |
|---|---|---|
| JDK | 21 | Backend runtime |
| Maven | 3.8+ | Backend build |
| Node.js | 18+ | Frontend build |
| MySQL | 8.0+ | Business database |
| Redis | 6.0+ | Token whitelist, draw lock, hot spot snapshot |
Method 1: Docker Compose One-Click Startup (Recommended)
# First deploy: copy environment variable template and fill strong passwords
# MYSQL_ROOT_PASSWORD / REDIS_PASSWORD / JWT_SECRET (JWT_SECRET at least 32 bytes)
cp .env.example .env
# Run from project root
docker compose up -d --build
# Check service status
docker compose ps
# View backend logs
docker compose logs -f backend
After startup, access:
| Service | Address |
|---|---|
| Frontend page | http://localhost |
| Backend API | http://localhost:8080/api |
| API docs (Knife4j) | http://localhost:8080/api/doc.html |
MySQL and Redis automatically run
schema.sqlanddata.sqlon first start to create tables and seed data.
Method 2: Local Development Startup
# 1. Initialize database (table structure auto-created by application startup, missing tables auto-created)
mysql -uroot -p < scripts/init-db.sql
# 2. Start Redis (default dev config has no password)
redis-server
# 3. Start backend
cd backend
mvn clean compile
mvn spring-boot:run
# 4. Start frontend
cd frontend
npm install
npm run dev
Frontend runs by default at http://localhost:5174, with /api proxied to http://localhost:8080.
Built-in demo data: 20 students, 8 teachers, 5 semesters, 38 courses, 53 timetable entries, 344 selection records, 298 grade records, 159 course evaluations; all selection combinations have passed time-conflict validation.
8. Demo Accounts
The initialization script data.sql includes demo data; all accounts have initial password 123456. (Note: text uses {noop} prefix for plaintext for easy testing; new users or password changes use bcrypt.)
| Role | Account | Description |
|---|---|---|
| Admin | admin |
System administrator |
| Teacher | T2026001 |
Zhang Mingyuan, Professor (Computer Science) |
| Teacher | T2026002 |
Li Chengyang, Associate Professor (Telecom) |
| Teacher | T2026003 |
Wang Yaqin, Professor (Economics) |
| Student | 2026010101 |
Liu Siyuan, CS 2601 |
| Student | 2026010102 |
Sun Jiayi, CS 2601 |
| Student | 2026010201 |
Zhou Zi'ang, Software 2601 |
| Student | 2026020101 |
Wu Yutong, Telecom 2601 |
| Student | 2026030101 |
Zheng Yuxuan, Business 2601 |
Demo passwords use
{noop}prefix for plaintext for quick experience; when admin creates users or changes passwords, bcrypt is used automatically. In production, change all default passwords and overrideJWT_SECRETvia environment variables.
9. Repository and Branches
- Gitee (main): https://gitee.com/huangrenhui/CollegeElectiveSystem
- GitHub (mirror): https://github.com/huangrenhui/CollegeElectiveSystem
Branches:
| Branch | Selection mechanism |
|---|---|
master |
Redis + Lua real-time rush (seat pre-reservation, queue smoothing) |
feature/wish-lottery-selection |
Wish filling + unified lottery (shown in this article) |
Both branches share the same registrar management, grades, evaluations, and mini-program capabilities, allowing side-by-side comparison of the two selection implementations.
10. Conclusion
This project originally set out to make "course selection" solid: not just being able to select, but also being able to explain, verify, and drop. The wish + lottery approach sacrifices some instant gratification of "immediate results" in exchange for fairness and explainability — submission time no longer matters, results can be recomputed, and every missed wish has a clear reason.
If this project helps you, feel free to Star. Questions can be discussed in comments or filed as Issues.
Note: Images in this article are hosted on jsDelivr (GitHub mirror); on certain networks, if loading is slow, view the originals in the
docs/images/directory of the repository.