コード例 #1
0
ファイル: login.java プロジェクト: nitt006/project_final
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
 protected collegeTable getCollege(String id, Connection con) throws SQLException {
   try {
     ResultSet rs = null;
     Statement statement = con.createStatement();
     rs =
         statement.executeQuery(
             "SELECT * FROM "
                 + TABLECOLLEGES
                 + " WHERE "
                 + collegeTable.ID
                 + " = "
                 + id
                 + " LIMIT 1");
     // if found
     if (rs.next()) {
       collegeTable table = new collegeTable();
       table.setID(id);
       table.setShort(rs.getString(collegeTable.SHORTNAME));
       table.setFull(rs.getString(collegeTable.FULLNAME));
       return table;
     } else {
       return null; // not found
     }
   } catch (Exception e) {
     log.writeException(e.getMessage());
     throw new SQLException(e.getMessage());
   }
 } // end getCollege
コード例 #3
0
ファイル: JsfLogin.java プロジェクト: radu-m/ssase13
  public String checkValidLogin(String myUserName, String myPW) {

    try {
      Class.forName(javaSQLDriverPath);
      Connection conn =
          (Connection) DriverManager.getConnection(ConnectionPath, ConnectionUser, ConnectionPW);
      Statement st = conn.createStatement();
      String query = "Select * from User";

      ResultSet rs = st.executeQuery(query);
      while (rs.next()) {
        // return rs.getString("Username");
        if (myUserName.equals(rs.getString("Username"))) {
          if (myPW.equals(rs.getString("Password"))) {
            setUserVariables(myUserName);
            return "success";
          } else {
            return "wrongPassword";
          }
        }
      }

      rs.close();
      st.close();
      conn.close();

      return "userNotFound";
    } catch (Exception e) {

      return e.getMessage();
    }
  }
コード例 #4
0
ファイル: project3.java プロジェクト: emadonop/ergasia3
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */
  private void goodB2G1() throws Throwable {
    String data;
    if (IO.staticTrue) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.staticFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String data_copy;
    {
      String data;

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";

      data_copy = data;
    }
    {
      String data = data_copy;

      Logger log2 = Logger.getLogger("local-logger");

      Connection conn_tmp2 = null;
      Statement sqlstatement = null;
      ResultSet sqlrs = null;

      try {
        conn_tmp2 = IO.getDBConnection();
        sqlstatement = conn_tmp2.createStatement();

        /* POTENTIAL FLAW: take user input and place into dynamic sql query */
        sqlrs = sqlstatement.executeQuery("select * from users where name='" + data + "'");

        IO.writeString(sqlrs.toString());
      } catch (SQLException se) {
        log2.warning("Error getting database connection");
      } finally {
        try {
          if (sqlrs != null) {
            sqlrs.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlrs");
        } finally {
          try {
            if (sqlstatement != null) {
              sqlstatement.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing sqlstatement");
          } finally {
            try {
              if (conn_tmp2 != null) {
                conn_tmp2.close();
              }
            } catch (SQLException e) {
              log2.warning("Error closing conn_tmp2");
            }
          }
        }
      }
    }
  }
コード例 #7
0
ファイル: UserUtils.java プロジェクト: vagisha/msdapl
  /**
   * Determine whether or a not a User with the supplied researcherID exists
   *
   * @param username The researcherID to test
   * @return true if the user exists, false if not
   * @throws SQLException if a database error was encountered
   */
  public static boolean userExists(int researcherID) throws SQLException {
    boolean returnVal = false;

    // Get our connection to the database.
    Connection conn = DBConnectionManager.getConnection("yrc");
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
      stmt = conn.prepareStatement("SELECT researcherID FROM tblUsers WHERE researcherID = ?");
      stmt.setInt(1, researcherID);

      rs = stmt.executeQuery();

      // No rows returned.
      if (!rs.next()) {
        returnVal = false;
      } else {
        returnVal = true;
      }

      rs.close();
      rs = null;

      stmt.close();
      stmt = null;

      conn.close();
      conn = null;
    } finally {

      // Always make sure result sets and statements are closed,
      // and the connection is returned to the pool
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {;
        }
        rs = null;
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (SQLException e) {;
        }
        stmt = null;
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {;
        }
        conn = null;
      }
    }

    return returnVal;
  }
コード例 #8
0
 private void printOutLogs(Connection connection, PrintWriter out) throws SQLException {
   Statement select = connection.createStatement();
   ResultSet result = select.executeQuery("SELECT * FROM LOGGING ORDER BY DATE ASC");
   while (result.next()) {
     Timestamp date = result.getTimestamp("DATE");
     String ip = result.getString("IP");
     String url = result.getString("URL");
     out.println(date + "\t\t" + ip + "\t\t" + url);
   }
 }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String dataCopy;
    {
      String data;

      /* FIX: Use a hardcoded string */
      data = "foo";

      dataCopy = data;
    }
    {
      String data = dataCopy;

      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();

        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
コード例 #10
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      System.out.println("Enrollno: 130050131049");
      // STEP 2: Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      // STEP 2: Executing query
      String sql = "SELECT * FROM logindetails WHERE name = ?";
      pstmt = conn.prepareStatement(sql);
      pstmt.setString(1, "Krut");

      ResultSet rs = pstmt.executeQuery();
      out.print("| <b>Name</b>| ");
      out.print("<b>Password</b>| ");
      out.println("</br>\n-------------------------------</br>");
      while (rs.next()) {
        out.println();
        out.print("| " + rs.getString(1));
        out.print("| " + rs.getString(2) + "|");
        out.println("</br>");
      }

    } catch (SQLException se) {
      // Handle errors for JDBC
      se.printStackTrace();
    } catch (Exception e) {
      // Handle errors for Class.forName
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (pstmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
  }
  /* goodG2B1() - use goodsource and badsink by changing first IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (IO.STATIC_FINAL_FIVE == 5) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");
        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  public void bad() throws Throwable {
    String data;
    if (IO.staticTrue) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.staticTrue) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");
        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
コード例 #13
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      String email = request.getParameter("email_id");

      String number = "";
      boolean exists = false;
      String user_name = "";
      int user_id = -1;
      String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setString(1, email);
      ResultSet rs1 = prep1.executeQuery();
      if (rs1.next()) {
        exists = true;
        user_id = rs1.getInt("USER_ID");
        user_name = rs1.getString("NAME");
        number = rs1.getString("PHONE_NUMBER");
      }
      int verification = 0;
      JSONObject data = new JSONObject();
      if (exists) {
        verification = (int) (Math.random() * 9535641 % 999999);
        System.out.println("Number " + number + "\nVerification: " + verification);
        SMSProvider.sendSMS(
            number, "Your One Time Verification Code for PeopleConnect Is " + verification);
      }

      data.put("user_name", user_name);
      data.put("user_id", user_id);
      data.put("verification_code", "" + verification);
      data.put("phone_number", number);

      String toSend = data.toJSONString();
      out.print(toSend);
      System.out.println(toSend);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
コード例 #14
0
ファイル: bookList.java プロジェクト: jhernantes/claseIngSw
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter toClient = res.getWriter();
    toClient.println("<!DOCTYPE HTML>");
    toClient.println("<html>");
    toClient.println("<head><title>Books</title></head>");
    toClient.println("<body>");
    toClient.println("<a href=\"index.html\">Home</A>");
    toClient.println("<h2>List of books</h2>");

    HttpSession session = req.getSession(false);
    if (session != null) {
      String name = (String) session.getAttribute("name");
      if (name != null) {
        toClient.println("<h2>name: " + name + "</h2>");
      }
    }

    toClient.print("<form action=\"bookOpinion\" method=GET>");
    toClient.println("<table border='1'>");

    String sql = "Select code, title, author FROM books";
    System.out.println(sql);
    try {
      Statement statement = connection.createStatement();
      ResultSet result = statement.executeQuery(sql);
      while (result.next()) {
        toClient.println("<tr>");
        String codeStr = result.getString("code");
        toClient.println(
            "<td><input type=\"radio\" name=\"book" + "\" value=\"" + codeStr + "\"></td>");
        toClient.println("<td>" + codeStr + "</td>");
        toClient.println("<td>" + result.getString("title") + "</td>");
        toClient.println("<td>" + result.getString("author") + "</td>");
        toClient.println("</tr>");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("Resulset: " + sql + " Exception: " + e);
    }
    toClient.println("</table>");
    toClient.println("<textarea rows=\"8\" cols=\"60\" name=\"comment\"></textarea><BR>");
    toClient.println("<input type=submit>");
    toClient.println("</form>");
    toClient.println("</body>");
    toClient.println("</html>");
    toClient.close();
  }
  /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
  public void goodB2G1Sink(String data) throws Throwable {
    if (CWE89_SQL_Injection__connect_tcp_executeQuery_22a.goodB2G1PublicStatic) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  private void goodB2G1Sink(String data) throws Throwable {
    if (goodB2G1Private) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      Connection dbConnection = null;
      PreparedStatement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        /* FIX: Use prepared statement and executeQuery (properly) */
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
        sqlStatement.setString(1, data);

        resultSet = sqlStatement.executeQuery();

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
コード例 #17
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // get a connection
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();

    String sqlStatement = request.getParameter("sqlStatement");
    String sqlResult = "";
    try {
      // create a statement
      Statement statement = connection.createStatement();

      // parse the SQL string
      sqlStatement = sqlStatement.trim();
      if (sqlStatement.length() >= 6) {
        String sqlType = sqlStatement.substring(0, 6);
        if (sqlType.equalsIgnoreCase("select")) {
          // create the HTML for the result set
          ResultSet resultSet = statement.executeQuery(sqlStatement);
          sqlResult = SQLUtil.getHtmlTable(resultSet);
          resultSet.close();
        } else {
          int i = statement.executeUpdate(sqlStatement);
          if (i == 0) {
            sqlResult = "<p>The statement executed successfully.</p>";
          } else { // an INSERT, UPDATE, or DELETE statement
            sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>";
          }
        }
      }
      statement.close();
      connection.close();
    } catch (SQLException e) {
      sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>";
    } finally {
      pool.freeConnection(connection);
    }

    HttpSession session = request.getSession();
    session.setAttribute("sqlResult", sqlResult);
    session.setAttribute("sqlStatement", sqlStatement);

    String url = "/index.jsp";
    getServletContext().getRequestDispatcher(url).forward(request, response);
  }
コード例 #18
0
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
      res.setContentType("text/html");
      pw = res.getWriter();
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:com", "o7it58", "yajiv32737");
      st = con.createStatement();
      pw.println("<html>");
      pw.println("<head><title>Welcome</title></head>");
      pw.println("<body>");

      s = req.getParameter("login");
      if (s.equals("Submit")) {
        uname = req.getParameter("firstname");
        pass = req.getParameter("pwd");
        PrintWriter out = new PrintWriter(new FileWriter("log.txt"), true);
        out.println(uname);
        rs =
            st.executeQuery(
                "select type from login where username='******' and password='******'");
        if (rs.next()) {
          type = rs.getString("type");
        } else {
          pw.println("<center>");
          pw.println("User does not exists");
          pw.println("</center>");
        }
        if (type.equals("admin")) {

          pw.println(
              "<a href=\"http://localhost:8080/servlet/AdminLogin\">Hello Admin.Please Click Here</a>");
        } else if (type.equals("staff")) {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StaffLogin\">Hello Staff.Please Click Here</a>");
        } else {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StudentLogin\">Hello Student.Please Click Here</a>");
        }
      }
      pw.println("</body></html>");
    } catch (Exception e) {
    }
  }
コード例 #19
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      int user_id = Integer.parseInt(request.getParameter("user_id"));
      int question_id = Integer.parseInt(request.getParameter("question_id"));
      int option = Integer.parseInt(request.getParameter("option"));

      System.out.println("uid: " + user_id + "\nquestion: " + question_id + "\noption: " + option);
      String str1 = "INSERT INTO VOTES(USER_ID, QUESTION_ID,OPTION_VOTED) VALUES (?,?,?)";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setInt(1, user_id);
      prep1.setInt(3, option);
      prep1.setInt(2, question_id);
      prep1.execute();

      String str2 = "SELECT OPTION_" + option + " FROM ARCHIVE_VOTES WHERE QUESTION_ID=?";
      PreparedStatement prep2 = con.prepareStatement(str2);
      prep2.setInt(1, question_id);
      int count = 0;
      ResultSet rs2 = prep2.executeQuery();
      if (rs2.next()) {
        count = rs2.getInt("OPTION_" + option);
      }
      count++;
      String str3 = "UPDATE ARCHIVE_VOTES SET OPTION_" + option + "=? WHERE QUESTION_ID=?";
      PreparedStatement prep3 = con.prepareStatement(str3);
      prep3.setInt(1, count);
      prep3.setInt(2, question_id);
      prep3.executeUpdate();

      out.print("You Vote has been recorded! Thank you!");
      System.out.println(
          "Voted for question " + question_id + ", by user " + user_id + ", for option " + option);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    PreparedStatement sqlstatement = null;
    ResultSet sqlrs = null;

    try {
      /* FIX: use prepared sqlstatement */
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.prepareStatement("select * from users where name=?");
      sqlstatement.setString(1, data);

      sqlrs = sqlstatement.executeQuery();

      IO.writeString(sqlrs.toString());
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlrs != null) {
          sqlrs.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlrs");
      } finally {
        try {
          if (sqlstatement != null) {
            sqlstatement.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlstatement");
        } finally {
          try {
            if (conn_tmp2 != null) {
              conn_tmp2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn_tmp2");
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;
    ResultSet sqlrs = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      /* POTENTIAL FLAW: take user input and place into dynamic sql query */
      sqlrs = sqlstatement.executeQuery("select * from users where name='" + data + "'");

      IO.writeString(sqlrs.toString());
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlrs != null) {
          sqlrs.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlrs");
      } finally {
        try {
          if (sqlstatement != null) {
            sqlstatement.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlstatement");
        } finally {
          try {
            if (conn_tmp2 != null) {
              conn_tmp2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn_tmp2");
          }
        }
      }
    }
  }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(HashMap<Integer, String> dataHashMap) throws Throwable {
    String data = dataHashMap.get(2);

    Connection dbConnection = null;
    PreparedStatement sqlStatement = null;
    ResultSet resultSet = null;

    try {
      /* FIX: Use prepared statement and executeQuery (properly) */
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.prepareStatement("select * from users where name=?");
      sqlStatement.setString(1, data);

      resultSet = sqlStatement.executeQuery();

      IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (resultSet != null) {
          resultSet.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
      }

      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
  /* goodG2B() - use GoodSource and BadSink */
  public void goodG2BSink(HashMap<Integer, String> dataHashMap) throws Throwable {
    String data = dataHashMap.get(2);

    Connection dbConnection = null;
    Statement sqlStatement = null;
    ResultSet resultSet = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
      resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");

      IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (resultSet != null) {
          resultSet.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
      }

      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
コード例 #24
0
 public ActionForward execute(
     ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
     throws Exception {
   ServiceDataForm obj = (ServiceDataForm) form;
   String serviceId = obj.getServiceId();
   CalculateService obj2 = new CalculateService();
   obj2.calculate(serviceId);
   Connection con = null;
   Class.forName(ConnectionStats.DRIVER);
   String url = ConnectionStats.DB_URL;
   String usr = ConnectionStats.DB_USER;
   String pwd = ConnectionStats.DB_PASSWORD;
   con = DriverManager.getConnection(url, usr, pwd);
   Statement stmt = con.createStatement();
   ResultSet rs = null;
   rs = stmt.executeQuery("select * from " + serviceId + "_main");
   ResultSetMetaData rsmd = rs.getMetaData();
   int col = rsmd.getColumnCount();
   String[] mainHeader = new String[col];
   for (int i = 0; i < col; i++) {
     mainHeader[i] = rsmd.getColumnLabel(i + 1);
   }
   ArrayList<String[]> serviceDataMain = new ArrayList<String[]>();
   while (rs.next()) {
     String[] str = new String[col];
     for (int i = 0; i < col; i++) {
       str[i] = rs.getString(i + 1);
     }
     serviceDataMain.add(str);
   }
   req.setAttribute("mainHeader", mainHeader);
   req.setAttribute("serviceDataMain", serviceDataMain);
   rs = stmt.executeQuery("select * from " + serviceId + "_tbl");
   rsmd = rs.getMetaData();
   col = rsmd.getColumnCount();
   String[] tblHeader = new String[col];
   for (int i = 0; i < col; i++) {
     tblHeader[i] = rsmd.getColumnLabel(i + 1);
   }
   ArrayList<String[]> serviceDatatbl = new ArrayList<String[]>();
   while (rs.next()) {
     String[] str = new String[col];
     for (int i = 0; i < col; i++) {
       str[i] = rs.getString(i + 1);
     }
     serviceDatatbl.add(str);
   }
   req.setAttribute("tblHeader", tblHeader);
   req.setAttribute("serviceDatatbl", serviceDatatbl);
   rs.close();
   con.close();
   return mapping.findForward("success");
 }
コード例 #25
0
 public Object process(ResultSet rs) {
   String users = "";
   try {
     while (rs.next()) {
       users =
           users
               + "<li>"
               + "<a href=/user1/user/"
               + rs.getString(1)
               + ">"
               + rs.getString(2)
               + "</a>"
               + "</li>";
     }
   } catch (Exception e) {
     users = e.toString();
   }
   return (Object) users;
 }
コード例 #26
0
ファイル: SearchServlet.java プロジェクト: sander92/evalimine
 private static String createJSON(ResultSet rs, String party, String area) {
   List<Candidate> candidates = new ArrayList<Candidate>();
   try {
     while (rs.next()) {
       Candidate candidate = new Candidate();
       candidate.setFName(rs.getString("FirstName"));
       candidate.setLName(rs.getString("LastName"));
       if (party.equals("") || party == null) {
         candidate.setParty(rs.getString("PartyName"));
       }
       if (area.equals("") || area == null) {
         candidate.setArea(rs.getString("AreaName"));
       }
       candidates.add(candidate);
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   Gson gson = new GsonBuilder().create();
   String candidatesJson = gson.toJson(candidates);
   return candidatesJson;
 }
コード例 #27
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    nseer_db_backup1 stock_db = new nseer_db_backup1(dbApplication);

    try {
      if (stock_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        int i;
        int intRowCount;
        String sqll =
            "select * from stock_config_public_char where describe1='\u51fa\u5165\u5e93\u7406\u7531'";
        ResultSet rs = stock_db.executeQuery(sqll);
        rs.next();
        rs.last();
        intRowCount = rs.getRow();
        String[] del = new String[intRowCount];
        del = (String[]) dbSession.getAttribute("del");
        if (del != null) {
          for (i = 1; i <= intRowCount; i++) {
            String sql = "delete from stock_config_public_char where id='" + del[i - 1] + "'";
            stock_db.executeUpdate(sql);
          }
        }
        stock_db.commit();
        stock_db.close();
        response.sendRedirect("stock/config/apply_gather_pay/reason.jsp");
      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #28
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String dbUser = "******"; // enter your username here
    String dbPassword = "******"; // enter your password here

    try {
      OracleDataSource ods = new oracle.jdbc.pool.OracleDataSource();
      ods.setURL("jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB");
      ods.setUser(dbUser);
      ods.setPassword(dbPassword);

      Connection conn = ods.getConnection();

      String query = new String();
      Statement s = conn.createStatement();

      query = "select * from events";

      ResultSet r = s.executeQuery(query);
      while (r.next()) {
        out.println("Today's Date: " + r.getString(1) + " ");
      }
      r.close();
      s.close();

      conn.close();

    } catch (Exception e) {
      out.println("The database could not be accessed.<br>");
      out.println("More information is available as follows:<br>");
      e.printStackTrace(out);
    }
  } // end doGet method
コード例 #29
0
  private void loadFromDb() throws WareNotFoundException {
    Connection con = null;
    PreparedStatement pstmt = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(LOAD_WARE_BY_ID);
      pstmt.setInt(1, Id);
      ResultSet rs = pstmt.executeQuery();
      if (!rs.next()) {
        throw new WareNotFoundException("从数据表[ware]中读取用户数据失败,欲读取的用户ID:[ " + Id + "]!");
      }

      this.Id = rs.getInt("Id");
      this.Pname = rs.getString("Pname");
      this.Pmodel = rs.getString("Pmodel");
      this.Pcost = rs.getString("Pcost");
      this.Pheft = rs.getString("Pheft");
      this.Pfacturer = rs.getString("Pfacturer");
      this.Pnote = rs.getString("Pnote");
      this.Createdate = rs.getString("Createdate");
      this.Status = rs.getInt("Status");
    } catch (SQLException sqle) {
      throw new WareNotFoundException("从数据表[WARE]中读取用户数据失败,欲读取的用户ID:[ " + Id + "]!");
    } finally {
      try {
        pstmt.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        con.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #30
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   out.println("vaishali mehta-130050131524");
   out.println("<html>");
   out.println("<body><table border='1'>");
   out.println("<th>name</th>");
   out.println("<th>password</th>");
   try {
     rs = stmt.executeQuery("select *from records");
     while (rs.next()) {
       tn = rs.getString("name");
       tp = rs.getString("password");
       out.println("<tr>");
       out.println("<td>" + tn + "</td>");
       out.println("<td>" + tp + "</td>");
       out.println("</tr>");
     }
   } catch (Exception e) {
     System.out.println(e);
   }
   out.println("</table></body></html>");
 }