当前位置: 首页 > article >正文

基于jsp+servlet+mybatis的简易在线选课系统

目录

一.数据库

1.数据库和表的创建

2.数据插入 

二.代码实现

1.pojo类

(1)Course

(2)User

(3)Elective

 2.mapper接口

 (1)UserMapper

(2)ElectiveMapper

(3)CourseMapper

3.sevlet 

(1)LoginServlet:登录处理

(2)IndexServlet:用户主页面处理

(3)ChooseServlet:对选课请求的处理

 (4)ViewCourseServlet:选课结果相关数据处理

(5)addCourseServlet:处理添加课程的请求

4.utils工具类

(1)SqlSessionUtil

5.resource

 (1)mybatis-config.xml

(2)CourseMapper.xml

(3) jdbc.propetise

(4)log4j.propertise

6.jsp页面

(1)login.jsp:登录页面

(2)chooseList.jsp:学生选课页面、教师浏览学生选课情况

(3)viewCourse.jsp :选课结果一览

 (4)addCourse.jsp

(5)error.jsp

三.实施结果

1.学生:

​2.老师:

四.系统测试


一.数据库

根据实训题目中给出的表间关系图、数据表结构设计、数据说明等等信息,可创建数据库如下:

1.数据库和表的创建

CREATE DATABASE xuanke;
-- 创建用户表
CREATE TABLE USER (
  username VARCHAR(20) PRIMARY KEY NOT NULL,
  PASSWORD VARCHAR(20) NOT NULL,
  realname VARCHAR(20) NOT NULL,
  ROLE CHAR(1) NOT NULL CHECK (ROLE IN ('0', '1'))
);

-- 创建课程表
CREATE TABLE course (
  course_id CHAR(6) PRIMARY KEY NOT NULL,
  course_name VARCHAR(40) NOT NULL,
  teacher VARCHAR(40) NOT NULL,
  `point` INT NOT NULL,
  time_1 CHAR(2) NOT NULL CHECK (time_1 BETWEEN '11' AND '55'),
  time_2 CHAR(2) NOT NULL CHECK (time_2 BETWEEN '11' AND '55'),
  location VARCHAR(40) NOT NULL,
  limited INT NOT NULL CHECK (limited >= 0)
);

-- 创建选课表
CREATE TABLE elective (
  username VARCHAR(20) NOT NULL,
  course_id CHAR(6) NOT NULL,
  PRIMARY KEY (username, course_id),
  FOREIGN KEY (username) REFERENCES USER(username),
  FOREIGN KEY (course_id) REFERENCES course(course_id)
);

2.数据插入 

-- 插入数据到用户表(USER):
INSERT INTO USER (username, PASSWORD, realname, ROLE)
VALUES ('user1', 'password1', '张三', '1');

INSERT INTO USER (username, PASSWORD, realname, ROLE)
VALUES ('user2', 'password2', '李四', '0');

INSERT INTO USER (username, PASSWORD, realname, ROLE)
VALUES ('user3', 'password3', '王五', '0');


-- 插入数据到课程表(course)
INSERT INTO course (course_id, course_name, teacher, POINT, time_1, time_2, location, limited)
VALUES ('C001', '数学', '张老师', 3, '12', '14', '教室A', 50);

INSERT INTO course (course_id, course_name, teacher, POINT, time_1, time_2, location, limited)
VALUES ('C002', '英语', '李老师', 2, '11', '13', '教室B', 40);

INSERT INTO course (course_id, course_name, teacher, POINT, time_1, time_2, location, limited)
VALUES ('C003', '物理', '王老师', 3, '15', '17', '教室C', 60);

-- 插入数据到选课表(elective):
INSERT INTO elective (username, course_id)
VALUES ('user1', 'C001');

INSERT INTO elective (username, course_id)
VALUES ('user1', 'C002');

INSERT INTO elective (username, course_id)
VALUES ('user2', 'C001');

二.代码实现

1.pojo类

(1)Course

此处使用parseTime方法实现题目要求中的数据说明与用户页面的time的转换

package com.hjj.pojo;

import lombok.Data;

/**
 * @author:嘉佳 Date:2023/11/27 23:30
 **/
@Data
public class Course {
    private String courseId;
    private String courseName;
    private String teacher;
    private int point;
    private String time1;
    private String time2;
    private String location;
    private int limited;
    private int choose;

    public void setTime1(String time1) {
        this.time1 = parseTime(time1);
    }

    public void setTime2(String time2) {
        this.time2 = parseTime(time2);
    }

    public String parseTime(String unTime) {
        int x = Integer.parseInt(unTime);
        String time = "星期";
        switch (x / 10) {
            case 1:
                time += "一";
                break;
            case 2:
                time += "二";
                break;
            case 3:
                time += "三";
                break;
            case 4:
                time += "四";
                break;
            case 5:
                time += "五";
                break;
        }
        switch (x % 10) {
            case 1:
                time += "8:05~9:50";
                break;
            case 2:
                time += "10:15~12:00";
                break;
            case 3:
                time += "13:35~15:20";
                break;
            case 4:
                time += "15:45~17:30";
                break;
            case 5:
                time += "18:30~20:45";
                break;
        }
        return time;
    }
}

(2)User

package com.hjj.pojo;

import lombok.Data;

/**
 * @author:嘉佳 Date:2023/11/27 23:29
 **/
@Data
public class User {
    private String username;
    private String password;
    private String realName;
    private char role;
}

(3)Elective

package com.hjj.pojo;

import lombok.Data;

/**
 * @author:嘉佳 Date:2023/11/27 23:30
 **/
@Data
public class Elective {
    private String username;
    private String courseId;
}

 2.mapper接口

mapper接口中方法名要与映射文件中的sql的id保持一致

使用 MyBatis 框架的注解方式执行 SQL

 (1)UserMapper

package com.hjj.mapper;
import com.hjj.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * @author:嘉佳 Date:2023/12/1 17:40
 **/
@Mapper
public interface UserMapper {


    @Select("select * from user where username = #{username} and password = #{password} and role = #{role}")
    User selectAdminByNameAndPassword(@Param("username") String username, @Param("password") String password, @Param("role") Integer role);


    @Insert("insert into user(username,password,realname,role) values(#{username},#{password},#{realname},#{role})")
    void insertUser(@Param("username") String username,@Param("password") String password,@Param("realname") String realName,@Param("role") Integer role);
}

(2)ElectiveMapper

package com.hjj.mapper;

import com.hjj.pojo.Course;
import com.hjj.pojo.Elective;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @author:嘉佳 Date:2023/12/3 23:54
 **/
public interface ElectiveMapper {
    
    @Select("SELECT COUNT(*) FROM elective \n" +
            "WHERE username=#{username} AND course_id=#{course_id}")
    Integer selectCourse(@Param("username") String username, @Param("course_id") String courseId);

    @Select("SELECT * FROM elective e LEFT JOIN course c ON c.course_id  = e.course_id \n" +
            "WHERE e.username = #{username}")
    List<Course> selectElective(@Param("username") String username);
    
    @Insert("insert into elective(username,course_id) values(#{username},#{course_id})")
    void insertElect(@Param("username") String username, @Param("course_id") String courseId);

}

(3)CourseMapper

package com.hjj.mapper;

import com.hjj.pojo.Course;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author:嘉佳 Date:2023/12/1 23:54
 **/
public interface CourseMapper {
    @Select("select * from course")
    List<Course> selectAll();

    @Select("SELECT * FROM course c LEFT JOIN `user` u ON c.teacher = u.realname WHERE username = #{teacher}")
    List<Course> selectByTeacher(@Param("teacher")String teacher);

    @Select("SELECT COUNT(e.username) AS selected_count FROM course c\n" +
            "LEFT JOIN elective e ON c.course_id = e.course_id\n" +
            "WHERE c.course_id = #{courseId} GROUP BY c.course_id, c.course_name;\n")
    int countChoose(@Param(("courseId"))String courseId);

    @Select("select * from course where teacher = #{teacher}")
    List<Course> selectCourseByName(@Param("teacher") String teacher);

    @Insert("insert into course(course_id,course_name,teacher,POINT,time_1,time_2,location,limited) " +
            "values (#{courseId},#{name},#{teacher},#{point},#{time_1},#{time_2},#{location},#{limited})")
    void insertCourse(@Param("courseId") String courseId, @Param("name") String name, @Param("teacher") String teacher, @Param("point") Integer point, @Param("time_1") String time_1, @Param("time_2")String time_2, @Param("location")String location, @Param("limited")Integer limited);

}

3.sevlet 

(1)LoginServlet:登录处理

功能:验证用户的输入是否正确,验证输入信息的完整性,然后使用 Mybatis 进行数据库查询操作,如果查询结果不为空则表示登录成功并跳转到主页面,在验证角色时角色编码设置为 0、1。

package com.hjj.servlet;

/**
 * @author:嘉佳 Date:2023/11/27 12:40
 **/

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.hjj.mapper.UserMapper;
import com.hjj.pojo.User;
import com.hjj.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login01")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 从表单获取输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        
        request.getSession().setAttribute("username", username);
        request.getSession().setAttribute("roleType", role);
        int roleCode = 0;
        if (role.equals("teacher")) {
            roleCode = 1;
        }

        // 验证用户名和密码是否为空
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            request.getRequestDispatcher("xuanke/error.jsp").forward(request, response);
        }

        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.selectAdminByNameAndPassword(username, password, roleCode);

        if (user == null) {
            request.getRequestDispatcher("xuanke/error.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("indexServlet").forward(request, response);
        }

    }
}

(2)IndexServlet:用户主页面处理

针对不同用户设置相关信息,这样不用单独写多个servlet处理多个不同类型用户

功能:获取当前用户的角色类型,并根据用户的角色类型使用 Mybatis 进行不同的数据库查询操作,从而获取课程列表信息。

package com.hjj.servlet;

import com.hjj.mapper.CourseMapper;
import com.hjj.pojo.Course;
import com.hjj.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author:嘉佳 Date:2023/12/4 0:02
 **/
@WebServlet("/indexServlet")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);

        HttpSession session = req.getSession();
        List<Course> courseList=null;
        String roleType = session.getAttribute("roleType").toString();
        if(roleType.equals("student")){
            courseList = mapper.selectAll();
        }else{
            courseList=mapper.selectByTeacher((String) session.getAttribute("username"));
        }
        for (int i = 0; i < courseList.size(); i++) {
            int countChoose = mapper.countChoose(courseList.get(i).getCourseId());
            courseList.get(i).setChoose(countChoose);
        }
        req.setAttribute("lists", courseList);
        System.out.println("o");

        req.getRequestDispatcher("xuanke/chooseList.jsp").forward(req, resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}

(3)ChooseServlet:对选课请求的处理

 功能:检验课程是否已选并将数据添加至数据库

package com.hjj.servlet;

import com.hjj.mapper.CourseMapper;
import com.hjj.mapper.ElectiveMapper;
import com.hjj.pojo.Course;
import com.hjj.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author:嘉佳 Date:2023/12/4 15:49
 **/
@WebServlet("/chooseServlet")
public class ChooseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String courseId = req.getParameter("courseId");
        String username = req.getParameter("username");

        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        ElectiveMapper mapper = sqlSession.getMapper(ElectiveMapper.class);

        Integer course = mapper.selectCourse(username, courseId);
        if (course > 0) {
            req.setAttribute("errorMessage", "请勿选择已选课程");
        } else {
            System.out.println(course);
            mapper.insertElect(username, courseId);
            sqlSession.commit();
            sqlSession.close();
            req.setAttribute("errorMessage", "选课成功");
        }

        req.getRequestDispatcher("/indexServlet").forward(req, resp);
    }
}

 (4)ViewCourseServlet:选课结果相关数据处理

功能:查询本人已选课程,计算已选学分

package com.hjj.servlet;

import com.hjj.mapper.ElectiveMapper;
import com.hjj.pojo.Course;
import com.hjj.pojo.Elective;
import com.hjj.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author:嘉佳 Date:2023/12/5 22:02
 **/
@WebServlet("/viewCourseServlet")
public class ViewCourseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String username = (String) req.getSession().getAttribute("username");

        System.out.println(username);
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        ElectiveMapper mapper = sqlSession.getMapper(ElectiveMapper.class);
        List<Course> electives = mapper.selectElective(username);

//        计算已选学分
        int points=0;
        for (Course elective:electives){
            points+=elective.getPoint();
        }
        req.setAttribute("totalPoint",points);
        req.setAttribute("lists",electives);
        req.getRequestDispatcher("xuanke/viewCourse.jsp").forward(req,resp);
    }
}

(5)addCourseServlet:处理添加课程的请求

功能:获取前端传递过来的课程信息,将用户输入的信息录入数据库

package com.hjj.servlet;

import com.hjj.mapper.CourseMapper;
import com.hjj.pojo.Course;
import com.hjj.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author:嘉佳 Date:2023/11/28 12:24
 **/
@WebServlet("/addCourseServlet")
public class addCourseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        
        String courseId = req.getParameter("courseId");
        System.out.println(courseId);
        String courseName = req.getParameter("courseName");
        String teacherName = req.getParameter("teacherName");
        String credits = req.getParameter("credits");
        String classLocation = req.getParameter("classLocation");
        String maxStudents = req.getParameter("maxStudents");
        String weekday1 = req.getParameter("weekday1");
        String time1 = req.getParameter("time1");
        String weekday2 = req.getParameter("weekday2");
        String time2 = req.getParameter("time2");
        System.out.println(weekday1+time1);
        String classTime1=weekday1+time1;
        String classTime2=weekday2+time2;

        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        mapper.insertCourse(courseId,courseName,teacherName,Integer.parseInt(credits),classTime1,classTime2,classLocation,Integer.parseInt(maxStudents));

        sqlSession.commit();
        sqlSession.close();
        req.setAttribute("errorMessage","添加成功");
        req.getRequestDispatcher("indexServlet").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

4.utils工具类

(1)SqlSessionUtil

功能:获取一个SqlSession对象,以便后续进行数据库操作。

package com.hjj.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author:嘉佳 Date:2023/3/22 15:52
 **/
public class SqlSessionUtil {

    public static SqlSession getSqlSession(){
        SqlSession sqlSession=null;
        try {
//        获取核心配置文件(读取配置信息)的输入流
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//        获取SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
//        获取SqlSessionFactory对象(从文件或输入流中读取配置)
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//        获取sql的会话对象SqlSession-》Mybatis提供的操作数据库的对象
            sqlSession=sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }
}

5.resource

 (1)mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>

    <settings>
        <setting name="logImpl" value="LOG4J"/>
            <!--  开启自动驼峰命名规则映射  -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--
    type:设置需要起别名的类型
    alias:设置某个类型的别名
-->
    <typeAliases>
        <package name="com.hjj.pojo"/>
    </typeAliases>

    <!--配置连接数据库的环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--  引入映射文件-->
    <mappers>
        <package name="com.hjj.mapper"/>
    </mappers>
</configuration>

(2)CourseMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--命名空间的作用:在 MyBatis 的配置中引用 Mapper 接口或 XML 文件,以实现数据库操作的映射-->
<mapper namespace="com.hjj.mapper.CourseMapper">

</mapper>

其他两个只是改了

<mapper namespace="com.hjj.mapper.XXMapper">

(3) jdbc.propetise

数据库连接的相关配置信息

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=按自己
jdbc.username=按自己
jdbc.password=按自己

(4)log4j.propertise

log4j.rootLogger=DEBUG,console,file

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

log4j.appender.file = org.apache.log4j.RollingFileAppender

log4j.appender.file.File=./log/mybatis.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n


log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

6.jsp页面

(1)login.jsp:登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<h1>用户登录</h1>

<form action="${pageContext.request.contextPath}/login01" method="post">
    <label for="username">用户名:</label>
    <input type="text" name="username" id="username">
    <br><br>

    <label for="password">密码:</label>
    <input type="password" name="password" id="password">
    <br><br>

    <label for="role">角色:</label>
    <select name="role" id="role" required>
        <option value="teacher">Teacher</option>
        <option value="student">Student</option>
    </select>
    <br><br>

    <input type="submit" value="登录">
    <input type="reset" value="清除">
</form>
</body>
</html>

(2)chooseList.jsp:学生选课页面、教师浏览学生选课情况

<%--
  Created by IntelliJ IDEA.
  User: ALASIJIA
  Date: 2023/12/4
  Time: 0:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>选择课程</title>
<%--    --%>
<%--    <%--%>
<%--        String path = request.getContextPath();--%>
<%--        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/css/choose.css";--%>
<%--    %>--%>

    <link rel="stylesheet" href="xuanke/css/choose.css" />
<%--    <link rel="stylesheet" type="text/css" href="css/choose.css">--%>
</head>
<body>
<div>
    <c:if test="${roleType=='student'}">
        <p>选课界面</p>
        <p>你可以选择的课程列表如下(灰色按钮代表选课人数已满)</p>
        <a href="${pageContext.request.contextPath}/viewCourseServlet">课程情况一览</a>
    </c:if>
    <c:if test="${roleType=='teacher'}">
        <p>选课情况</p>
        <a href="${pageContext.request.contextPath}/xuanke/addCourse.jsp">添加新课程</a>
    </c:if>
    <a href="xuanke/login.jsp">退出登录</a>
</div>
<p style="color: red">${errorMessage }</p>
<div id="box">
    <table>
        <thead>
        <tr>
            <th>课程编号</th>
            <th>课程名称</th>
            <th>授课老师</th>
            <th>学分</th>
            <th>上课时间</th>
            <th>上课地点</th>
            <th>限选人数</th>
            <th>已选人数</th>
            <c:if test="${roleType=='student'}">
                <th>操作</th>
            </c:if>
        </tr>
        </thead>
        <tbody>

        <c:forEach items="${lists}" var="list">
            <tr>
                <td>${list.courseId}</td>
                <td>${list.courseName}</td>
                <td>${list.teacher}</td>
                <td>${list.point}</td>
                <td>${list.time1}<br>${list.time2}</td>
                <td>${list.location}</td>
                <td>${list.limited}</td>
                <td>${list.choose}</td>
                <c:if test="${roleType=='student'}">
                    <td>
                        <form action="${pageContext.request.contextPath}/chooseServlet" method="post">
                            <input type="hidden" name="courseId" value="${list.courseId}">
                            <input type="hidden" name="username" value="${sessionScope.username}">
                            <input type="submit" value="选课" id="submit">
                        </form>
                    </td>
                </c:if>
            </tr>
        </c:forEach>
        </tbody>
    </table>
</div>
</body>
</html>

(3)viewCourse.jsp :选课结果一览

<%--
  Created by IntelliJ IDEA.
  User: ALASIJIA
  Date: 2023/12/5
  Time: 21:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>选课结果</title>
    <link rel="stylesheet" href="xuanke/css/choose.css" />
</head>
<body>
<div><p>选课结果一览</p>
    <a href="${pageContext.request.contextPath}/indexServlet">继续选课</a>
    <a href="${pageContext.request.contextPath}/xuanke/login.jsp">退出登录</a>
</div>
<p>您已选择的课程列表如下:</p>
<div id="box">
    <table>
        <thead>
        <tr>
            <th>课程编号</th>
            <th>课程名称</th>
            <th>授课老师</th>
            <th>学分</th>
            <th>上课时间</th>
            <th>上课地点</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        <c:forEach items="${lists}" var="list">
            <tr>
                <td>${list.courseId}</td>
                <td>${list.courseName}</td>
                <td>${list.teacher}</td>
                <td>${list.point}</td>
                <td>${list.time1}<br>${list.time2}</td>
                <td>${list.location}</td>
                <td>
                    <form action="${pageContext.request.contextPath}/chooseServlet" method="post">
                        <input type="hidden" name="courseId" value="${list.courseId}">
                        <input type="hidden" name="username" value="${sessionScope.username}">
                        <input type="submit" value="退课" id="submit">
                    </form>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
    <c:if test="${empty lists}">
        <p>无选课记录</p>
    </c:if>
    <c:if test="${not empty lists}">
        <p>您当前选课总学分为:${totalPoint}</p>
    </c:if>
</div>
</body>
</html>

 (4)addCourse.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>添加课程</title>
<%--    <link rel="stylesheet" href="xuanke/css/choose.css" />--%>
    <link rel="stylesheet" href="css/addCourse.css" />
</head>
<body>
<div><p>添加课程</p>
    <p>请输入新课程详细信息,并点击添加课程:</p>
    <a href="${pageContext.request.contextPath}/indexServlet">课程情况一览</a>
    <a href="${pageContext.request.contextPath}/xuanke/login.jsp">退出登录</a>
</div>
<form action="${pageContext.request.contextPath}/addCourseServlet" method="post">

    <label for="courseId">课程ID:</label>
    <input type="text" id="courseId" name="courseId" required><br>

    <!-- 课程名称 -->
    <label for="courseName">课程名称:</label>
    <input type="text" id="courseName" name="courseName" required><br>

    <!-- 教师姓名 -->
    <label for="teacherName">教师姓名:</label>
    <input type="text" id="teacherName" name="teacherName" required><br>

    <!-- 学分 -->
    <label for="credits">学分:</label>
    <input type="text" id="credits" name="credits" required><br>


    <!-- 上课地点 -->
    <label for="classLocation">上课地点:</label>
    <input type="text" id="classLocation" name="classLocation" required><br>

    <!-- 限制人数 -->
    <label for="maxStudents">限制人数:</label>
    <input type="number" id="maxStudents" name="maxStudents" required><br>

    <!-- 上课时间第一次 -->
<%--    <label for="classTime1">上课时间(第一次):</label>--%>
<%--    <input type="datetime-local" id="classTime1" name="classTime1" required><br>--%>
    <span>上课时间(第一次):</span>
    <label for="weekday1">选择星期:</label>
    <select name="weekday1" id="weekday1">
        <option value="1">星期一</option>
        <option value="2">星期二</option>
        <option value="3">星期三</option>
        <option value="4">星期四</option>
        <option value="5">星期五</option>
    </select>
    <label for="time1">选择上课时间段:</label>
    <select name="time1" id="time1">
        <option value="1">8:05~9:50</option>
        <option value="2">10:15~12:00</option>
        <option value="3">13:35~15:20</option>
        <option value="4">15:45~17:30</option>
        <option value="5">18:30~20:45</option>
    </select>
    <br><br>
    <!-- 上课时间第二次 -->
    <span>上课时间(第二次):</span>
    <label for="weekday2">选择星期:</label>
    <select name="weekday2" id="weekday2">
        <option value="1">星期一</option>
        <option value="2">星期二</option>
        <option value="3">星期三</option>
        <option value="4">星期四</option>
        <option value="5">星期五</option>
    </select>
    <label for="time2">选择上课时间段:</label>
    <select name="time2" id="time2">
        <option value="1">8:05~9:50</option>
        <option value="2">10:15~12:00</option>
        <option value="3">13:35~15:20</option>
        <option value="4">15:45~17:30</option>
        <option value="5">18:30~20:45</option>
    </select>
    <br><br>
    <!-- 提交按钮 -->
    <input type="submit" value="添加课程">
</form>
</body>
</html>

(5)error.jsp

<%--
  Created by IntelliJ IDEA.
  User: ALASIJIA
  Date: 2023/11/27
  Time: 13:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        window.onload = function() {
            var confirmed = confirm("用户名或密码有误");
            if (confirmed) {
                window.location.href = "xuanke/login.jsp";
            }
        };
    </script>
</head>
<body>

</body>
</html>

三.实施结果

1.学生:

2. 老师:

登录页面与学生相同

四.系统测试

 


http://www.kler.cn/a/160245.html

相关文章:

  • A029-基于Spring Boot的物流管理系统的设计与实现
  • 一键生成本地SSL证书:打造HTTPS安全环境
  • Java 多线程(三)—— 死锁
  • 设计模式之装饰器模式(SSO单点登录功能扩展,增加拦截用户访问方法范围场景)
  • 建筑施工特种作业人员安全生产知识试题
  • 标准C++ 字符串
  • Dubbo(二)dubbo调用关系
  • golang使用sip协议 用户名和密码注册到vos3000
  • vue3中如何实现事件总线eventBus
  • 【数据结构(八)】哈希表
  • OpenCV-python numpy和基本作图
  • 甘草书店:#8 2023年11月22日 星期三「“说一套做一套”的甘草与麦田」
  • InnoDB的数据存储结构
  • Qt5.15.2的镜像网址
  • 用100ask 6ull配合 飞凌 elf1的教程进行学习的记录 - ap3216
  • SQL手工注入漏洞测试(Sql Server数据库)-墨者
  • 【Linux】进程控制-进程终止
  • 【musl-pwn】msul-pwn 刷题记录 -- musl libc 1.2.2
  • 面试官问:如何手动触发垃圾回收?幸好昨天复习到了
  • HarmonyOS学习--创建和运行Hello World
  • 基于SSM的物资物流系统
  • 什么是呼叫中心的语音通道?呼叫中心语音线路有几种?
  • [Electron] 将应用日志文件输出
  • 图解系列--Web服务器,Http首部
  • 我想涨工资,请问测试开发该怎么入门?
  • Zabbix自定义飞书webhook告警媒介2