简单的学生选课系统——基于Servlet+Ajax

时间:2022-09-28 19:09:27

    以前挖的坑,早晚要往里掉。基础太薄弱,要恶补。在此程序前,我还对Servlet没有一个清晰的概念;一周时间写好此程序之后,对Servlet的理解清晰许多。

    这周一直在恶补Spring,今天正好完成了Spring的每日任务,于是抽空来写一下博客,希望这篇随笔可以帮到各位新手们。

    此文章省略了bean,这个很简单,有需要的可以自行创建。

  一、 简单介绍

    这是一个非常简单的一个程序,功能并不完整,只实现了学生方面的登录和选课操作,但是代码干净、整洁。

    主要模块:1. 登录方面写入了MD5密码加密模块;

         2. 选课方面查询、选中、取消选中操作;

         3. 拦截器。

  二、整体预览

    1. Web项目预览

     其中applicationContext.xml是Druid配置文件。虽然Druid是配好的,但是写着写着莫名用得JDBC。

     简单的学生选课系统——基于Servlet+Ajax

    2. lib文件夹->jar包

      简单的学生选课系统——基于Servlet+Ajax

    3. pages文件夹->jsp页面

     简单的学生选课系统——基于Servlet+Ajax

      4. src文件夹->.java

    简单的学生选课系统——基于Servlet+Ajax

  三、 JSP代码

    1. 登录——login.jsp

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
<body style="text-align: center;">
      <br><br>
      <h3>学生登录</h3>
      <form action="LoginServlet" method="post">
          学号:<input type="text" name="numText">
          <br><br>
          密码:<input type="password" name="passowrdText">
          <br><br>
          <input type="submit" value="登录" name="submit">
      </form>
 </body>
login.jsp

    2. 学生选课主页面——studentIndex.jsp

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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">

    <link rel="stylesheet" type="text/css" href="pages/css/studentIndex.css">
    
    <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script>
    <script type="text/javascript">
        //选择课程
        $(document).ready(
                function() {
                $("input[name='select']").click(function(){
                    var node = $(this);
                    var remainNum = $(this).parent().parent().children("td").eq(1).html();

                    if (!(remainNum == "0")) {
                        $.ajax({
                            url:"http://localhost:8080/StudentSelect/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>
      <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="courseTable">
        <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>
    
    <frameset>
        <iframe style="width: 80%;" id="stuInfoIframe" src="StudentInfoServlet"></iframe>
    </frameset>
  </body>
</html>
studentIndex.jsp

    3. 学生选中的课程信息显示页面——studentInfo.jsp

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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">
    
    <link rel="stylesheet" type="text/css" href="pages/css/studentIndex.css">
    
    <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script>
    <script type="text/javascript">
    //学生课程
    $(document).ready(
        function() {
            $.ajax({
                url:"http://localhost:8080/StudentSelect/StudentInfoServlet",    //请求的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/StudentSelect/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="courseTable">
        <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>
studentInfo.jsp

  四、 Servlet代码

      1. 登录功能的Servlet——LoginServlet.java

     帐号见数据库(下文有显示)

     密码为123    

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.DriverManager;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.util.MD5Util;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @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 { 
              Class.forName("com.mysql.jdbc.Driver"); 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              String username = "root"; 
              String password = "zhao1110"; 
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              Statement statement = (Statement) conn.createStatement();
              
              //根据学号查询
              //获取学号
              req.setCharacterEncoding("UTF-8");
              String keyNum = req.getParameter("numText");
              //String keyNum = new String(req.getParameter("numText").getBytes("iso-8859-1"), "utf-8");
              if(keyNum == null) {
                  keyNum = "";
              }
              
              String sql1 = "select * from student where student_num='" + keyNum + "'"; 
              ResultSet resultSet = statement.executeQuery(sql1);
              
              //获取密码
              req.setCharacterEncoding("UTF-8");
              String keyPassword = req.getParameter("passowrdText");
              //String keyPassword = new String(req.getParameter("passowrdText").getBytes("iso-8859-1"), "utf-8");
              if(keyPassword == null) {
                  keyPassword = "";
              }
              
              //密码加密
              MD5Util md5 = new MD5Util();  
              String newString = "";
              try {
                newString = md5.EncoderByMd5(keyPassword);
              } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
              } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
              }
              
              //比对密码
              String passwordString = "";
              while (resultSet.next()) {
                  passwordString = resultSet.getString("student_password");
              }
              if (passwordString.equals(newString)) {
                  //将学号存入session
                  HttpSession session = req.getSession();
                  session.setAttribute("numSession", keyNum);
                  
                  resp.sendRedirect("/StudentSelect/FindServlet");
              } else {
                  resp.setContentType("text/html;charset=UTF-8");
                  resp.getWriter().write("<script language='javascript'>alert('学号或密码错误!')</script>");
                  resp.setHeader("refresh", "0; url=/StudentSelect");
              }
              
              resultSet.close(); 
              statement.close(); 
              conn.close(); 
          
            } catch (Exception e) { 
              e.printStackTrace(); 
            }
    }
}
LoginServlet.java

      2. 主页显示信息的Servlet——FindServlet.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;

public class FindServlet extends HttpServlet{
    private static final long serialVersionUID = 1L; 
    
    @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 { 
              // 加载数据库驱动,注册到驱动管理器 
              Class.forName("com.mysql.jdbc.Driver"); 
              // 数据库连接字符串 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              // 数据库用户名 
              String username = "root"; 
              // 数据库密码 
              String password = "zhao1110"; 
              // 创建Connection连接
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              // SQL语句
              String sql = "select * from course"; 
              // 获取Statement
              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);

              //后台显示数据
              /*JSONArray jsonArray = JSONArray.fromObject(courseList);
              System.out.println(jsonArray.toString());*/
              
              resultSet.close(); 
              statement.close(); 
              conn.close(); 
          
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
          
            req.getRequestDispatcher("pages/studentIndex.jsp").forward(req, resp);
    }
}
FindServlet.java

     3. 查询功能的Servlet——SearchServlet.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;

public class SearchServlet 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 {
        
        req.setCharacterEncoding("UTF-8");
        String keyString = req.getParameter("search");
        
        if(keyString == null) {
            keyString = "";
        }
          
        try { 
              Class.forName("com.mysql.jdbc.Driver"); 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              String username = "root"; 
              String password = "zhao1110";
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              Statement statement = (Statement) conn.createStatement(); 
          
              String sql = "select * from course where course_name like '%" + keyString + "%' or course_remain like '%" + keyString + "%' "
                      + "or course_total like '%" + keyString + "%' or course_teacher like '%" + keyString + "%'"
                              + " or course_place like '%" + keyString + "%' or course_time like '%" + keyString + "%'"
                                      + " or course_timelength like '%" + keyString + "%'"; 
              
              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);

              //后台显示数据
              /*JSONArray jsonArray = JSONArray.fromObject(courseList);
              System.out.println(jsonArray.toString());*/
              
              resultSet.close(); 
              statement.close(); 
              conn.close(); 
          
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
          
            req.getRequestDispatcher("pages/studentIndex.jsp?search='"+keyString+"'").forward(req, resp);
    }
}
SearchServlet.java

     4. 选中课程时触发的Servlet——RemainAddServlet.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

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 { 
              Class.forName("com.mysql.jdbc.Driver"); 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              String username = "root"; 
              String password = "zhao1110";
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              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 student_selected_course from student where student_num = '" + numSession + "'";
              ResultSet resultSet = statement.executeQuery(sql1);
              String courseString = "";
              while (resultSet.next()) {
                  courseString = resultSet.getString("student_selected_course");
              }
              
              //检查课程选择是否重复
              String[] courseStrings = courseString.split(",");
              for (int i=0; i<courseStrings.length; i++) {
                  if (courseStrings[i].equals(keyString)) {
                      
                      return;
                  }
              }
              courseString = courseString + keyString + ",";
              
              //课程余量-1
              String sql = "update course set course_remain=course_remain-1 where course_id = '"+ keyString + "'";
              statement.executeUpdate(sql);
              
              //修改课程数据
              String sql2 = "update student set student_selected_course='" + courseString + "' where student_num = '" + numSession + "'";
              statement.executeUpdate(sql2);
              
              statement.close(); 
              conn.close(); 
            } catch (Exception e) { 
              e.printStackTrace(); 
            }
        
        resp.getWriter().print("{\"data\":\"返回json数据!\"}"); 
    }
}
RemainAddServlet.java

     5. 取消选中的课程时触发的Servlet——CancelServlet.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class CancelServlet 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 { 
              Class.forName("com.mysql.jdbc.Driver"); 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              String username = "root"; 
              String password = "zhao1110";
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              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 student_selected_course from student where student_num = '" + numSession + "'";
              ResultSet resultSet = statement.executeQuery(sql1);

              //取出课程字符串
              String courseString = "";
              while (resultSet.next()) {
                  courseString = resultSet.getString("student_selected_course");
              }
              
              //找到课程id
              Integer spot = courseString.indexOf(keyString);
              courseString = courseString.substring(0, spot) + courseString.substring(spot+2);
              
              //更新课程数据
              String sql2 = "update student set student_selected_course='" + courseString + "' where student_num = '" + numSession + "'";
              statement.executeUpdate(sql2);
              
              //课程余量+1
              String sql3 = "update course set course_remain=course_remain+1 where course_id = '"+ keyString + "'";
              statement.executeUpdate(sql3);
              
              statement.close(); 
              conn.close(); 
            } catch (Exception e) { 
              e.printStackTrace(); 
            }
        
            resp.getWriter().print("{\"data\":\"返回json数据!\"}");
    }
}
CancelServlet.java

     6. 学生选中的课程信息显示Servlet——StudentInfoServlet.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;
import com.studentselect.bean.Student;

public class StudentInfoServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;
    
    @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 { 
              Class.forName("com.mysql.jdbc.Driver"); 
              String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; 
              String username = "root"; 
              String password = "zhao1110"; 
              Connection conn = (Connection) DriverManager.getConnection(url, username, password); 
              Statement statement = (Statement) conn.createStatement(); 
              
              String numSession = (String) req.getSession().getAttribute("numSession");
              String sql1 = "select * from student where student_num = '" + numSession + "'";
          
              ResultSet resultSet = statement.executeQuery(sql1); 
          
              //判断参数是否为空
              /*req.setCharacterEncoding("UTF-8");
              String keyString = req.getParameter("id");
              
              if(keyString == null) {
                    keyString = "";
                    resp.sendRedirect("FindServlet");
                    
                    return;
              }*/
              
              List<Student> courseStudentList = new ArrayList<Student>(); 
              while (resultSet.next()) { 
                  Student student = new Student();
                  student.setStudentSelectedCourse(resultSet.getString("student_selected_course"));
                  
                  courseStudentList.add(student); 
              } 

              String courseStudentString = courseStudentList.get(0).getStudentSelectedCourse();
              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);
              
              //后台显示数据
              /*JSONArray jsonArray2 = JSONArray.fromObject(studentCourseList);
              System.out.println(jsonArray2.toString());*/
              
              //返回json数据
              /*PrintWriter out = resp.getWriter();
              out.print(jsonArray2.toString());*/
              
              resultSet.close(); 
              statement.close(); 
              conn.close(); 
          
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
           
            resp.setCharacterEncoding("UTF-8");
            req.getRequestDispatcher("pages/studentInfo.jsp").forward(req, resp);
    }
}
StudentInfoServlet.java

     7. MD5密码加密——MD5Util.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.yangcheboshi.util.weibo.http.BASE64Encoder;

public class MD5Util {
      /**利用MD5进行加密*/
      public String EncoderByMd5(String string)
              throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        
        //加密后的字符串
        @SuppressWarnings("static-access")
        String newString = base64en.encode(md5.digest(string.getBytes("utf-8")));
        
        return newString;
      }
       
      //判断用户密码是否正确
      public boolean checkpassword(String newpassword,String initialpassword)
              throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if(EncoderByMd5(newpassword).equals(initialpassword))
          return true;
        else
          return false;
      }
}
MD5Util.java

  五、 filter拦截器代码

     1. 登录拦截——LoginFilter.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class LoginFilter implements Filter{

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("------login过滤器初始化------");
    }
    
    @Override
    public void destroy() {
        System.out.println("------login过滤器销毁------");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
            
            //对request和response进行一些预处理
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
             
            HttpServletRequest req = (HttpServletRequest)request;
            Object numSession = req.getSession().getAttribute("numSession");
            String url = req.getRequestURI();
            if (numSession != null || (url.endsWith("pages/login.jsp") || url.endsWith("LoginServlet"))) {
                chain.doFilter(request, response);  //让目标资源执行,放行
                
                return;
            } else {
                req.getRequestDispatcher("/").forward(request, response);
            }
    }
}
LoginFilter.java

     2. JSP页面拦截——JSPFilter.java

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
package com.studentselect.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class JSPFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("------.jsp过滤器初始化------");
    }
    
    @Override
    public void destroy() {
        System.out.println("------.jsp过滤器销毁------");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        
        //对request和response进行一些预处理
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        HttpServletRequest req = (HttpServletRequest)request;
        String url = req.getRequestURI();
        if (!(url.endsWith(".jsp"))) {
            chain.doFilter(request, response);  //让目标资源执行,放行
            
            return;
        } else {
            req.getRequestDispatcher("/").forward(request, response);
        }
    }
}
JSPFilter

  六、 web.xml配置

      简单的学生选课系统——基于Servlet+Ajax简单的学生选课系统——基于Servlet+Ajax
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>StudentSelect</display-name>
  <welcome-file-list>
    <welcome-file>pages/login.jsp</welcome-file>
    <welcome-file>pages/default.jsp</welcome-file>
  </welcome-file-list>
  
  <!--配置过滤器-->
  <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.studentselect.filter.LoginFilter</filter-class>
  </filter>
  <!--映射过滤器-->
  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <!--/*表示拦截所有的请求 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <filter>
    <filter-name>JSPFilter</filter-name>
    <filter-class>com.studentselect.filter.JSPFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>JSPFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 课程信息 -->
  <servlet>
    <!-- 声明Servlet对象 -->
    <servlet-name>FindServlet</servlet-name>
    <!-- 上面一句指定Servlet对象的名称 -->
    <servlet-class>com.studentselect.servlet.FindServlet</servlet-class>
    <!-- 上面一句指定Servlet对象的完整位置,包含包名和类名 -->
  </servlet>
  <servlet-mapping>
    <!-- 映射Servlet -->
    <servlet-name>FindServlet</servlet-name>
    <!--<servlet-name>与上面<Servlet>标签的<servlet-name>元素相对应,不可以随便起名  -->
    <url-pattern>/FindServlet</url-pattern>
    <!-- 上面一句话用于映射访问URL -->
  </servlet-mapping>

  <!-- 学生课程 -->
  <servlet>
      <servlet-name>StudentInfoServlet</servlet-name>
      <servlet-class>com.studentselect.servlet.StudentInfoServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>StudentInfoServlet</servlet-name>
      <url-pattern>/StudentInfoServlet</url-pattern>
  </servlet-mapping>

  <!-- 搜索课程 -->
  <servlet>
      <servlet-name>SearchServlet</servlet-name>
      <servlet-class>com.studentselect.servlet.SearchServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>SearchServlet</servlet-name>
      <url-pattern>/SearchServlet</url-pattern>
  </servlet-mapping>
  
  <!-- 课程余量、添加课程 -->
  <servlet>
      <servlet-name>RemainAddServlet</servlet-name>
      <servlet-class>com.studentselect.servlet.RemainAddServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>RemainAddServlet</servlet-name>
      <url-pattern>/RemainAddServlet</url-pattern>
  </servlet-mapping>
  
  <!-- 学生取消课程 -->
  <servlet>
      <servlet-name>CancelServlet</servlet-name>
      <servlet-class>com.studentselect.servlet.CancelServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>CancelServlet</servlet-name>
      <url-pattern>/CancelServlet</url-pattern>
  </servlet-mapping>
  
  <!-- 学生登录 -->
  <servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>com.studentselect.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>LoginServlet</servlet-name>
      <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  

  <!-- 连接池 启用Web监控统计功能   start-->
  <filter>
      <filter-name>DruidWebStatFilter</filter-name>
      <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
      <init-param>
          <param-name>exclusions</param-name>
          <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>DruidWebStatFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置 Druid 监控信息显示页面 -->  
  <servlet>  
    <servlet-name>DruidStatView</servlet-name>  
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
    <init-param>  
        <!-- 允许清空统计数据 -->  
        <param-name>resetEnable</param-name>  
        <param-value>true</param-value>  
    </init-param>  
    <init-param>  
        <!-- 用户名 -->  
        <param-name>loginUsername</param-name>  
        <param-value>overfly</param-value>  
    </init-param>  
    <init-param>  
        <!-- 密码 -->  
        <param-name>loginPassword</param-name>  
        <param-value>zhao1110</param-value>  
    </init-param>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>DruidStatView</servlet-name>  
    <url-pattern>/druid/*</url-pattern>  
  </servlet-mapping>
  <!-- 连接池 启用Web监控统计功能   end-->
</web-app>
Web.xml

  七、 表结构

  简单的学生选课系统——基于Servlet+Ajax

简单的学生选课系统——基于Servlet+Ajax

简单的学生选课系统——基于Servlet+Ajax

  八、 程序运行图

简单的学生选课系统——基于Servlet+Ajax

 

  九、简单说说

     1. filter拦截器我是用来拦截未登录就访问内容和地址栏URL直接访问Servlet,我将用户的登录信息存在Session中,用来判断用户是否已经登录。

     2. 密码加密是用户将密码输入提交后,MD5Util对密码进行加密操作,转换成一系列字符编码,然后用转换后的字符编码与数据库进行比对。

      虽然MD5是不可逆的,但是我认为依旧不安全,但是能在一定程度上简单防止它人盗取数据库获取用户信息这种黑客行为。