三、servlet防止sql注入漏洞

一、经常出现漏洞的sql语句 用户名和密码 一起同时查询。

select * from users where username=‘abc’ and passwd=‘123or 1=‘1

二、正确的sql语句先查询数据库根据用户名查询密码,如果存在改用户名,再看密码是否相同。

 "select passwd from users where username='" + name + "' limit 1";

正确代码如下:

        String name = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 加载数据库驱动
            String driver = "com.mysql.jdbc.Driver";
            Class.forName(driver);
            // 得到数据库连接
            String url = "jdbc:mysql://localhost:3306/student";
            String user = "root";
            String password = "tianyejun6";
            conn = DriverManager.getConnection(url, user, password);
            // 创建statement
            statement = conn.createStatement();
            //sql语句
            String sql = "select passwd from users where username='" + name + "' limit 1";
            System.out.println(sql);
            resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
                // 说明用户真实存在
                String passwd = resultSet.getString(1);
                if (passwd.equals(pwd)) {// 说明用户真合法,密码相同
                    HttpSession session = req.getSession(true);
                    // 向session中添加某个属性
                    session.setAttribute("pass", "ok");
                    // 设置超时时间。
                    session.setMaxInactiveInterval(20);

                    resp.sendRedirect("Wel?username=" + name + "&pwd=" + pwd);
                } else {// 说明用户名不存在
                    resp.sendRedirect("Login");
                }
            } else {
                resp.sendRedirect("Login");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect("Login");
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章