JavaWeb学生选课(Servlet、JSP、JDBC)

1

运行结果:

clipboard.png

clipboard.png

clipboard.png

clipboard.png

clipboard.png

clipboard.png

clipboard.png

数据库的2个表:
course表
clipboard.png

student表
clipboard.png

ps:一定要build path导入数据库用的jar包,以及在在lib文件夹中导入数据库jar包

文件目录结构:

clipboard.pngclipboard.png

具体代码:
index.jsp 首页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎进入选课系统</title>
</head>
<body>
<center>
<h2>欢迎进入选课 系统</h2>
<a href="login.jsp">学生登录</a>
<a href="regist.jsp">学生注册</a>
<a href="admin.jsp">管理员登录</a>
</center>
</body>
</html>

login.jsp 学生登录

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生登录</title>
</head>
 
<body style="text-align: center;">
      <br><br>
      <h3>学生登录</h3>
      <form action="LoginServlet" method="post">
          学号:<input type="text" name="stuno">
          <br><br>
          密码:<input type="password" name="stupassowrd">
          <br><br>
          <input type="submit" value="登录" name="submit">
          <a href="regist.jsp" role="button">注册</a>
          <a href="index.jsp">返回</a>
      </form>
 </body>
</html>

regist.jsp 学生注册

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h2 align=center>注册页面</h2>
    <center>
      
          <form action="RegisterServlet" method="post" >  
              <table  border="1">
                  <tr>
                      <td>学号:</td>
                      <td><input name="userNo"></td>
                  </tr>
                  <tr>
                      <td>姓名:</td>
                      <td><input name="userName"></td>
                  </tr>
                  <tr>
                      <td>密码:</td>
                      <td><input name="password" type="password"></td>
                  </tr>
                  
                  <tr>
                      <td>院系:</td>
                      <td><input name="major"></td>
                  </tr>
                  <tr>
                      <td>年级:</td>
                      <td><input name="grade"></td>
                  </tr>
                  <tr>
                      <td>班级:</td>
                      <td><input name="sclass"></td>
                  </tr>
                  <tr align="center">
                      <td colspan="2"><input type="submit" value="提交注册"><input type = "reset" value = "重置"></td>
                  </tr>
              </table>
          </form>
          
          您有账号?<a href="login.jsp"><front color="GREEN" >点击直接登录</front></a>
      </center>    

</body>
</html>

studentIndex.jsp 学生选课主页

  <!-- JSTL1.1 的声明是: -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html; ISO-8859-1" language="java" import="java.util.*" pageEncoding="utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>学生选课</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!--<link rel="stylesheet" type="text/css" href="pages/css/studentIndex.css">  -->  
    
    <script type="text/javascript" src="href/jquery-3.4.0.js"></script>
    <script type="text/javascript">
        //选择课程
        $(document).ready(
                function() {
                $("input[name='select']").click(function(){
                    var node = $(this);
                    //获取剩余量
                  //通过td里面的元素获得tr,使用tr的children(“td”) 方法获取所有的td,在通过eq(1) 拿第二个td
                    var remainNum = $(this).parent().parent().children("td").eq(1).html();
                    console.log(remainNum);
                    if (!(remainNum == "0")) {
                        $.ajax({
                            url:"http://localhost:8080/xxmtest6/RemainAddServlet",    //请求的url地址
                            dataType:"json",    //返回格式为json
                            async:true,    //请求是否异步,默认为异步,这也是ajax重要特性
                            data:{"id":$(this).attr("id")},    //参数值
                            type:"POST",    //请求方式
                            beforeSend:function(){
                                //请求前的处理
                            },
                            success:function(req){
                                //请求成功时处理
                                //node.parent().parent().remove();
                                node.parent().parent().children("td").eq(1).html(parseInt(remainNum)-parseInt(1));
                                alert("已选中!");
                                document.getElementById("stuInfoIframe").contentWindow.location.reload(true);
                            },
                            complete:function(){
                                //请求完成的处理
                                //alert("请求完成!");
                            },
                            error:function(){
                                //请求出错处理
                                alert("重复选择!");
                            }
                        });
                    } else {
                        alert("此课程人数已满!");
                    }
                });
            });
    </script>
  </head>
  
  <body>
  <header><a style="flow :right" href="index.jsp">退出登录</a></header>
      <h3>学生选课界面</h3>
      <form action="SearchServlet" method="post">
          查找:<input type="text" name="search" value=<%=request.getParameter("search") == null?"":request.getParameter("search")%> >
          <input type="submit" value="搜索" name="ok" />
      </form>
      <br><br>
    <table class="table">
        <tr>
            <td>课程名称</td>
            <td>剩余量</td>
            <td>总数量</td>
            <td>任课教师</td>
            <td>课程地点</td>
            <td>课程时间</td>
            <td>课程时长</td>
            <td>操作</td>
        </tr>
        
        <c:forEach items="${courseList}" var="courseList">
        <tr>
            <td>${courseList.courseName }</td>
            <td>${courseList.courseRemain }</td>
            <td>${courseList.courseTotal }</td>
            <td>${courseList.courseTeacher }</td>
            <td>${courseList.coursePlace }</td>
            <td>${courseList.courseTime }</td>
            <td>${courseList.courseTimelength }</td>
            <td>
                <input type="button" value="选中" name="select" id="${courseList.courseId}"/>
            </td>
        </tr>
        </c:forEach>
    </table>
    
    <br><br>
    <hr>
    <br><br>
    <h2>我的选课</h2>
    <frameset>
        <iframe style="width: 80%;" id="stuInfoIframe" src="StudentInfoServlets"></iframe>
    </frameset>
  </body>
</html>

studentInfo.jsp 学生已选的课程展示

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html; ISO-8859-1" language="java" import="java.util.*" pageEncoding="utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>学生课程</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
     <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script type="text/javascript" src="href/jquery-3.4.0.js"></script>
    <script type="text/javascript">
    //学生课程
    $(document).ready(
        function() {
            $.ajax({
                url:"http://localhost:8080/xxmtest6/StudentInfoServlets",    //请求的url地址
                //dataType:"text",   //返回格式
                async:true,//请求是否异步,默认为异步,这也是ajax重要特性
                data:{
                },    //参数值,发送个服务端的数据
                type:"GET",   //请求方式
                beforeSend:function(){
                    //请求前的处理
                },
                success:function(req){
                    //请求成功时处理
                    //alert("学生课程显示成功!");
                },
                complete:function(){
                    //请求完成的处理
                    //alert("请求完成!");
                },
                error:function(){
                    //请求出错处理
                    //alert("学生课程显示失败!");
                }
            });
        });
    
        //取消课程
        $(document).ready(
                function() {
                $("input[name='cancel']").click(function(){
                    var node = $(this);
                    var nodeId = $(this).attr("id");
                    var remainNum = $("#"+nodeId, window.parent.document).parent().parent().children("td").eq(1).html();
                    
                    $.ajax({
                        url:"http://localhost:8080/xxmtest6/CancelServlet",    //请求的url地址
                        dataType:"json",   //返回格式为json
                        async:true,//请求是否异步,默认为异步,这也是ajax重要特性
                        data:{"id":$(this).attr("id")},    //参数值
                        type:"POST",   //请求方式
                        beforeSend:function(){
                            //请求前的处理
                        },
                        success:function(req){
                            //请求成功时处理
                               /* var iframe = window.parent;
                            var div =iframe.document.getElementById(nodeId);
                            alert(div.length); */
                            node.parent().parent().remove();
                             $("#"+nodeId, window.parent.document).parent().parent().children("td").eq(1).html(parseInt(remainNum)+parseInt("1"));
                             alert("取消成功!");
                            //window.location.reload();
                        },
                        complete:function(){
                            //请求完成的处理
                            //alert("请求完成!");
                        },
                        error:function(){
                            //请求出错处理
                            alert("取消失败!");
                        }
                    });
                });
            });
    </script>
  </head>
  
  <body>
      <table class="table">
        <tr>
            <td>课程名称</td>
            <td>任课教师</td>
            <td>课程地点</td>
            <td>课程时间</td>
            <td>课程时长</td>
            <td>操作</td>
        </tr>
        
        <c:forEach items="${studentCourseList }" var="studentCourseList">
        <tr>
            <td>${studentCourseList.courseName }</td>
            <td>${studentCourseList.courseTeacher }</td>
            <td>${studentCourseList.coursePlace }</td>
            <td>${studentCourseList.courseTime }</td>
            <td>${studentCourseList.courseTimelength }</td>
            <td>
                <input type="button" value="取消" name="cancel" id="${studentCourseList.courseId }" />
            </td>
        </tr>
        </c:forEach>
    </table>
  </body>
</html>

admin.jsp 管理员登录

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>管理员登录</title>
</head>
<body style="text-align: center;">
      <br><br>
      <h3>管理员登录</h3>
      <%
          String error = (String)session.getAttribute("error");
      if(error!=null&&error.length()!=0){
          out.println(error);
      }
          
      %>
      <form action="checkadmin.jsp" method="post">
          账号:<input type="text" name="adno">
          <br><br>
          密码:<input type="password" name="adpassowrd">
          <br><br>
          <input type="submit" value="登录" name="submit">
           <a href="index.jsp">返回</a>
      </form>
 </body>
</html>

adminCourse.jsp 管理课程页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  

<script type="text/javascript" src="href/jquery-3.4.0.js"></script>

<title>课程后台管理</title>
</head>
<body>
<header><a href="index.jsp">退出登录</a></header>

    <div id="app">

        <!-- 标题 -->
        <div class="jumbotron jumbotron-fluid py-3">
            <div class="container">
                <h1 class="display-3">选课后台管理</h1>
                <p class="lead"></p>
            </div>
        </div>
         <!-- 主体 -->
        <div class="container-fluid">
            <div class="row">
            <form action="CreateCourseServlet">
                <div class="col-lg-14 col-sm-12">
                    <!-- 输入表单 -->
                    
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title" style="color:blue">添加课程</h4>
                            <!-- 输入框 -->
                            <div class="form-group">
                              <label for="">课程名字</label>
                              <input type="text" 
                                class="form-control form-control-lg"
                                
                                name="cName">
                            </div>
                            <div class="form-group">
                              <label for="">任课老师</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                
                                name="cTeacher">
                            </div>
                            <div class="form-group">
                              <label for="">上课地点</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                
                                name="cPlace">
                                 
                                  </div>
                                <div class="form-group">
                              <label for="">上课时间</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                
                                name="cTime">
                            </div>
                            <div class="form-group">
                              <label for="">课时</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                
                                name="cLong">
                            </div>
                            <div class="form-group">
                              <label for="">上课总人数</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                
                                name="cTotal">
                            </div>
                            <div class="form-group">
                              <label for="">剩余可选数</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                name="cRemain">
                            </div>
                              
                            </div>

                            <!-- 按钮 -->
                            <input type="submit" class="btn btn-primary btn-lg btn-block" value="创建">
                     </div>
                     </div>   
                    
                </form>
                
                
                <div class="col-lg-8 col-sm-12">
                    <!-- 表格 -->
                    <table class="table text-center">
                        <thead>
                            <tr class="text-center">
                                <th>编号</th>
                                <th style="width: 12% ">课程名</th>
                                <th>任课老师</th>
                                <th>上课地点</th>
                                <th style="width: 25% ">上课时间</th>
                                <th style="width: 7%">课时</th>
                                <th style="width: 7%">总人数</th>
                                <th >剩余数</th>
                                <th style="width: 18% " >操作</th>
                            </tr>
                        </thead>
                        
         <c:forEach items="${courseList}" var="courseList">
        <tr>
            <td>${courseList.courseId}</td>
            <td>${courseList.courseName }</td>
            
            <td>${courseList.courseTeacher }</td>
            <td>${courseList.coursePlace }</td>
            <td>${courseList.courseTime }</td>
            
            <td>${courseList.courseTimelength }</td>
            
            <td>${courseList.courseTotal }</td>
            <td>${courseList.courseRemain }</td>
            <td >
                  <div class="row">
                                        <div class="col-lg-6 col-sm-12 " >
                                            <button type="button"  class="btn btn-primary " data-toggle="modal" data-target="#edit1${courseList.courseId}">编辑</button>
                                            <!-- 对话框 5.2 -->

                                            
                                            <!-- Modal 模态对话框 -->
                                            <div class="modal fade" id="edit1${courseList.courseId}" tabindex="-1" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
                                                <div class="modal-dialog" role="document">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title">编辑</h5>
                                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                    <span aria-hidden="true">&times;</span>
                                                                </button>
                                                        </div>
                                                        <div class="modal-body">
                                <!-- 开始编辑 -->
                                <form action="AdminCourseServlet" name="edit" method="post">
                                <div class="form-group">
                                    <!-- 课程号作为id,不显示,根据id进行修改 -->
                                    <input type="hidden" class="form-control" name="newNo" id="newNo"
                                      aria-describedby="helpId" value="${courseList.courseId}">
                                  </div>
                                 <div class="form-group">
                              <label for="">课程名字</label>
                              <input type="text" 
                                class="form-control form-control-lg"
                                value="${courseList.courseName }"
                                name="ccName">
                            </div>
                            <div class="form-group">
                              <label for="">任课老师</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.courseTeacher }"
                                name="ccTeacher">
                            </div>
                            <div class="form-group">
                              <label for="">上课地点</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.coursePlace }"
                                name="ccPlace">
                                 
                                  </div>
                                <div class="form-group">
                              <label for="">上课时间</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.courseTime }"
                                name="ccTime">
                            </div>
                            <div class="form-group">
                              <label for="">课时</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.courseTimelength }"
                                name="ccLong">
                            </div>
                            <div class="form-group">
                              <label for="">上课总人数</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.courseTotal}"
                                name="ccTotal">
                            </div>
                            <div class="form-group">
                              <label for="">剩余可选数</label>
                              <input type="text"
                                class="form-control form-control-lg"
                                value="${courseList.courseRemain }"
                                name="ccRemain">
                            </div>
                                              
                              <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                                                            <input type="submit"  class="btn btn-primary" value="修改">
                                                        </div>
                             </form>
                                                    
                                                    </div>
                                                </div>
                                            </div>
                                            
                                        </div>
                                        
                                        <div class="col-lg-6 col-sm-12 " >
                                        <form action="CancelCourse">
                                            
                                            <input type="submit"  class="btn btn-danger " value="删除">
                                        <input type="hidden" class="form-control" name="newNo" id="newNo"
                                      aria-describedby="helpId" value="${courseList.courseId}">
                                        </form>
                                        </div>
                                    </div>   
            </td>         
        </tr>
        </c:forEach>
                  
                    </table>
        </div>
            </div>
        </div>
</div>


  <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

checkadmin.jsp 检查管理员账号密码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>check</title>
</head>
<body>
<% String adno=request.getParameter("adno");
          String adpassword = request.getParameter("adpassowrd");
          if(adno==null||adno.length()==0||adpassword==null ||adpassword.length()==0){
              request.getSession().setAttribute("error", "账号或密码错误");
              response.sendRedirect("admin.jsp");
          }else{
              if(!adno.equals("admin")||!adpassword.equals("admin")){
                  request.getSession().setAttribute("error", "账号或密码错误");
                  response.sendRedirect("admin.jsp");
              }else{
                  request.getSession().setAttribute("error", "");
                  response.sendRedirect("/xxmtest6/FindCourseServlet");
              }
          }
          %>
</body>
</html>

bean
Student.java 学生实体

package xxm.bean;

/**
 * 学生实体类
 * @author xxm
 *
 */
public class Student {

    String no;
    String name;
    String passwd;
    String major;
    String grade;
    String sclass;
    String selectedCourse;
    
    
    public Student() {
        
    }

    
    
    public String getSelectedCourse() {
        return selectedCourse;
    }



    public void setSelectedCourse(String cid) {
        this.selectedCourse = cid;
    }



    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getSclass() {
        return sclass;
    }

    public void setSclass(String sclass) {
        this.sclass = sclass;
    }

    
}

Course.java 课程实体类

package xxm.bean;

/**
 * 课程
 * 
 * @author xxm
 *
 */
public class Course {

    int courseId;
    String courseName;
    int courseRemain;
    int courseTotal;
    String courseTeacher;
    String coursePlace;
    String courseTime;
    String courseTimelength;
    
    public Course() {
        
    }

    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

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

    public int getCourseRemain() {
        return courseRemain;
    }

    public void setCourseRemain(int courseRemain) {
        this.courseRemain = courseRemain;
    }

    public int getCourseTotal() {
        return courseTotal;
    }

    public void setCourseTotal(int courseTotal) {
        this.courseTotal = courseTotal;
    }

    public String getCourseTeacher() {
        return courseTeacher;
    }

    public void setCourseTeacher(String courseTeacher) {
        this.courseTeacher = courseTeacher;
    }

    public String getCoursePlace() {
        return coursePlace;
    }

    public void setCoursePlace(String coursePlace) {
        this.coursePlace = coursePlace;
    }

    public String getCourseTime() {
        return courseTime;
    }

    public void setCourseTime(String courseTime) {
        this.courseTime = courseTime;
    }

    public String getCourseTimelength() {
        return courseTimelength;
    }

    public void setCourseTimelength(String courseTimelength) {
        this.courseTimelength = courseTimelength;
    }
    
    
    
}

数据库操作
DBO
DBOper.java

package xxm.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import xxm.bean.Student;
import xxm.dao.StudentDao;


public class DBOper {

  //驱动
      private    static String driver = "com.mysql.cj.jdbc.Driver";
      //database名,选择我要用的数据库shiyan6
      private    static String url = "jdbc:mysql://localhost:3306/shiyan6?serverTimezone=UTC";
      //验证用户名和密码
      private    static String    username = "root";
      private    static String  passwd= "123456";
      //数据库的连接对象
      private static Connection conn = null;
      //Statement对象
      private static  PreparedStatement ps = null;
       ResultSet rs = null;
       
      /**
       * 连接数据库
       * @return
       * @throws SQLException
       */
      public   Connection getConnection() throws SQLException {
          try {
              
              Class.forName(driver);
              conn = DriverManager.getConnection(url,username,passwd);//连接数据库
          } catch (ClassNotFoundException e) {
              System.err.println("无法连接数据库!");
          }//加载驱动
          return conn;        
      }

    //执行sql语句,可以进行查询
    public ResultSet executeQuery(String preparedSql,String []param){
        try{
            ps = conn.prepareStatement(preparedSql);
            if(param != null){
                for (int i = 0; i < param.length; i++) {
                    ps.setString(i + 1, param[i]);
                }
            }
            rs = ps.executeQuery();
        }catch(SQLException e){
            e.printStackTrace();
        }       
        return rs;

    }
    //执行sql语句,增加,修改,删除
    public int executeUpdate(String preparedSql,String[]param){
        int num = 0;
        try{
            ps = conn.prepareStatement(preparedSql);
            if(ps != null){
                for (int i = 0; i < param.length; i++) {
                    ps.setString(i + 1, param[i]);
                }
            }
            num = ps.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return num;
    }
    
    public static void main(String[] args) {
        try {
            DBOper dao = new DBOper();
            Connection conn=dao.getConnection();
            if(conn!=null)
            {
                System.out.println("连接数据库正常");
            }
            else {
                System.out.println("连接数据库异常");
            }

        } catch (Exception ex) {
            // TODO: handle exception
            ex.printStackTrace();
        }
    }
}

StudentDao.java

package xxm.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import xxm.bean.Student;
import xxm.database.DBOper;


public class StudentDao extends DBOper{

    Connection conn =null;
    
    public StudentDao() {

        try {
            conn= super.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 添加学生用户
     * @param student
     * @return
     */
    public boolean addUser(Student student){
        boolean r = false;
       
        String sql = "INSERT INTO student(sno,sname,spassword,smajor,sclass,sgrade) VALUES(?,?,?,?,?,?);";
       
        try{

           int num = this.executeUpdate(sql,new String[]{student.getNo(),student.getName(),student.getPasswd(),student.getMajor(),student.getSclass(),student.getGrade()});
            if(num > 0){
                r = true;
               
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //this.closeAll();
        }
        return r;
    }
    
}

CourseDao.java

package xxm.dao;

import java.sql.Connection;
import java.sql.SQLException;

import xxm.bean.Course;
import xxm.bean.Student;
import xxm.database.DBOper;

/**
 * 课程管理
 * 
 * @author xxm
 *
 */
public class CourseDao  extends DBOper{

    Connection conn =null;
    
    public CourseDao(){
        try {
            conn= super.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /** 
     * 添加选课课程
    * @param course
    * @return
    */
   public boolean addCourse(Course course){
       boolean r = false;
      
       String sql = "INSERT INTO course(course_Name,course_Remain,course_Total,course_Teacher,course_Place,course_Time,course_Timelength) VALUES(?,?,?,?,?,?,?);";
      
       try{

          int num = this.executeUpdate(sql,new String[]{course.getCourseName(),String.valueOf(course.getCourseRemain()),String.valueOf(course.getCourseTotal()),course.getCourseTeacher(),course.getCoursePlace(),course.getCourseTime(),course.getCourseTimelength()});
           if(num > 0){
               r = true;
              
           }
       }catch(Exception e){
           e.printStackTrace();
       }finally{
           //this.closeAll();
       }
       return r;
   }
   
  /**
   * 更新
   * @param course
   * @return
   */
   public boolean update(Course course) {
       
       String sql = "update course set course_Name=?,course_Teacher=?,course_Place=?,course_Time=?,course_Timelength=?,course_Total=?,course_Remain=? where course_Id = ? ";
       int num = this.executeUpdate(sql, new String[]{course.getCourseName(),
               course.getCourseTeacher(),
               course.getCoursePlace(),
               course.getCourseTime(),
               course.getCourseTimelength(),
               String.valueOf(course.getCourseTotal()),
               String.valueOf(course.getCourseRemain()),
               String.valueOf(course.getCourseId())});
      if(num>0)
        return true;
      else return false;
   }
}

Servlet

处理学生选课的servlet
RegisterServlet.java 学生注册

package xxm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
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 xxm.bean.Student;
import xxm.dao.StudentDao;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#HttpServlet()
         */
        public RegisterServlet() {
        
            super();
            // TODO Auto-generated constructor stub
        }

        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doPost(request,response);
        }

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset = utf-8");
            String userno = request.getParameter("userNo");
            String username = request.getParameter("userName");
            String userpass = request.getParameter("password");
            String major = request.getParameter("major");
            String grade = request.getParameter("grade");
            String sclass = request.getParameter("sclass");
            PrintWriter out = response.getWriter();

            Student user = new Student();
            user.setNo(userno);
            user.setName(username);
            user.setPasswd(userpass);
            user.setMajor(major);
            user.setGrade(grade);
            user.setSclass(sclass);
           
            StudentDao dao = new StudentDao();
            try {
                Connection conn = dao.getConnection();
                if(conn!=null) {
                    out.print("conn is not null");
                }
                 if(dao.addUser(user)){
                        out.print("注册成功!");
                        response.sendRedirect("login.jsp");
                    }
                    else{
                        out.print("注册失败!");
                    }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

LoginServlet.java 学生登录

package xxm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import xxm.database.DBOper;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        PrintWriter out = response.getWriter();
        String stuno = request.getParameter("stuno");
        String stupass = request.getParameter("stupassowrd");    
        DBOper db = new DBOper();
        try {
            db.getConnection();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String sql = "SELECT sno,spassword FROM student WHERE sno = ? AND spassword = ?";
        ResultSet rs = db.executeQuery(sql,new String[]{stuno,stupass});
        try {
            if(rs != null && rs.next()){
                HttpSession session = request.getSession();

                session.setAttribute("numSession", stuno);
                Cookie cookie = new Cookie("stuno",stuno);
                cookie.setMaxAge(60*60*24*30);
                response.addCookie(cookie);
                //登录成功,跳转...
   
                RequestDispatcher dispatcher = request.getRequestDispatcher("/FindServlet");
                dispatcher.forward(request,response);
            }else{
                out.print("登录失败");
                out.print("<br><a href = 'login.jsp'>重新登陆</a>");
//                response.setContentType("text/html;charset=UTF-8");
//               
//                response.setHeader("refresh", "0; url=/StudentSelect");

            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void init()throws ServletException {

    }

}

FindServlet.java 选课主页

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;

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.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import xxm.bean.Course;
import xxm.database.DBOper;

/**
 * 主页显示信息的Servlet
 * 
 * @author xxm
 *
 */
@WebServlet("/FindServlet")
public class FindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

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


     public void process(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            try { 
                 
                // 创建Connection连接
                DBOper dao = new DBOper();
                  Connection conn = dao.getConnection(); 
                  // SQL语句
                  String sql = "select * from course"; 
                  // 获取Statement
                  Statement statement =  conn.createStatement(); 
              
                  ResultSet resultSet = statement.executeQuery(sql); 
              
                  List<Course> courseList = new ArrayList<Course>(); 
                  while (resultSet.next()) { 
                    Course course = new Course();
                    course.setCourseId(resultSet.getInt("course_Id"));
                    course.setCourseName(resultSet.getString("course_Name"));
                    course.setCourseRemain(resultSet.getInt("course_Remain"));
                    course.setCourseTotal(resultSet.getInt("course_Total"));
                    course.setCourseTeacher(resultSet.getString("course_Teacher"));
                    course.setCoursePlace(resultSet.getString("course_Place"));
                    course.setCourseTime(resultSet.getString("course_Time"));
                    course.setCourseTimelength(resultSet.getString("course_Timelength"));
                    
                    courseList.add(course);
                  } 
                  req.setAttribute("courseList", courseList);

                  resultSet.close(); 
                  statement.close(); 
                  conn.close(); 
              
                } catch (Exception e) { 
                  e.printStackTrace(); 
                } 

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

StudentInfoServlets.java 学生已选课程

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

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 xxm.bean.Course;
import xxm.bean.Student;
import xxm.database.DBOper;

/**
 * Servlet implementation class StudentInfoServlets
 */
@WebServlet("/StudentInfoServlets")
public class StudentInfoServlets extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentInfoServlets() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
    
    protected void process(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try { 
            
              Connection conn = (new DBOper()).getConnection(); 
              Statement statement = (Statement) conn.createStatement(); 
              
              String numSession = (String) req.getSession().getAttribute("numSession");
              String sql1 = "select * from student where sno = " + numSession;
          
              ResultSet resultSet = statement.executeQuery(sql1); 
  
              List<Student> courseStudentList = new ArrayList<Student>(); 
              while (resultSet.next()) { 
                  Student student = new Student();
                  student.setSelectedCourse(resultSet.getString("selected_course"));
                  //将学生加入到课程列表
                  courseStudentList.add(student); 
              } 
 
              String courseStudentString= courseStudentList.get(0).getSelectedCourse();
              String[] array = courseStudentString.split(",");
              
              List<Course> studentCourseList = new ArrayList<Course>(); 
              for (String s:array) {
                  String sql2 = "select * from course where course_Id = " + s ;
                  resultSet = statement.executeQuery(sql2);
                  
                  while (resultSet.next()) {
                      Course course = new Course();
                      course.setCourseId(resultSet.getInt("course_Id"));
                      course.setCourseName(resultSet.getString("course_Name"));
                      course.setCourseTeacher(resultSet.getString("course_Teacher"));
                      course.setCoursePlace(resultSet.getString("course_Place"));
                      course.setCourseTime(resultSet.getString("course_Time"));
                      course.setCourseTimelength(resultSet.getString("course_Timelength"));
                      //将课程加入学生课程列表
                      studentCourseList.add(course);
                  }
              }
 
              req.setAttribute("studentCourseList", studentCourseList);

              resultSet.close(); 
              statement.close(); 
              conn.close(); 
          
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
           
            resp.setCharacterEncoding("UTF-8");
            req.getRequestDispatcher("studentInfo.jsp").forward(req, resp);
    }

}

RemainAddServlet.java 剩余可选数

package xxm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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 xxm.database.DBOper;

/**
 * Servlet implementation class RemainAddServlet
 */
@WebServlet("/RemainAddServlet")
public class RemainAddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
     @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            process(req, resp);
        }
     
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            process(req, resp);
        }
        
        protected void process(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            try { 
                DBOper db = new DBOper();
                  Connection conn = db.getConnection(); 
                  Statement statement = (Statement) conn.createStatement(); 
     
                  //String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8");
                  
                  req.setCharacterEncoding("UTF-8");
                  //课程号
                  String keyString = req.getParameter("id");
                  
                  if(keyString == null) {
                        keyString = "";
                        resp.sendRedirect("/FindServlet");
                        
                        return;
                  }
                  
                  //添加课程,只能选一门课程
                  String numSession = (String) req.getSession().getAttribute("numSession");
                  String sql1 = "select selected_course from student where sno = " + numSession;
                  ResultSet resultSet = statement.executeQuery(sql1);
                  String course = "";
                  while (resultSet.next()) {
                      course = resultSet.getString("selected_course");
                  }
                  
                  //还没有选课
                  if(course==null||course.length()==0) {
                      
                      //修改课程数据
                      String sql2 = "update student set selected_course=\'" + keyString + "\' where sno = " + numSession;
                      statement.executeUpdate(sql2);
                  
                      //课程余量-1
                      String sql = "update course set course_Remain=course_Remain-1 where course_Id = \'"+ keyString + "\'";
                      statement.executeUpdate(sql);
                  
                  }else {
                      PrintWriter pw = resp.getWriter();
                      pw.println("<h4>重复选课</h4>");
                  }
                  
                 
                  statement.close(); 
                  conn.close(); 
                } catch (Exception e) { 
                  e.printStackTrace(); 
                }
            
            resp.getWriter().print("{\"data\":\"返回json数据!\"}"); 
        }
    
}

CancelServlet.java 取消选课

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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 xxm.database.DBOper;

/**
 * 取消选课
 */
@WebServlet("/CancelServlet")
public class CancelServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CancelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
    
    protected void process(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try { 
              
              Connection conn = (new DBOper()).getConnection(); 
              Statement statement = (Statement) conn.createStatement();
              
              //String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8");
              req.setCharacterEncoding("UTF-8");
              String course = req.getParameter("id");
              
              if(course == null) {
                    course = "";
                    resp.sendRedirect("/FindServlet");
                    
                    return;
              }
              
              String numSession = (String) req.getSession().getAttribute("numSession");
//              String sql1 = "select selected_course from student where sno = '" + numSession + "'";
//              ResultSet resultSet = statement.executeQuery(sql1);
 
              //取出课程字符串
//              String courseString = "";
//              while (resultSet.next()) {
//                  courseString = resultSet.getString("selected_course");
//              }
              
              //找到课程id
//              Integer spot = ;
//              courseString = courseString.substring(0, spot) + courseString.substring(spot+2);
              
              //更新课程数据,取消
              String sql2 = "update student set selected_course=NULL where sno = " + numSession ;
              statement.executeUpdate(sql2);
              
              //课程余量+1
              String sql3 = "update course set course_Remain=course_Remain+1 where course_Id ="+ course;
              statement.executeUpdate(sql3);
              
              statement.close(); 
              conn.close(); 
            } catch (Exception e) { 
              e.printStackTrace(); 
            }
        
            resp.getWriter().print("{\"data\":\"返回json数据!\"}");
    }

}

管理员操作部分
FindCourseServlet.java 管理员主页展示

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

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 xxm.bean.Course;
import xxm.database.DBOper;

/**
 * 显示课程信息
 * 
 * @author xxm
 *
 */
@WebServlet("/FindCourseServlet")
public class FindCourseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindCourseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

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


     public void process(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    

            try { 
                 
                // 创建Connection连接
                DBOper dao = new DBOper();
                  Connection conn = dao.getConnection(); 
                  // SQL语句
                  String sql = "select * from course"; 
                  // 获取Statement
                  Statement statement =  conn.createStatement(); 
              
                  ResultSet resultSet = statement.executeQuery(sql); 
              
                  List<Course> courseLists = new ArrayList<Course>(); 
                  while (resultSet.next()) { 
                    Course course = new Course();
                    course.setCourseId(resultSet.getInt("course_Id"));
                    course.setCourseName(resultSet.getString("course_Name"));
                    course.setCourseRemain(resultSet.getInt("course_Remain"));
                    course.setCourseTotal(resultSet.getInt("course_Total"));
                    course.setCourseTeacher(resultSet.getString("course_Teacher"));
                    course.setCoursePlace(resultSet.getString("course_Place"));
                    course.setCourseTime(resultSet.getString("course_Time"));
                    course.setCourseTimelength(resultSet.getString("course_Timelength"));
                    
                    courseLists.add(course);
                  } 
                  request.setAttribute("courseList", courseLists);
     
                  
                  resultSet.close(); 
                  statement.close(); 
                  conn.close(); 
              
                } catch (Exception e) { 
                  e.printStackTrace(); 
                } 

            request.getRequestDispatcher("adminCourse.jsp").forward(request, response);
        }
}

CreateCourseServlet.java 添加新的课程

package xxm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

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 xxm.bean.Course;
import xxm.bean.Student;
import xxm.dao.CourseDao;
import xxm.dao.StudentDao;

/**
 * 创建课程,管理员
 * 
 * @author xxm
 *
 */
@WebServlet("/CreateCourseServlet")
public class CreateCourseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateCourseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        String cName = request.getParameter("cName");
        String cTeacher = request.getParameter("cTeacher");
        String cPlace = request.getParameter("cPlace");
        String cTime = request.getParameter("cTime");
        String cLong = request.getParameter("cLong");
        int cTotal = Integer.parseInt(request.getParameter("cTotal"));
        int cRemain = Integer.parseInt(request.getParameter("cRemain"));
        PrintWriter out = response.getWriter();
        
        //设置属性
        Course course = new Course();
        course.setCourseName(cName);
        course.setCourseTeacher(cTeacher);
        course.setCoursePlace(cPlace);
        course.setCourseTime(cTime);
        course.setCourseTimelength(cLong);
        course.setCourseTotal(cTotal);
        course.setCourseRemain(cRemain);
        
        //添加到数据库
        CourseDao dao = new CourseDao();
        try {
            Connection conn = dao.getConnection();
            if(conn!=null) {
                out.print("conn is not null");
            }
             if(dao.addCourse(course)){
                    out.print("添加成功!");
                    System.out.println("成功!");
                    response.sendRedirect("/xxmtest6/FindCourseServlet");
                }
                else{
                    out.print("添加失败!");
                    System.out.println("失败!");
                    response.sendRedirect("/xxmtest6/FindCourseServlet");
                }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

CancelCourse.java 删除课程

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

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 xxm.dao.CourseDao;


/**
 * 删除课程
 * @author Administrator
 *
 */
@WebServlet("/CancelCourse")
public class CancelCourse extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CancelCourse() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
         request.setCharacterEncoding("UTF-8");
        String courseId = request.getParameter("newNo");
         //删除数据
        CourseDao dao = new CourseDao();
       
            try {
                Connection conn = dao.getConnection();
                String sql = "delete from course where course_Id = " + courseId;
                Statement statement = (Statement) conn.createStatement();
                
                if(courseId == null) {
                    courseId = "";
                    response.sendRedirect("/xxmtest6/FindCourseServlet");
                    
                    return;
              }
                response.sendRedirect("/xxmtest6/FindCourseServlet");
                statement.executeUpdate(sql);
                statement.close(); 
                  conn.close(); 
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
            
            }
            
            
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

AdminCourseServlet.java 修改课程信息

package xxm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
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 xxm.bean.Course;
import xxm.dao.CourseDao;

/**
 * 修改课程数据
 * 
 * @author xxm
 *
 */
@WebServlet("/AdminCourseServlet")
public class AdminCourseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminCourseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
         request.setCharacterEncoding("UTF-8");
        int cid = Integer.parseInt(request.getParameter("newNo"));
        String cteach = request.getParameter("ccTeacher");
        String cname = request.getParameter("ccName");
        String cplace = request.getParameter("ccPlace");
        String ctime = request.getParameter("ccTime");
        String clong = request.getParameter("ccLong");
        int ctotal= Integer.parseInt(request.getParameter("ccTotal"));
        int cremain = Integer.parseInt(request.getParameter("ccRemain"));
        System.out.printf("%d,%s,%s,%s,%s,%s,%d,%d\n",cid,cteach,cplace,cname,ctime,clong,ctotal,cremain);
        System.out.println("===========");
        //设置属性
        Course course = new Course();
        course.setCourseId(cid);
        course.setCourseName(cname);
        course.setCourseTeacher(cteach);
        course.setCoursePlace(cplace);
        course.setCourseTime(ctime);
        course.setCourseTimelength(clong);
        course.setCourseTotal(ctotal);
        course.setCourseRemain(cremain);
        
         //修改数据
        CourseDao dao = new CourseDao();
       
            try {
                Connection conn = dao.getConnection();
                if(dao.update(course)) {
                    System.out.println("修改成功!");
                }else {
                    System.out.println("修改失败!");
                }
            
                  conn.close(); 
                  response.sendRedirect("/xxmtest6/FindCourseServlet");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
            
            }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

工程已上传到链接描述


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

IQQcode · 7月5日

博主,请问管理员的账号和密码是什么?

回复

载入中...