基于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. 老师:

登录页面与学生相同

四.系统测试

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/223585.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Park Unpark

文章目录 当先调用park时&#xff1a;如果_counter0&#xff0c;这时候该线程阻塞&#xff0c;进入_cond阻塞&#xff0c;之后Unpark设置_counter为1后停止阻塞 当先调用Unpark时&#xff1a;此时先将_counter设置为1&#xff0c;当后面出现park时一判断_counter为1&#xff0c…

IntelliJ IDEA 之初体验

文章目录 第一步&#xff1a;下载与安装 IntelliJ IDEA1&#xff09;官网下载2&#xff09;选择那种安装包3&#xff09;开始下载4&#xff09;解压 第二步&#xff1a;启动 IntelliJ IDEA第三步&#xff1a;创建第一个 Java 项目第四步&#xff1a;运行第一个 Java 程序1&…

Java注册并监听全局快捷键

背景 之前在博客中分享了SWT托盘功能, 随之带来一个问题, 当程序最小化后无法快速唤醒, 按照平时使用软件的思路, 自然想到了注册全局快捷键, 本文介绍使用java方式实现全局快捷键的注册. 方案 通过google,搜到一个现成的库: jintellitype, 使用maven可以直接引用, 非常方便…

使用TouchSocket适配一个c++的自定义协议

这里写目录标题 说明一、新建项目二、创建适配器三、创建服务器和客户端3.1 服务器3.2 客户端3.3 客户端发送3.4 客户端接收3.5 服务器接收与发送 四、关于同步Send 说明 今天有小伙伴咨询我&#xff0c;他和同事&#xff08;c端&#xff09;协商了一个协议&#xff0c;如果使…

http和https的区别有哪些

目录 HTTP&#xff08;HyperText Transfer Protocol&#xff09; HTTPS&#xff08;HyperText Transfer Protocol Secure&#xff09; 区别与优势 应用场景 未来趋势 当我们浏览互联网时&#xff0c;我们经常听到两个常用的协议&#xff1a;HTTP&#xff08;HyperText Tra…

【LeetCode刷题-链表】--92.反转链表II

92.反转链表II /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(int val, ListNode next) { this.val val; this.next next; }* }*/ cla…

项目中使用之Maven BOM

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a; 工具教程 ✨特色专栏&#xff1a; MyS…

MYSQL全语法速查(含示例)

文章目录 1.从简单的查询开始查找所有记录(SELECT *)查找记录中的所有登录名(SELECT)查找登录名为admin的密码(WHERE)查找电话号码非空的记录(IS NOT NULL)查找所在城市为北京或者用户名字是李四的记录(OR)查找所在城市为北京并且用户名字是张三的记录(AND)查找用户名字是李四或…

【节日专栏】Python海龟绘制圣诞树代码

圣诞节就要到了&#xff0c;有没有要送给朋友礼物的程序员呢&#xff1f; import turtledef tree(d, s):if d < 0:returnturtle.forward(s)tree(d - 1, s * 0.8)turtle.right(120)tree(d - 3, s * 0.5)turtle.right(120)tree(d - 3, s * 0.5)turtle.right(120)turtle.backw…

4.10 构建onnx结构模型-Softmax

前言 构建onnx方式通常有两种&#xff1a; 1、通过代码转换成onnx结构&#xff0c;比如pytorch —> onnx 2、通过onnx 自定义结点&#xff0c;图&#xff0c;生成onnx结构 本文主要是简单学习和使用两种不同onnx结构&#xff0c; 下面以 Softmax 结点进行分析 方式 方法一…

神通数据库备份

备份策略&#xff1a; 每月1、15日00:00全量物理备份 每周一凌晨02:00差异物理备份 其余每天凌晨03:00增量物理备份 使用的工具&#xff1a; 数据库维护工具 环境&#xff1a;windows11 step1&#xff1a;创建全量/差异/增量物理备份调度任务 其中&#xff1a; 备份模式&…

C语言之多维数组

所谓多维数组就是以多个数组为单位组成的数组&#xff0c;即元素本身是数组的数组。下面我们来学习多维数组的基本知识&#xff1a; 多维数组 上一节学习的数组都是int型或double型等单一类型&#xff0c;实际上数组本身也可以作为组成数组的元素。 以数组作为元素的数组时二…

HarmonyOS学习--创建和运行Hello World

创建和运行Hello World 打开DevEco Studio&#xff0c;在欢迎页单击Create Project&#xff0c;创建一个新工程。根据工程创建向导&#xff0c;选择创建Application应用或Atomic Service元服务。选择“Empty Ability”模板&#xff0c;然后单击Next。关于工程模板的介绍和支持…

C++ Core Guidelines解析 ( 好书推荐 )

C Core Guidelines是Bjarne和 Herb Sutter发起编写的一个开源项目&#xff0c;汇聚了 C社区多年来积累的宝贵经验&#xff0c;是非常全面的编程最佳实践指导&#xff0c;包括代码风格、函数、类、错误处理、性能优化等&#xff0c;可以说是C社区的集大成者。用Effective Modern…

Python函数

1.函数 1.1 函数概述 函数定义和优势 不同形状正方形打印 # 2个 for i in range(0, 2):for j in range(0, 2):print("*", end"")print() # 3个 for i in range(0, 3):for j in range(0, 3):print("*", end"")print() # 4个 for i …

NET Core迁移前工作

前段时间迁移.NET Core做了大量的试水和评估&#xff0c;今天整理一下分享给大家。大致有以下几个部分&#xff1a; 1. .NET Core的由来 2. 为什么要迁移.NET Core 3. .NET Core3.X主要特性 4. .NET Standard和.NET Core 5. .NET Core Roadmap&版本选择 接下来&#…

记录一次vscode markdown的图片路径相关插件学习配置过程

插件及说明查找过程 csdn搜索markdown图片路径&#xff0c;找到关于这一款插件的回答。打开vscode拓展搜索Paste Image这款插件&#xff0c;看到下载量挺高的&#xff0c;应该不赖。 点击仓库,进入该插件开源的github仓库,查看README文件阅读说明. 淡然在Vscode 插件项目下的细…

minio的k8s的单机部署

minio的k8s的单机部署 apiVersion: apps/v1 kind: Deployment metadata:name: minionamespace: itshare spec:replicas: 1selector:matchLabels:app: miniotemplate:metadata:labels:app: miniospec:containers:- name: minioimage: minio/minio:RELEASE.2022-10-15T19-57-03Z…

微服务开发:断路器详解

微服务是目前业界使用的最重要的实现方面。通过使用微服务架构&#xff0c;开发人员可以消除他们以前在单体应用程序中遇到的许多问题。展望未来&#xff0c;人们开始在微服务中搜索和采用各种模式。大多数时候&#xff0c;新模式的产生是为了解决另一个模式中出现的常见问题。…