资讯专栏INFORMATION COLUMN

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

fuchenxuan / 2620人阅读

摘要:运行结果数据库的个表表表一定要导入数据库用的包,以及在在文件夹中导入数据库包文件目录结构具体代码首页欢迎进入选课系统欢迎进入选课系统学生登录学生注册管理员登录学生登录学生登录学生登录学号密码登录注册返回学生注册注册

运行结果:

数据库的2个表:
course表

student表

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

文件目录结构:

具体代码:
index.jsp 首页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




欢迎进入选课系统


欢迎进入选课 系统

学生登录 学生注册 管理员登录

login.jsp 学生登录

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




学生登录

 

      

学生登录

学号:

密码:

注册 返回

regist.jsp 学生注册

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




注册
    
    


注册页面

学号:
姓名:
密码:
院系:
年级:
班级:
您有账号?点击直接登录

studentIndex.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+"/";
%>
 


  
    
    
    学生选课
    
    
    
        
    
    
  
    
    
    
    
    
  
  
  
  
退出登录

学生选课界面

查找: >


课程名称 剩余量 总数量 任课教师 课程地点 课程时间 课程时长 操作
${courseList.courseName } ${courseList.courseRemain } ${courseList.courseTotal } ${courseList.courseTeacher } ${courseList.coursePlace } ${courseList.courseTime } ${courseList.courseTimelength }





我的选课

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+"/";
%>
 


  
    
    
    学生课程
    
    
    
        
    
    
     
    
    
    
  
  
  
      
        
课程名称 任课教师 课程地点 课程时间 课程时长 操作
${studentCourseList.courseName } ${studentCourseList.courseTeacher } ${studentCourseList.coursePlace } ${studentCourseList.courseTime } ${studentCourseList.courseTimelength }

admin.jsp 管理员登录

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




管理员登录


      

管理员登录

<% String error = (String)session.getAttribute("error"); if(error!=null&&error.length()!=0){ out.println(error); } %>
账号:

密码:

返回

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"%>





    
    
  



课程后台管理


退出登录

选课后台管理

添加课程

编号 课程名 任课老师 上课地点 上课时间 课时 总人数 剩余数 操作
${courseList.courseId} ${courseList.courseName } ${courseList.courseTeacher } ${courseList.coursePlace } ${courseList.courseTime } ${courseList.courseTimelength } ${courseList.courseTotal } ${courseList.courseRemain }

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




check


<% 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");
              }
          }
          %>

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("
重新登陆"); // 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 courseList = new ArrayList(); 
                  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 courseStudentList = new ArrayList(); 
              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 studentCourseList = new ArrayList(); 
              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("

重复选课

"); } 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 courseLists = new ArrayList(); 
                  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 java           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/74714.html

相关文章

  • JavaWeb学生选课ServletJSPJDBC

    摘要:运行结果数据库的个表表表一定要导入数据库用的包,以及在在文件夹中导入数据库包文件目录结构具体代码首页欢迎进入选课系统欢迎进入选课系统学生登录学生注册管理员登录学生登录学生登录学生登录学号密码登录注册返回学生注册注册 运行结果: showImg(https://segmentfault.com/img/bVbthFj); showImg(https://segmentfault.com/...

    zhunjiee 评论0 收藏0
  • 基于javaweb+jsp学生宿舍管理系统

    摘要:基于的学生宿舍管理系统部分代码实现楼栋不能为空编辑表单提交之前进行检查,如果,则不允许提交根据获取值姓名不能为空电话不能为空侧边栏 基于javaweb+jsp的学生...

    DandJ 评论0 收藏0
  • 基于javaweb+jsp学生成绩管理系统

    基于javaweb+jsp的学生成绩管理系统 JavaWeb JavaBean JSP MVC MySQL Tomcat JavaScript idea eclipse MyEclipse Servlet SSM Maven … 部分代码实现JSP let editIndex = layedit.build('LAY_demo_editor'); ...

    番茄西红柿 评论0 收藏2637

发表评论

0条评论

fuchenxuan

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<