国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

JavaWeb學生選課(Servlet、JSP、JDBC)

zhunjiee / 1334人閱讀

摘要:運行結果數據庫的個表表表一定要導入數據庫用的包,以及在在文件夾中導入數據庫包文件目錄結構具體代碼首頁歡迎進入選課系統歡迎進入選課系統學生登錄學生注冊管理員登錄學生登錄學生登錄學生登錄學號密碼登錄注冊返回學生注冊注冊

運行結果:

數據庫的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           
               
                                           
                       
                 

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/104247.html

相關文章

  • JavaWeb學生選課ServletJSPJDBC

    摘要:運行結果數據庫的個表表表一定要導入數據庫用的包,以及在在文件夾中導入數據庫包文件目錄結構具體代碼首頁歡迎進入選課系統歡迎進入選課系統學生登錄學生注冊管理員登錄學生登錄學生登錄學生登錄學號密碼登錄注冊返回學生注冊注冊 運行結果: showImg(https://segmentfault.com/img/bVbthFj); showImg(https://segmentfault.com/...

    fuchenxuan 評論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條評論

zhunjiee

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<