为了账号安全,请及时绑定邮箱和手机立即绑定

JSP+Servlet培训班作业管理系统[19] -完结篇之源代码

标签:
Java Html/CSS

本篇是上篇介绍所有功能的相关源代码,按一定组织顺序贴出如下,在注释中已经添加了比较明显的解释:

/**
 * util包:工具包
 * Constant类:保存常量信息的类
 */
package util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
public class Constant {
    //roleMenu用于保存角色及对应的菜单信息
    public static HashMap<String,String[][]> RoleMenu=new HashMap<String,String[][]>();
    //pageSize用于保存不同实体列表页面显示实体个数信息(每页多少个)
    public static HashMap<String,Integer> PageSize=new HashMap<String,Integer>();
    //JobScore用于保存不同的job_score状态
    public static HashMap<String,String> JobScore=new HashMap<String,String>();
    //使用static代码块对roleMenu进行初始化
    static{
        //注意,二位数组中的每一组表示一个菜单的信息,又通过map建立了角色名和菜单直接的对应关系
        RoleMenu.put("校长", new String[][]{
                {"人员管理","view","User"},//由具体的地址,变为抽象的参数
                {"课程查看","view","Course"}
        });
        RoleMenu.put("教师", new String[][]{
                {"课程管理","view","Course"},
                {"批阅作业","view","Job"}
        });
        RoleMenu.put("学生", new String[][]{
                {"做作业","view","Job"},
                {"选课","view","Course"}
        });
        //初始化页面列表个数
        PageSize.put("Course", 5);
        PageSize.put("Job", 5);
        PageSize.put("Lesson", 5);
        PageSize.put("Role", 5);
        PageSize.put("User", 5);
        PageSize.put("Work", 5);
        //-2作业未提交 -1已提交未阅 0优秀 1良好 2合格 3不合格
        JobScore.put("-2", "作业未提交");
        JobScore.put("-1", "已提交未阅");
        JobScore.put("0", "优秀");
        JobScore.put("1", "良好");
        JobScore.put("2", "合格");
        JobScore.put("3", "不合格");
    }   
    public static String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateValue = sdf.format(now);
        return dateValue;
    }
}
/**
 * exception包:包含自定义异常类的包
 */
package exception;
import java.util.Date;
public class MyException extends Exception{
    private Date time;//记录异常发生时间
    private String message;//原始异常信息,给程序员看,记录日志
    private String info;//自定义信息,给用户看
    public MyException(){
        super();
    }
    public MyException(Date time,String msg,String info){
        super();
        this.time=time;
        this.message=msg;
        this.info=info;
        System.out.println("====异常出现了====");
        System.out.println("msg:"+msg);
        System.out.println("info:"+info);
        System.out.println("====异常显示了====");
    }
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}
/**
 * database包:保存数据库操作基类的包,包含MySQLPool和MySQLHandler类
 * MySQLPool:数据库连接池类
 * MySQLHandler:使用数据库连接池的mysql数据库操作类
 */
package database;
import java.sql.*;
import java.util.Date;
import java.util.LinkedList;
import exception.MyException;
/**
 * MySQL数据库自定义连接池
 * @author 猫哥
 * @date 2017.2.6修改
 */
public class MySQLPool {
    private static LinkedList<Connection> pool = new LinkedList<Connection>(); 
    private static int maxCount=1;//最大连接数
    static{//初始化
        for(int i=0;i<maxCount;i++){
            MySQLHandler handler=new MySQLHandler();
            Connection connection = handler.buildConnection();
            pool.add(connection);
        }    
    }
    public static Connection getConnecton() throws MyException{
        if(pool.size()==0)//分配完了
        {
            throw new MyException(new Date(),"数据库连接池资源短缺,无连接可分配","数据库连接错误");
        }
        else{
            return pool.remove(0);//删除第一个对象并返回
        }
    }
    public static void release(Connection connection){//使用完的归还给池子
        pool.add(connection);
    }
}
package database;
import java.sql.*;//导入数据库相关类库
import java.util.ArrayList;
import java.util.Date;
import exception.MyException;
/**
 * MysqlHandler MySQL数据库管理类,使用数据库连接池
 * @author 猫哥
 * @date 2016.1.9
 * @modify 2016.2.6 MysqlHandler-MySQLHandler,use MyException
 */
public class MySQLHandler{   
    //依然是那熟悉的三个必备参数
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    //建立数据库连接,此处仅用于提供原始连接,供放入池中使用
    public Connection buildConnection() {        
         String driver = "com.mysql.jdbc.Driver";
         String url = "jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=utf-8";//数据库连接字符串
         String user = "root";
         String password = "Pass1234";
         try{   
            Class.forName(driver);//加载驱动程序
            conn=DriverManager.getConnection(url,user,password);
         }
         catch(Exception ex){
            //暂时不处理(未throw),加上日志模块后记在日志里
            new MyException(new Date(),ex.getMessage(),"数据库连接建立异常");
         }
        return conn;
    }
    //操作1,“增删改查”中,增、删、改都是执行sql语句,无需返回ResultSet结果集,所以设置为一个方法
    public int execute(String sql) throws MyException{
        try {
            if(conn==null)//未分配
                conn=MySQLPool.getConnecton();//用时从池中取,很爽快
            stmt=conn.createStatement();
            int affectedCount = stmt.executeUpdate(sql);//此处真正执行stmt定义的操作
            return affectedCount;//这个是收到影响的行数
        }
        catch (Exception ex) {
            throw new MyException(new Date(),ex.getMessage(),"数据库连接错误");
        }
    }
    //操作2,如果是查询,需返回结果集
    public ResultSet query(String sql)throws Exception{
        try{
            if(conn==null)//未分配
                conn=MySQLPool.getConnecton();//用时从池中取,很爽快
            stmt=conn.createStatement();
            rs = stmt.executeQuery(sql);//执行pstmt中定义的查询
            return rs;//将结果集返回 
        }
         catch (Exception ex) {
            throw new MyException(new Date(),ex.getMessage(),"数据库连接错误");
         }
    }
    //操作3,释放资源
    public void sayGoodbye(){
        if(rs!=null){//关闭结果集,这个不关闭也浪费
            try {
                rs.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if(stmt!=null){//关闭Statement,不要浪费
            try {
                stmt.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //此处注意,conn在池中管理,不用关闭,用完回归连接池继续使用
        MySQLPool.release(conn);
    }

    public Boolean doTransaction(ArrayList<String> sqlList) throws MyException{
        try{
            if(conn==null)//未分配
                conn=MySQLPool.getConnecton();//用时从池中取,很爽快
            //开始事务(不让mysql自动提交了,程序员做主何时一起提交或者还是回退)
            conn.setAutoCommit(false);
            for(String sql:sqlList){
                stmt=conn.createStatement();
                stmt.executeUpdate(sql);
            }
            //此处提交事务,如果中间所有执行语句没错,则全部一起执行,如果有错跳到catch
            conn.commit();
            return true;
        }
        catch (Exception ex) {
            try {
                //如果有错误,则回归到所有sql未执行状态
                conn.rollback();
            } catch (SQLException sqlEx) {
                new MyException(new Date(),sqlEx.getMessage(),"事务回滚错误");
            }  
            throw new MyException(new Date(),ex.getMessage(),"数据库执行错误");
        }finally{
            MySQLPool.release(conn);//用完归还
        }
    }
}
/**
 * entity包:包含所有实体类的包
 * 实体类计有:Course Job Lesson Role User Work
 */
package entity;
public class Course{//对应system_course
    private int courseId;
    private String courseName;
    private User courseUser;
    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 User getCourseUser() {
        return courseUser;
    }
    public void setCourseUser(User courseUser) {
        this.courseUser = courseUser;
    }
}
package entity;
public class Job{//对应work_job
    private int jobId;  
    private String jobTime;
    private String jobContent;
    private String jobScore;
    private Work jobWork;
    private User jobUser;
    public int getJobId() {
        return jobId;
    }
    public void setJobId(int jobId) {
        this.jobId = jobId;
    }
    public String getJobTime() {
        return jobTime;
    }
    public void setJobTime(String jobTime) {
        this.jobTime = jobTime;
    }
    public String getJobContent() {
        return jobContent;
    }
    public void setJobContent(String jobContent) {
        this.jobContent = jobContent;
    }
    public String getJobScore() {
        return jobScore;
    }
    public void setJobScore(String jobScore) {
        this.jobScore = jobScore;
    }
    public Work getJobWork() {
        return jobWork;
    }
    public void setJobWork(Work jobWork) {
        this.jobWork = jobWork;
    }
    public User getJobUser() {
        return jobUser;
    }
    public void setJobUser(User jobUser) {
        this.jobUser = jobUser;
    }
}
package entity;
//学生选课
public class Lesson {
    private int lessonId;
    private User lessonUser;
    private Course lessonCourse;
    public int getLessonId() {
        return lessonId;
    }
    public void setLessonId(int lessonId) {
        this.lessonId = lessonId;
    }
    public User getLessonUser() {
        return lessonUser;
    }
    public void setLessonUser(User lessonUser) {
        this.lessonUser = lessonUser;
    }
    public Course getLessonCourse() {
        return lessonCourse;
    }
    public void setLessonCourse(Course lessonCourse) {
        this.lessonCourse = lessonCourse;
    }
}
package entity;
public class Role{//对应system_role
    private int roleId;
    private String roleName;
    public int getRoleId() {
        return roleId;
    }
    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}
package entity;
public class User{//对应system_user
    private int userId;
    private String userName;
    private String userPassword;
    private Role userRole;  
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    public Role getUserRole() {
        return userRole;
    }
    public void setUserRole(Role userRole) {
        this.userRole = userRole;
    }
}
package entity;
public class Work {//对应system_work
    private int workId;
    private String workTitle;
    private String workTime;
    private Course workCourse;
    public int getWorkId() {
        return workId;
    }
    public void setWorkId(int workId) {
        this.workId = workId;
    }
    public String getWorkTitle() {
        return workTitle;
    }
    public void setWorkTitle(String workTitle) {
        this.workTitle = workTitle;
    }
    public String getWorkTime() {
        return workTime;
    }
    public void setWorkTime(String workTime) {
        this.workTime = workTime;
    }
    public Course getWorkCourse() {
        return workCourse;
    }
    public void setWorkCourse(Course workCourse) {
        this.workCourse = workCourse;
    }
}
/**
 * operation包:保存数据库实体对象操作类的包
 * 计有CourseOperation JobOperation LessonOperation RoleOperation UserOperation WorkOperation
 * 因代码量太大且逻辑相近,此处只展示了CourseOperation
 */
package operation;
import inter.IOperation;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import database.MySQLHandler;
import entity.*;
import exception.MyException;
public class CourseOperation implements IOperation{
    //学生选课使用begin
    public int selectCountByStudentId(int studentId) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        int re=0;
        try {
            //此处不要写select *,因为数据库将*转换为该表所有列名肯定需要浪费时间
            rs=hand.query("select count(course_id) as count from system_course where course_id"
                    +" not in(select lesson_course from student_lesson l where l.lesson_user='"+studentId+"')");
            while(rs.next()){
                re=rs.getInt("count");
            }
            return re;
        } catch (Exception ex) {
            //对于数据库操作层面的异常,此时不予以向外抛出,记录在日志中分析即可
            //在设计的时候就要明确,什么类型异常要外抛,什么异常不抛出只记录
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectCountByStudentId异常");
            return 0;//注意null和new Course()并不同!
        }finally{
            hand.sayGoodbye();
        }
    }
    public List selectPageByStudentId(int offset, int size,int studentId) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        ArrayList<Course> list=new ArrayList<Course>();//返回值
        try {
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +" system_Course c,system_user u where c.Course_user=u.user_id "
                    +" and c.course_id not in (select lesson_course from student_lesson l where l.lesson_user='"+studentId+"')"
                    +" order by c.Course_id limit "+offset+","+size);
            while(rs.next()){ 
                Course one=new Course();//返回值中的一个
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
                list.add(one);//添加到列表
            }
            return list;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectPageByStudentId异常");
            return null;
        }finally{
            hand.sayGoodbye();
        }
    }
    //学生选课使用end
    @Override
    public int selectCount() {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        int re=0;
        try {
            //此处不要写select *,因为数据库将*转换为该表所有列名肯定需要浪费时间
            rs=hand.query("select count(course_id) as count from system_course");
            while(rs.next()){
                re=rs.getInt("count");
            }
            return re;
        } catch (Exception ex) {
            //对于数据库操作层面的异常,此时不予以向外抛出,记录在日志中分析即可
            //在设计的时候就要明确,什么类型异常要外抛,什么异常不抛出只记录
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectCount异常");
            return 0;//注意null和new Course()并不同!
        }finally{
            hand.sayGoodbye();
        }
    }
    public int selectCountByUserId(int userId) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        int re=0;
        try {
            //此处不要写select *,因为数据库将*转换为该表所有列名肯定需要浪费时间
            rs=hand.query("select count(course_id) as count from system_course where course_user='"+userId+"'");
            while(rs.next()){
                re=rs.getInt("count");
            }
            return re;
        } catch (Exception ex) {
            //对于数据库操作层面的异常,此时不予以向外抛出,记录在日志中分析即可
            //在设计的时候就要明确,什么类型异常要外抛,什么异常不抛出只记录
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectCount异常");
            return 0;//注意null和new Course()并不同!
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public Object selectById(int id) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        Course one=new Course();//如果查询内容为空,则通过one.getCourseId()==0来判断即可
        try {
            //此处不要写select *,因为数据库将*转换为该表所有列名肯定需要浪费时间
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +"system_Course c,system_user u where c.Course_id='"+id+"' and c.Course_user=u.user_id");
            while(rs.next()){
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
            }
            return one;
        } catch (Exception ex) {
            //对于数据库操作层面的异常,此时不予以向外抛出,记录在日志中分析即可
            //在设计的时候就要明确,什么类型异常要外抛,什么异常不抛出只记录
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectById异常");
            return null;//注意null和new Course()并不同!
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public List selectAll() {//注意返回值null和list.size()==0的区别
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        ArrayList<Course> list=new ArrayList<Course>();//返回值
        try {
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +"system_Course c,system_user u where c.Course_user=u.user_id");
            while(rs.next()){
                Course one=new Course();//返回值中的一个
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
                list.add(one);//添加到列表
            }
            return list;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectAll异常");
            return null;
        }finally{
            hand.sayGoodbye();
        }
    }
    public List selectAllByUserId(int userId) {//注意返回值null和list.size()==0的区别
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        ArrayList<Course> list=new ArrayList<Course>();//返回值
        try {
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +"system_Course c,system_user u where c.Course_user=u.user_id"
                    +" and u.user_id='"+userId+"'");
            while(rs.next()){
                Course one=new Course();//返回值中的一个
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
                list.add(one);//添加到列表
            }
            return list;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectAll异常");
            return null;
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public List selectPage(int offset, int size) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        ArrayList<Course> list=new ArrayList<Course>();//返回值
        try {
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +" system_Course c,system_user u where c.Course_user=u.user_id "
                    +" order by c.Course_id limit "+offset+","+size);
            while(rs.next()){ 
                Course one=new Course();//返回值中的一个
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
                list.add(one);//添加到列表
            }
            return list;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectPage异常");
            return null;
        }finally{
            hand.sayGoodbye();
        }
    }
    public List selectPageByUserId(int offset, int size,int userId) {
        MySQLHandler hand=new MySQLHandler();
        ResultSet rs=null;
        ArrayList<Course> list=new ArrayList<Course>();//返回值
        try {
            rs=hand.query("select Course_id,Course_name,user_id,user_name from "
                    +" system_Course c,system_user u where c.Course_user=u.user_id and user_id='"+userId+"'"
                    +" order by c.Course_id limit "+offset+","+size);
            while(rs.next()){ 
                Course one=new Course();//返回值中的一个
                one.setCourseId(rs.getInt("Course_id"));
                one.setCourseName(rs.getString("Course_name"));     
                User user=new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("user_name"));
                one.setCourseUser(user);
                list.add(one);//添加到列表
            }
            return list;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.selectPage异常");
            return null;
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public int add(Object obj) {
        Course one=(Course)obj;
        MySQLHandler hand=new MySQLHandler();
        try {
            int re=hand.execute("insert into system_Course(Course_name,Course_user)"
                    +" values('"+one.getCourseName()+"','"+one.getCourseUser().getUserId()+"')");
            return re;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.add异常");
            return 0;
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public int deleteById(int id) {
        MySQLHandler hand=new MySQLHandler();
        try {
            int re=hand.execute("delete from system_Course where Course_id='"+id+"'");
            return re;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.deleteById异常");
            return 0;
        }finally{
            hand.sayGoodbye();
        }
    }
    @Override
    public int update(Object obj) {
        Course one=(Course)obj;
        MySQLHandler hand=new MySQLHandler();
        try {
            int re=hand.execute("update system_Course set Course_name='"+one.getCourseName()
                    +"',Course_user='"+one.getCourseUser().getUserId()
                    +"' where Course_id='"+one.getCourseId()+"'");
            return re;
        } catch (Exception ex) {
            new MyException(new Date(),ex.getMessage(),"CourseOperation.update异常");
            return 0;
        }finally{
            hand.sayGoodbye();
        }
    }
}
点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
软件工程师
手记
粉丝
1.5万
获赞与收藏
1523

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消