58 简单学生管理系统【项目需求、数据库搭建、项目搭建、功能实现(注册功能、登录功能完善验证码功能(Session-会话对象))】

简单学生管理系统

项目需求

项目需求分析

数据库搭建

数据库建表

数据库建表

导数据库sql

了解

导数据库sql

项目搭建

导包,基础页面,实体类,工具类

项目基本搭建.

基础页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>欢迎页面</h1>

  <a href="login.html">登录</a>
  <a href="register.html">注册</a>

</body>
</html>

实体类

public class User {

    private String username;
    private String password;
    private String name;
    private String sex;
    private int age;
    ...
    
}
public class Student extends User{

    private String hobbies;
    ...
}
public class Teacher extends User{

    private int courseId;
	...
}
public class Course {

    private int id;
    private String name;
    ...
}

工具类

/**
 * 数据库工具类
 */
public class DBUtils {

    private static DruidDataSource pool;
    private static ThreadLocal<Connection> local;

    static{
        Properties properties = new Properties();
        try {
            properties.load(DBUtils.class.getClassLoader().getResourceAsStream("DBConfig.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String driverClassName = properties.getProperty("driverClassName");
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        int maxActive = Integer.parseInt(properties.getProperty("maxActive"));

        //初始化数据库连接池
        pool = new DruidDataSource();

        //设置参数
        pool.setDriverClassName(driverClassName);
        pool.setUrl(url);
        pool.setUsername(username);
        pool.setPassword(password);
        pool.setMaxActive(maxActive);

        local = new ThreadLocal<>();
    }

    /**
     * 获取连接对象
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = local.get();//获取当前线程的Connection对象
        if(connection == null){
            connection = pool.getConnection();//获取数据库连接池里的连接对象
            local.set(connection);//将Connection对象添加到local中
        }
        return connection;
    }

    /**
     * 关闭资源
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection != null){
            try {
                if(connection.getAutoCommit()){
                    connection.close();
                    local.set(null);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 开启事务
     */
    public static void startTransaction() throws SQLException {
        Connection connection = getConnection();
        connection.setAutoCommit(false);
    }

    /**
     * 提交事务
     */
    public static void commit() throws SQLException {
        Connection connection = local.get();
        if(connection != null){
            connection.commit();
            connection.close();
            local.set(null);
        }
    }

    public static void rollback() throws SQLException {
        Connection connection = local.get();
        if(connection != null){
            connection.rollback();
            connection.close();
            local.set(null);
        }
    }

    /**
     * 更新数据(添加、删除、修改)
     */
    public static int commonUpdate(String sql,Object... params) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            paramHandler(statement,params);
            int num = statement.executeUpdate();
            return num;
        }finally {
            close(connection,statement,null);
        }
    }

    /**
     * 添加数据 - 主键回填(主键是int类型可以返回)
     */
    public static int commonInsert(String sql,Object... params) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = getConnection();
            statement = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
            paramHandler(statement,params);
            statement.executeUpdate();

            resultSet = statement.getGeneratedKeys();
            int primaryKey = 0;
            if(resultSet.next()){
                primaryKey = resultSet.getInt(1);
            }
            return primaryKey;
        }finally {
            close(connection,statement,resultSet);
        }
    }

    /**
     * 查询多个数据
     */
    public static <T> List<T> commonQueryList(Class<T> clazz,String sql, Object... params) throws SQLException, InstantiationException, IllegalAccessException {

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            paramHandler(statement,params);
            resultSet = statement.executeQuery();

            //获取表数据对象
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取字段个数
            int count = metaData.getColumnCount();

            List<T> list = new ArrayList<>();

            while(resultSet.next()){

                T t = clazz.newInstance();

                //获取字段名及数据
                for (int i = 1; i <= count; i++) {
                    String fieldName = metaData.getColumnName(i);
                    Object fieldVal = resultSet.getObject(fieldName);
                    setField(t,fieldName,fieldVal);
                }
                list.add(t);
            }
            return list;
        } finally {
            DBUtils.close(connection,statement,resultSet);
        }
    }

    /**
     * 查询单个数据
     */
    public static <T> T commonQueryObj(Class<T> clazz,String sql, Object... params) throws SQLException, InstantiationException, IllegalAccessException {

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            paramHandler(statement,params);
            resultSet = statement.executeQuery();

            //获取表数据对象
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取字段个数
            int count = metaData.getColumnCount();

            if(resultSet.next()){

                T t = clazz.newInstance();

                //获取字段名及数据
                for (int i = 1; i <= count; i++) {
                    String fieldName = metaData.getColumnName(i);
                    Object fieldVal = resultSet.getObject(fieldName);
                    setField(t,fieldName,fieldVal);
                }
                return t;
            }
        } finally {
            DBUtils.close(connection,statement,resultSet);
        }
        return null;
    }

    /**
     * 处理statement对象参数数据的处理器
     */
    private static void paramHandler(PreparedStatement statement,Object... params) throws SQLException {
        for (int i = 0; i < params.length; i++) {
            statement.setObject(i+1,params[i]);
        }
    }

    /**
     * 获取当前类及其父类的属性对象
     * @param clazz class对象
     * @param name 属性名
     * @return 属性对象
     */
    private static Field getField(Class<?> clazz,String name){

        for(Class<?> c = clazz;c != null;c = c.getSuperclass()){
            try {
                Field field = c.getDeclaredField(name);
                return field;
            } catch (NoSuchFieldException e) {
            } catch (SecurityException e) {
            }
        }
        return null;
    }

    /**
     * 设置对象中的属性
     * @param obj 对象
     * @param name 属性名
     * @param value 属性值
     */
    private static void setField(Object obj,String name,Object value){

        Field field = getField(obj.getClass(), name);
        if(field != null){
            field.setAccessible(true);
            try {
                field.set(obj, value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

功能实现

1.注册功能(简单实现)

注册的是学生,老师账号一般都由管理员分配
注册成功

html页面
<body>
    <h1>注册页面</h1>

    <form action="RegisterServlet" method="post">

        账号:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        姓名:<input type="text" name="name"/><br/>
        年龄:<input type="text" name="age"/><br/>
        性别:
        <input type="radio" name="sex" value="man" checked="checked"/><input type="radio" name="sex" value="woman"/><br/>
        爱好:
        <input type="checkbox" name="hobbies" value="football"/>足球
        <input type="checkbox" name="hobbies" value="basketball"/>篮球
        <input type="checkbox" name="hobbies" value="shop"/>购物
        <br/>

        <input type="submit" value="注册"/>
        <input type="button" value="返回" onclick="goWelcome()"/>
    </form>

    <script type="text/javascript">
        function goWelcome(){
            window.location = "welcome.html";
        }
    </script>
</body>
RegisterServlet
  1. 设置请求、响应编码格式
  2. 获取请求中的数据
  3. 通过username查询数据库中的学生对象
  4. 通过学生对象进行判断

​ 允许注册,将数据插入到学生表中,利用重定向跳转到登录页面

​ 不允许注册,利用重定向跳转到注册页面

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求、响应编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");
        String[] hobbies = request.getParameterValues("hobbies");

        //通过username查询数据库中的学生对象
        Student student = null;
        try {
            student = DBUtils.commonQueryObj(Student.class, "select * from student where username=?", username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        if(student == null){//允许注册

            //将数据插入到学生表中
            try {
                DBUtils.commonUpdate("insert into student(username,password,name,sex,age,hobbies) values(?,?,?,?,?,?)",username,password,name,sex,age, StringUtils.handleArray(hobbies));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            //利用重定向跳转到登录页面
            response.sendRedirect("login.html");
        }else{//不允许注册

            //利用重定向跳转到注册页面
            response.sendRedirect("register.html");
        }

    }
}
新增工具类handleArray

处理数组,对于学生的爱好是数组

public class StringUtils {

    public static String handleArray(Object[] os){

        StringBuffer sb = new StringBuffer();
		//利用反射实现
        for (int i = 0; i<Array.getLength(os);i++){

            if(i != 0){//不是第一次循环,也就是后面的循环才加逗号,注意先后顺序
                sb.append(",");
            }

            Object element = Array.get(os, i);
            sb.append(element);

        }
        
//        for (Object element : os) {
//            if(sb.length() !=0){
//                sb.append(",");
//            }
//            sb.append(element);
//        }
        return sb.toString();
    }
}

2.登录功能(只对账号、密码做了判断)

登录功能_账号密码角色
登录功能_账号密码角色

html页面

注意设置刷新验证码的函数

<body>
    <h1>登录页面</h1>

    <form action="LoginServlet" method="post">

        账号:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        验证码:<input type="text" name="userCode"/><img src="CodeServlet" width="120px" height="30px" "><a href="#" ">刷新</a><br/>
        记住我:<input type="checkbox" name="rememberMe"/><br/>
        角色:
            <select name="role">
                <option value="student">学生</option>
                <option value="teacher">老师</option>
            </select>
            <br/>
        <input type="submit" value="登录"/>
        <input type="button" value="返回" onclick="goWelcome()"/>
    </form>

    <script type="text/javascript">
        function goWelcome(){
            window.location = "welcome.html";
        }
    </script>
</body>
<body>
  <h1>详情页面</h1>
</body>
LoginServlet
  1. 设置请求、响应编码格式
  2. 获取请求中的数据
  3. 通过username、password查询数据库中的用户对象
  4. 通过用户对象进行判断

​ 登录成功,利用重定向跳转到详情页面

​ 登录失败 – 账号或密码错误,利用重定向跳转到登录页面

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求、响应编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userCode = request.getParameter("userCode");
        String rememberMe = request.getParameter("rememberMe");
        String role = request.getParameter("role");
			//方法1
//        String sysCode = CodeServlet.sysCode;
        	//完善的方法
        //从Session对象中获取系统的验证码
         String sysCode = (String) request.getSession().getAttribute("sysCode");
        //equalsIgnoreCase不区分大小写比较
         if(sysCode.equalsIgnoreCase(userCode)){//验证码正确
			
        	//通过username、password查询数据库中的用户对象
            User user = null;
            try {
                if("student".equals(role)){
                    user = DBUtils.commonQueryObj(Student.class, "select * from student where username=? and password=?", username, password);
                }else if("teacher".equals(role)){
                    user = DBUtils.commonQueryObj(Student.class, "select * from teacher where username=? and password=?", username, password);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            if(user != null){//登录成功
                //利用重定向跳转到详情页面
                response.sendRedirect("index.html");
            }else{//登录失败 -- 账号或密码错误
                //利用重定向跳转到登录页面
                response.sendRedirect("login.html");
            }

          }else{//登录失败 - 验证码错误
              response.sendRedirect("login.html");
         }
    }
}

3.绘制验证码

登录验证码实现
登录验证码实现

CodeServlet

1.创建画布(前提定义宽高)

2.通过画布获取画笔

3.设置背景色 – 填充矩形【利用画笔】

4.设置验证码

​ 创建验证码数字数组、颜色数组

​ 利用随机数进行获取随机下标从而获取随机数字和颜色

​ 设置随机颜色

​ 设置字体(字体,样式,大小)

​ 设置单个验证码

​ StringBffer拼接成验证码

​ 设置干扰线

6.ImageIO将画布以jpg形式的文件传出给客户端

@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
	//方法1:public static String sysCode;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置宽高的变量
        int width = 120;
        int height = 30;

        //创建画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics graphics = image.getGraphics();

        //设置背景色 -- 填充矩形
        graphics.setColor(Color.BLUE);
        graphics.fillRect(0,0,width,height);

        //设置验证码
        Random random = new Random();
        String[] codes = {"A","B","C","D","E","F","G","H","J","K","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
        Color[] colors = {Color.CYAN,Color.BLACK,Color.GREEN,Color.PINK,Color.WHITE,Color.RED,Color.ORANGE};

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < 4; i++) {

            String randomCode = codes[random.nextInt(codes.length)];
            Color randomColor = colors[random.nextInt(colors.length)];

            graphics.setColor(randomColor);//设置随机颜色
            graphics.setFont(new Font("宋体",Font.BOLD,20+random.nextInt(10)));//设置字体(字体,样式,大小)
            graphics.drawString(randomCode,20+i*25,15+random.nextInt(10));//设置单个验证码

            sb.append(randomCode);
        }
		
        //方法1:sysCode = sb.toString();
        
        //完善的方法
        //将系统验证码设置到Session对象中(会话对象)
        HttpSession session = request.getSession();//获取请求里的JSESSIONID(客户端Cookie里的数据),如果没有就创建Session对象,如果有就从Session容器中获取会话对象
        session.setAttribute("sysCode",sb.toString());

        //设置干扰线
        graphics.setColor(Color.YELLOW);
        for (int i = 0; i < 3; i++) {
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));//绘制直线(x1,y1,x2,y2) -> 两点为一线
        }

        
        //将画布以jpg形式的文件传出给客户端
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
}

4.完善验证码功能(Session-会话对象 )*

Session

简单理解
session理解图

注意:浏览器不要禁用Cookie,JSESSIONID就不会保存

登录功能和绘制验证码的中描述未提及的内容

验证码:

方法1:

设置静态成员变量
public static String sysCode;
定义系统验证码
sysCode = sb.toString();

完善:

何时创建Session对象:要用到Session时才会创建

HttpSession session = request.getSession();

将系统验证码设置到Session对象中(会话对象)

session.setAttribute("sysCode",sb.toString());

ctrl+点击查看—底层:注意键和值分别的类型,Object意味着可以存对象

void setAttribute(String var1, Object var2);

添加登录验证码判断

方法1:

String sysCode = CodeServlet.sysCode;

共享变量验证码时登录情况
出现问题:当新开浏览器就会刷新验证码,就以前的验证码就用不了
共享变量验证码时登录情况
没有对应的JESSIONID没有cookie

完善:

从Session对象中获取系统的验证码,类型不一致注意强转

String sysCode = (String) request.getSession().getAttribute("sysCode");

equalsIgnoreCase不区分大小写比较系统验证码和用户验证码,包含了用户对象的判断,意味着登录验证先验证验证码

 if(sysCode.equalsIgnoreCase(userCode)){
 }else{}

获取Session对象解决问题
获取Session对象解决问题
浏览器有cookie中存有对应的JESSIONID有cookie

修改register.html

添加刷新验证码的函数和绑定

    验证码:<input type="text" name="userCode"/><img src="CodeServlet" width="120px" height="30px" onclick="refresh()"><a href="#" onclick="refresh()">刷新</a><br/>

	        <script type="text/javascript">


            img = document.getElementsByTagName("img")[0];
            function refresh(){
                img.src = "CodeServlet?" + new Date();
            }
        </script>
    
  • 15
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值