Exemple #1
0
 public static void connect() {
   try {
     DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
     link = DriverManager.getConnection(myURL);
   } catch (SQLException e) {
     System.out.println("Echec de la connexion : " + e.getMessage());
   }
 }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    System.out.println("Clearing changes");
    Connection c = null;
    try {

      DriverManager.registerDriver(new AppEngineDriver());
      c = DriverManager.getConnection("jdbc:google:rdbms://trmrphdn:veebirakendused/andmebaas");
      String statement = "delete from kandidaat where nimi = 'Tandi Kaat'";
      PreparedStatement stmt = c.prepareStatement(statement);
      stmt.executeUpdate();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Exemple #3
0
  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();
    }
  }
Exemple #4
0
  /**
   * 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);
    }
  }
Exemple #5
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   try {
     Driver driver = new com.mysql.jdbc.Driver();
     DriverManager.registerDriver(driver);
     Connection connection =
         DriverManager.getConnection("jdbc:mysql://127.0.0.1/school", "root", "password");
     PreparedStatement preparedStatement =
         connection.prepareStatement("update student set name=?, per=? where roll=?");
     preparedStatement.setString(1, request.getParameter("name"));
     preparedStatement.setFloat(2, Float.parseFloat(request.getParameter("per")));
     preparedStatement.setInt(3, Integer.parseInt(request.getParameter("roll")));
     preparedStatement.execute();
     preparedStatement.close();
     connection.close();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Display");
   requestDispatcher.forward(request, response);
 }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String fName = req.getParameter("fName");
    String lName = req.getParameter("lName");
    String party = req.getParameter("party");
    String area = req.getParameter("area");

    Connection c = null;
    try {
      DriverManager.registerDriver(new AppEngineDriver());
      c =
          DriverManager.getConnection(
              "jdbc:google:rdbms://netivalimised2013:netivalimised/evalimised");
      String statement;
      if ((fName.equals("") || fName == null)
          && (lName.equals("") || lName == null)
          && (party.equals("") || party == null)
          && (area.equals("") || area == null)) {
        System.out.println("Getting all candidates");
        statement =
            "SELECT Person.FirstName, Person.LastName, Party.PartyName, Area.AreaName "
                + "FROM Person JOIN Party ON Person.PartyID = Party.Party_Id JOIN Area ON Person.AreaID = Area.Area_Id";
      } else statement = createQuery(fName, lName, party, area);
      PreparedStatement stmt = c.prepareStatement(statement);
      ResultSet rs = stmt.executeQuery();
      String jsonData = createJSON(rs, party, area);
      resp.setContentType("application/json");
      resp.setCharacterEncoding("UTF-8");
      resp.getWriter().write(jsonData);
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException ignore) {
        }
      }
    }
    // resp.setHeader("Refresh","3; url=/evalimised.jsp");
  }
  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
  }
Exemple #8
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {

      int a;
      a = 3;
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      String url = "jdbc:odbc:books";
      connection = DriverManager.getConnection(url);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public void init(ServletConfig servletconfig) throws ServletException {
   super.init(servletconfig);
   try {
     System.out.println("inside init");
     Class.forName("oracle.jdbc.driver.OracleDriver");
     System.out.println("driver is created");
     con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "care", "care");
     System.out.println("Connection is created");
     st = con.createStatement();
     System.out.println("statement is created");
   } catch (Exception exception) {
     System.out.println(exception);
   }
 }
  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();
    }
  }
  // Log into DB and print out all logs.
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try (Connection connection =
        DriverManager.getConnection(getConnectionUrl(), "postgres", null)) {
      // Insert current request in DB ...
      insertLog(req, connection);

      // ... and then return all logs stored so far
      resp.setContentType("text/plain");
      PrintWriter out = resp.getWriter();
      printOutLogs(connection, out);

    } catch (SQLException e) {
      throw new ServletException("Cannot update DB: " + e, e);
    }
  }
  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) {
    }
  }
 public void init(ServletConfig sc) throws ServletException {
   super.init(sc);
   try {
     Class.forName("com.mysql.jdbc.Driver");
     System.out.println("driver is loaded");
     con = DriverManager.getConnection(url, un, password);
     System.out.println("connected");
     stmt = con.createStatement();
     System.out.println("wrapper created");
   } catch (ClassNotFoundException cnfe) {
     System.out.println("driver Not Loaded" + cnfe.getMessage());
     return;
   } catch (SQLException sqle) {
     System.out.println("connection problem" + sqle.getMessage());
     return;
   }
 }
Exemple #14
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

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

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
  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();
    }
  }
Exemple #16
0
  public void init() throws ServletException {

    ServletContext context = getServletContext();
    String driver = context.getInitParameter("p1");
    String cs = context.getInitParameter("p2");
    String username = context.getInitParameter("p3");
    String password = context.getInitParameter("p4");

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(cs, username, password);
      ps =
          con.prepareStatement(
              "select * from registration1 where username=? and password=? and user_type=?");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #17
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   try {
     String username = request.getParameter("t1");
     String password = request.getParameter("t2");
     String email = request.getParameter("t4");
     String college = request.getParameter("t5");
     String phone = request.getParameter("t6");
     String country = request.getParameter("t7");
     String languages = request.getParameter("t8");
     Class.forName("oracle.jdbc.driver.OracleDriver");
     Connection con =
         DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "tiger");
     PreparedStatement pst = con.prepareStatement("insert into stu_tab values(?,?,?,?,?,?,?)");
     pst.setString(1, username);
     pst.setString(2, password);
     pst.setString(3, email);
     pst.setString(4, college);
     pst.setString(5, phone);
     pst.setString(6, country);
     pst.setString(7, languages);
     int i = pst.executeUpdate();
     if (i != 0) {
       out.println("<html><body align=center bgcolor=#C0C0C0 text=black>");
       out.println("<h3>!.. Registration Successful !..</h3>");
       out.println(
           "<a href=Slogin1.html style=text-decoration:none>click here</a>&nbsp;to go back to login page");
       out.println("</body></html>");
     } else {
       out.println("<html><body align=center bgcolor=#C0C0C0 text=black>");
       out.println("<h3>!.. Registration Failed !..</h3>");
       out.println(
           "<a href=Slogin1.html style=text-decoration:none>click here</a>&nbsp;to go back to login page");
       out.println("</body></html>");
     }
   } catch (Exception e) {
     out.println(e);
   }
 }
Exemple #18
0
  private Connection getConnectiontoDB() {

    Connection con = null;
    /*	String url = "jdbc:postgresql://10.16.194.69:5432/ls";
    String user = "******";
    String password = "******";*/

    String url = "jdbc:postgresql://localhost:5432/ls";
    String user = "******";
    String password = "******";

    try {

      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection(url, user, password);

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return con;
  }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // I use "session" in order to throws the object named user bean.
   HttpSession session = request.getSession(true);
   response.setContentType("text/html");
   request.setCharacterEncoding("UTF-8");
   UserBean ub = (UserBean) session.getAttribute("user");
   if (ub == null) {
     String haveLogin = "******";
     session.setAttribute("haveLogin", haveLogin);
     response.sendRedirect("cart");
   } else {
     String mID = ub.getmID();
     String iID = (String) request.getParameter("iID");
     // String idx = (String)request.getParameter("idx");
     Connection conn = null;
     try {
       // Getting the connection from database.
       Class.forName("com.mysql.jdbc.Driver");
       /*conn = DriverManager
       .getConnection("jdbc:mysql://localhost/se?"
       		+ "user=root");*/
       conn =
           DriverManager.getConnection(
               "jdbc:mysql://localhost/user_register?"
                   + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8");
       String sql = "delete from cart_item_mapping where mID=? and iID = ?";
       PreparedStatement pst = conn.prepareStatement(sql);
       // Using preparedstatement by set the parameter related to "?" symbol.
       pst.setString(1, mID);
       pst.setString(2, iID);
       pst.executeUpdate();
       pst.close();
       response.sendRedirect("ShowCartController");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    switch (6) {
      case 6:
        {
          data = "pass";
        }
        break;
      default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        {
          java.util.logging.Logger log_good_source =
              java.util.logging.Logger.getLogger("local-logger");
          BufferedReader bufread2 = null;
          InputStreamReader inread2 = null;
          Properties prop = new Properties();
          IO.writeLine("Enter the password: "******"";
          try {
            inread2 = new InputStreamReader(System.in);
            bufread2 = new BufferedReader(inread2);
            /* FIX: password is read from stdin */
            data = bufread2.readLine();
          } catch (Exception e) {
            log_good_source.warning("Exception in try");
          } finally {
            try {
              if (bufread2 != null) {
                bufread2.close();
              }
            } catch (IOException e) {
              log_good_source.warning("Error closing bufread2");
            } finally {
              try {
                if (inread2 != null) {
                  inread2.close();
                }
              } catch (IOException e) {
                log_good_source.warning("Error closing inread2");
              }
            }
          }
        }
        break;
    }

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

    Connection conn2 = null;
    PreparedStatement st = null;
    ResultSet rs2 = null;
    String pw = data;
    try {
      /* POTENTIAL FLAW: use of hard-coded password */
      conn2 = DriverManager.getConnection("data-url", "root", pw);
      st = conn2.prepareStatement("select * from test_table");
      rs2 = st.executeQuery();
    } catch (SQLException e) {
      log2.warning("Error with database connection");
    } finally {
      try {
        if (rs2 != null) {
          rs2.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing rs2");
      } finally {
        try {
          if (st != null) {
            st.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing st");
        } finally {
          try {
            if (conn2 != null) {
              conn2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn2");
          }
        }
      }
    }
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector =
          (org.glassfish.jsp.api.ResourceInjector)
              application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\n");
      out.write("    \n");
      out.write("    \n");
      out.write("    \n");
      Class.forName("com.mysql.jdbc.Driver");
      out.write("\n");
      out.write("    \n");
      out.write("    \n");
      out.write(
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write(" <link href=\"css/bootstrap.min.css\" rel=\"stylesheet\">\n");
      out.write("        <!-- Bootstrap css online -->\n");
      out.write(
          "        <link rel=\"stylesheet\" href=\"http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css\">\n");
      out.write("        <link  href=\"css/customcss.css\" rel=\"stylesheet\">\n");
      out.write(
          "        <script type=\"text/javascript\" src=\"js/jquery-1.10.2.min.js\"></script>\n");
      out.write("        <script src=\"js/bootstrap.min.js\"></script>\n");
      out.write("\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n");
      out.write("<title>Analysis of Algorithms : D.B.Phatak</title>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      out.write("\n");
      out.write("<!--Header-->\n");
      out.write("\n");
      out.write("  ");

      String name = (String) session.getAttribute("pass");

      out.write("\n");
      out.write("    <div class=\"container\">\n");
      out.write("             <br>\n");
      out.write("            <!--HEADER -->\n");
      out.write("            <div class=\"header\">\n");
      out.write(
          "                <a href=\"index.jsp\" style=\"color: #000;\"> <ul class=\"nav nav-pills pull-left\" >\n");
      out.write(
          "                    <li id=\"brand_icon\">       <img src=\"Images/mic_logo.png\" alt=\"\" width=\"80px\" height=\"80px\"/></li>\n");
      out.write(
          "                    <li id=\"brand_name\"> <p class=\"title\"><span style=\"font-size: 70px;\">|</span> iClass <strong>Forum</strong></p></li>\n");
      out.write("\n");
      out.write("                </ul></a>\n");
      out.write(
          "                <!--   <p class=\"title1\">iClass</p>&nbsp;&nbsp;<p class=\"title2\">Forum</p> \n");
      out.write("                -->\n");
      out.write("                <form action=\"Login\" method=\"post\">\n");
      out.write("\n");
      out.write(
          "                    <ul class=\"nav nav-pills pull-right\" style=\"margin-top: 35px\">\n");
      out.write("                        <li><a href=\"index.jsp\">Home</a></li>\n");
      out.write("                        <li><a href=\"contactus.jsp\">Contact Us</a></li>\n");
      out.write("\n");
      out.write("                        ");
      if (name != null) {
        try {
          out.write("\n");
          out.write("\n");
          out.write("                        <li><a href=\"logout.jsp\">Logout</a></li>\n");
          out.write("                        <li style=\"margin-top: 10px\">Welcome ");
          out.print(name);
          out.write("</li>\n");
          out.write("\n");
          out.write("                        ");
        } catch (Exception e) {

          System.out.println("Problem :" + e);
        }

      } else {

        out.write("\n");
        out.write("\n");
        out.write("                        <li><a href=\"signup.jsp\">Login</a></li>\n");
        out.write("\n");
        out.write("                        ");
      }
      out.write("\n");
      out.write("\n");
      out.write("                    </ul>\n");
      out.write("                </form>\n");
      out.write("\n");
      out.write("\n");
      out.write("            </div>\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("            <br>\n");
      out.write("         \n");
      out.write("      \n");
      out.write("\n");
      out.write("        <!-- MODAL -->\n");
      out.write("        <form action=\"\" name=\"batti\" method=\"post\">\n");
      out.write("\n");
      out.write(
          "        <div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\n");
      out.write("          <div class=\"modal-dialog\">\n");
      out.write("            <div class=\"modal-content\">\n");
      out.write("              <div class=\"modal-header\">\n");
      out.write(
          "                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\n");
      out.write("                <h4 class=\"modal-title\" id=\"myModalLabel\">Answer here</h4>\n");
      out.write("              </div>\n");
      out.write("              <div class=\"modal-body\">\n");
      out.write("                                <div class=\"input-group input-group-lg\">\n");
      out.write("                                <span class=\"input-group-addon\">\n");
      out.write(
          "                                <span class=\"glyphicon glyphicon-pencil\"></span>\n");
      out.write("                                </span>\n");
      out.write(
          "                                <textarea class=\"form-control\" id=\"currentans\" name=\"mainanswer\" rows=\"10\" style=\"resize: vertical;\">\n");
      out.write("                                </textarea>\n");
      out.write("                                </div>\n");
      out.write("              </div>\n");
      out.write("              <div class=\"modal-footer\">\n");
      out.write(
          "              <input type=\"text\" id=\"hidden\" name=\"maindata\" value=\"JAI HO\"/>\n");
      out.write(
          "                <button type=\"button\" class=\"btn btn-primary\" onClick=\"saveAns()\">Save Answer</button>\n");
      out.write("              </div>\n");
      out.write("            </div>\n");
      out.write("          </div>\n");
      out.write("        </div>\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("    </form>\n");
      out.write("    <!-- MODAL ENDS HERE -->\n");
      out.write("\n");
      out.write("<div class=\"page1\" >          \n");
      out.write("                <center>\n");
      out.write("\n");
      out.write(
          "                    <font face=\"myFontThin\" size=\"6\" class=\"title\">Department of  </font><font face=\"myFontThick\" size=\"8\"><b>Computer Science</b></font>\n");
      out.write("                <br>\n");
      out.write("                   <font face=\"myFontThick\" size=\"5\">Prof. sunil</font>\n");
      out.write("                \n");
      out.write("                </center>\n");
      out.write(
          "                <br> <br>  <font face=\"myFontThick\" size=\"6\"><b> bbbbbb </b></font>\n");
      out.write("<br><br><br>\n");
      out.write("                        \n");
      out.write("\n");
      out.write("\n");
      out.write("            ");

      Connection connection =
          DriverManager.getConnection("jdbc:mysql://localhost/aakash", "root", "lavikothari");
      Statement statement = connection.createStatement();
      ResultSet resultset = statement.executeQuery("select * from qa27;");

      int i = 0, no, ct = 0;
      String qid, bid, ansdivid, buttonid, delbuttonid, userid, answerid;

      while (resultset.next()) {
        ct++;
        no = resultset.getInt(1);
        if (i < no) {
          i = no;
        }
        qid = "q" + no;
        ansdivid = "ans" + no;
        bid = "b" + no;
        buttonid = "button" + no;
        delbuttonid = "delbutton" + no;
        userid = "user" + no;
        answerid = "answer" + no;

        out.write("\n");
        out.write("        <!--  <form action=\"\" method=\"get\" name=\"batti\" > -->\n");
        out.write("\t    \n");
        out.write("\t<div class=\"panel panel-default\">\n");
        out.write("            <div class=\"panel-heading\">\n");
        out.write("                <h3 class=\"panel-title\">\n");
        out.write("                <div id=");
        out.print(userid);
        out.write(
            " style=\"font-style:bold ;font-size:15px; padding-left:0.5px ;text-shadow: 2px 2px 8px #6E6E6E\">\n");
        out.write("\t    \t");
        out.print(resultset.getString(4));
        out.write("\n");
        out.write("                </div>\n");
        out.write("                </h3>\n");
        out.write("            </div>\n");
        out.write("            <div class=\"panel-body\">\n");
        out.write("                <div id=");
        out.print(qid);
        out.write(" style=\"text-align:left ;font-size:20px;font-style:italic\">\n");
        out.write("\t\t\t");
        out.print(resultset.getString(2));
        out.write("<br><br>\n");
        out.write("\t\t</div>\n");
        out.write("\t    \t<div class=\"panel panel-default\" id=");
        out.print(ansdivid);
        out.write(" >\n");
        out.write("  \t\t\t\t<div class=\"panel-body\" >\n");
        out.write("   \t\t\t \t\t<p id=");
        out.print(answerid);
        out.write('>');
        out.print(resultset.getString(3));
        out.write("</p>\n");
        out.write(" \t\t \t\t</div>\n");
        out.write("\t\t</div>\n");
        out.write("\t\t<div id=");
        out.print(bid);
        out.write(" >\n");
        out.write("\t\t\t ");
        String condition = (String) session.getAttribute("pass");
        String prof1 = (String) session.getAttribute("Prof");
        String prof2 = (String) session.getAttribute("Prof2");

        // out.println("Lec="+condition);

        // out.println("prof1="+prof1);
        // out.println("prof2="+prof2);
        // System.out.println("Lec="+condition);
        if (condition != null && prof1.equals(prof2)) {

          out.write("       \n");
          out.write("\n");
          out.write(
              "                                <input type=\"button\" class=\"btn btn-primary btn-sm\" style=\"float:right;display:inline\" value=\"Delete\" onClick=\"delQues(this.id)\" id=");
          out.print(delbuttonid);
          out.write(" />\n");
          out.write(
              "                                <input type=\"button\" class=\"btn btn-primary btn-sm\" style=\"float:left;display:inline\" data-toggle=\"modal\" value=\"Answer\" data-target=\"#myModal\" onClick=\"myfunc(this.id)\" id=");
          out.print(buttonid);
          out.write(" />\n");
          out.write("                                ");
        }

        out.write("\n");
        out.write("         \n");
        out.write("\t\t</div>\n");
        out.write("            </div>\n");
        out.write("        </div>\n");
        out.write("\t\n");
        out.write("\t   \n");
        out.write("\t\t\n");
        out.write("        ");
      }
      out.write("\n");
      out.write("\n");
      out.write(
          "               <form action=\"\" name=\"delform\" method=\"post\" style=\"visibility:hidden\">\n");
      out.write("\n");
      out.write(
          "               <input type=\"text\" id= \"delfieldid\" name=\"delfield\" value=\"Namastey\" />\n");
      out.write(
          "               <input type=\"text\" id= \"futureid\" name=\"futurefield\" value=\"London\" />\n");
      out.write("               </form>\n");
      out.write("\n");
      out.write("\n");
      out.write("        <span id =\"debug\" style=\"visibility:hidden\">Hello </span>\n");
      out.write("\n");
      out.write("    </div>\n");
      out.write("</div>    \n");
      out.write("\t    \n");
      out.write(" \n");
      out.write("</div>\n");
      out.write(" \n");
      out.write(" </div>\n");
      out.write("        \n");
      out.write(" \n");
      out.write(" <script type=\"text/javascript\">\n");
      out.write("\t count=");
      out.print(ct);
      out.write(";\n");
      out.write("\t debugging=document.getElementById(\"debug\");\n");
      out.write("\t debugging.innerHTML=\"Count is\"+count;\n");
      out.write("\t hid=document.getElementById(\"hidden\");\n");
      out.write("\t hid.style.display='none';\n");
      out.write("\t \n");
      out.write("\t for (x=1;x<=count;x++)\n");
      out.write("\t {\t\n");
      out.write("\t\t y=document.getElementById(\"answer\"+x);\n");
      out.write("\t\t debug.innerHTML+=y.innerHTML;\n");
      out.write("\t\t z=document.getElementById(\"button\"+x);\n");
      out.write("\t\t if(y!=null && y.innerHTML==\"\")\n");
      out.write("\t\t {\n");
      out.write("\t\t document.getElementById(\"ans\"+x).style.display='none';\n");
      out.write("\t\t }\n");
      out.write("\t\t \n");
      out.write("\t\t else\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t if(z!=null){\n");
      out.write("\t\t\t z.value=\"Edit Answer\";\n");
      out.write("\t\t\t }\n");
      out.write("\t\t\t }\n");
      out.write("\t }\n");
      out.write("\n");
      out.write("\t function myfunc(clicked_id){\n");
      out.write("\t\t \n");
      out.write("\t\t hid.value=clicked_id;\n");
      out.write("\t\t quesid=clicked_id.replace(\"button\",\"q\");\n");
      out.write("\t\t ansid=clicked_id.replace(\"button\",\"answer\");\n");
      out.write("\t\t \n");
      out.write("\t\t question=document.getElementById(quesid).innerHTML;\n");
      out.write("\t\t answer=document.getElementById(ansid).innerHTML;\n");
      out.write("\t\t \n");
      out.write("\t\t answer.replace(\"  \",\"\");\n");
      out.write("\t\t question.replace(\"  \",\"\");\n");
      out.write("\t\t \n");
      out.write("\t\t document.getElementById(\"myModalLabel\").innerHTML=question;\n");
      out.write("\t\t document.getElementById(\"currentans\").value=answer;\n");
      out.write("\t\t \n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t\n");
      out.write("\t function saveAns()\n");
      out.write("\t {\n");
      out.write("\t\t document.batti.submit();\n");
      out.write("\t\t \n");
      out.write("\t\t ");

      String clid = request.getParameter("maindata");
      if (clid != null) {
        String tobeanswered = clid.replace("button", "");
        System.out.println(tobeanswered);
        String answer = request.getParameter("mainanswer");

        Statement stmt = connection.createStatement();
        String query = "update qa27 set ans ='" + answer + "' where id='" + tobeanswered + "';";

        stmt.executeUpdate(query);

        response.sendRedirect("lec.jsp#user" + tobeanswered);
      }

      out.write("\n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t \n");
      out.write("\n");
      out.write("\t function delQues(clicked_id)\n");
      out.write("\t {\n");
      out.write("\t\t \n");
      out.write("\t\t document.getElementById(\"delfieldid\").value=clicked_id;\n");
      out.write("\t\t \n");
      out.write("\t\t \n");
      out.write("\t\t\t document.getElementById(\"futureid\").value=\"yesssssssss\";\n");
      out.write("\t\t  v=parseInt(clicked_id.replace(\"delbutton\",\"\"))+1;\n");
      out.write("\t\t while(document.getElementById(\"user\"+v)==null && v<count)\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t v++;\n");
      out.write("\t\t\t document.getElementById(\"futureid\").value=\"user\"+v;\n");
      out.write("\t\t\t }\n");
      out.write("\t\t if(clicked_id==\"delbutton\"+count)\n");
      out.write("\t\t\t {\n");
      out.write("\t\t\t v=parseInt(clicked_id.replace(\"delbutton\",\"\"))-1;\n");
      out.write("\t\t\t }\n");
      out.write("\t\tdocument.getElementById(\"futureid\").value=\"user\"+v;\n");
      out.write("\t\t\t \n");
      out.write("\t\t document.delform.submit();\n");
      out.write("\t\t \n");
      out.write("\t\t ");

      String delid = request.getParameter("delfield");
      if (delid != null) {
        String tobedel = delid.replace("delbutton", "");
        System.out.println("Deleting " + tobedel);

        Statement stmt1 = connection.createStatement();
        String query1 = "delete from qa27 where id='" + tobedel + "';";

        stmt1.executeUpdate(query1);
        String futid = request.getParameter("futurefield");
        response.sendRedirect("lec.jsp#" + futid);
      }

      out.write("\n");
      out.write("\t\t \n");
      out.write("\t }\n");
      out.write("\t \n");
      out.write("\t \n");
      out.write("\t </script>\n");
      out.write("\t\n");
      out.write("\n");
      out.write("</body>\n");
      out.write("</html> \n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    HttpSession session = request.getSession(false);
    if (session == null) {
      session = request.getSession();
    }

    PrintWriter out = response.getWriter();
    Connection conn = null;
    Statement stmt = null;
    try {
      System.out.println("Enrollno: 130050131067");
      // 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...");

      stmt = conn.createStatement();

      // STEP 2: Executing query
      String name = "asdf";
      String rollno = "34";
      String branch = "CSE";
      String sql =
          "INSERT INTO student(rollno, name, branch) VALUES ('"
              + rollno
              + "', '"
              + name
              + "', '"
              + branch
              + "')";

      if (stmt.executeUpdate(sql) != 0) {
        out.println("Record has been inserted</br>");
      } else {
        out.println("Sorry! Failure</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 (stmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
  }
Exemple #23
0
  /**
   * 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;

    if (username == null || password == null) {
      out.println("<h1>Invalid Register Request</h1>");
      out.println("<a href=\"register.html\">Register</a>");

      return;
    }
    Connection con = null;

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

      if (con != null) {
        System.out.println("Ola ok me 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();

      rs = stmt.executeQuery("SELECT * FROM users WHERE username='******'");
      if (rs.next()) {
        out.println("<h1>Username exists</h1>");
        out.println("<a href=\"register.html\">Register</a>");

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

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO users VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>You are now registered " + username + "</h1>");
        out.println("<a href=\"index.jsp\">Login</a>");

        int i;
        for (i = 0; i < listeners.size(); i++) listeners.get(i).UserRegistered(username);
      } else {
        out.println("<h1>Could not add your username to the db</h1>");
        out.println("<a href=\"register.html\">Register</a>");
      }

      stmt.close();
      con.close();
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
Exemple #24
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    server svr = new server();
    response.setContentType("text/html");
    HttpSession session = request.getSession(true);
    PrintWriter out = response.getWriter();
    String email = request.getParameter("email");
    String pw1 = request.getParameter("pw1");
    String pw2 = request.getParameter("pw2");
    String error = null;
    String username = session.getAttribute("username").toString();
    if (pw1.compareTo(pw2) != 0) {
      error = "Passwords do not match";
      session.setAttribute("ErrorMessage", error);
      response.sendRedirect("home.jsp");
    }
    try {
      Statement st = null;
      String strQuery = null;
      if ((pw1.length() == 0) && (email.length() == 0)) {
        session.setAttribute("ErrorMessage", "Nothing to change!");
        response.sendRedirect("home.jsp");
      } else if ((pw1.length() != 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "', `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() == 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() != 0) && (email.length() == 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "' WHERE `username`='"
                + username
                + "'";
      }
      Connection dbcon = null;
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      dbcon = DriverManager.getConnection(svr.getURL(), svr.getUN(), svr.getPW());
      st = dbcon.createStatement();
      st.executeUpdate(strQuery);
      session.setAttribute("ErrorMessage", "Details Changed");
      dbcon.close();
      session.setAttribute("ErrorMessage", "Details Changed");
      response.sendRedirect("home.jsp");
    } catch (Exception ex) {
      out.println(ex);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    try {
      Object accountObject = session.getValue(ACCOUNT);

      // If no account object was put in the session, or
      // if one exists but it is not a hashtable, then
      // redirect the user to the original login page

      if (accountObject == null)
        throw new RuntimeException("You need to log in to use this service!");

      if (!(accountObject instanceof Hashtable))
        throw new RuntimeException("You need to log in to use this service!");

      Hashtable account = (Hashtable) accountObject;

      String userName = (String) account.get("name");

      //////////////////////////////////////////////
      // Display Messages for the user who logged in
      //////////////////////////////////////////////
      out.println("<HTML>");
      out.println("<HEAD>");
      out.println("<TITLE>Contacts for " + userName + "</TITLE>");
      out.println("</HEAD>");
      out.println("<BODY BGCOLOR='#EFEFEF'>");
      out.println("<H3>Welcome " + userName + "</H3>");

      out.println("<CENTER>");

      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con =
            DriverManager.getConnection(
                "jdbc:mysql://localhost/contacts?user=kareena&password=kapoor");

        stmt = con.createStatement();
        rs =
            stmt.executeQuery(
                "SELECT * FROM contacts WHERE userName='******' ORDER BY contactID");

        out.println("<form name='deleteContactsForm' method='post' action='deleteContact'>");

        out.println("<TABLE BGCOLOR='#EFEFFF' CELLPADDING='2' CELLSPACING='4' BORDER='1'>");
        out.println("<TR BGCOLOR='#D6DFFF'>");
        out.println("<TD ALIGN='center'><B>Contact ID</B></TD>");
        out.println("<TD ALIGN='center'><B>Contact Name</B></TD>");
        out.println("<TD ALIGN='center'><B>Comment</B></TD>");
        out.println("<TD ALIGN='center'><B>Date</B></TD>");
        out.println("<TD ALIGN='center'><B>Delete Contacts</B></TD>");
        out.println("</TR>");

        int nRows = 0;
        while (rs.next()) {
          nRows++;
          String messageID = rs.getString("contactID");
          String fromUser = rs.getString("contactName");
          String message = rs.getString("comments");
          String messageDate = rs.getString("dateAdded");

          out.println("<TR>");
          out.println("<TD>" + messageID + "</TD>");
          out.println("<TD>" + fromUser + "</TD>");
          out.println("<TD>" + message + "</TD>");
          out.println("<TD>" + messageDate + "</TD>");
          out.println(
              "<TD><input type='checkbox' name='msgList' value='" + messageID + "'> Delete</TD>");
          out.println("</TR>");
        }

        out.println("<TR>");
        out.println(
            "<TD COLSPAN='6' ALIGN='center'><input type='submit' value='Delete Selected Contacts'></TD>");
        out.println("</TR>");

        out.println("</TABLE>");
        out.println("</FORM>");
      } catch (Exception e) {
        out.println("Could not connect to the users database.<P>");
        out.println("The error message was");
        out.println("<PRE>");
        out.println(e.getMessage());
        out.println("</PRE>");
      } finally {
        if (rs != null) {
          try {
            rs.close();
          } catch (SQLException ignore) {
          }
        }
        if (stmt != null) {
          try {
            stmt.close();
          } catch (SQLException ignore) {
          }
        }
        if (con != null) {
          try {
            con.close();
          } catch (SQLException ignore) {
          }
        }
      }

      out.println("</CENTER>");
      out.println("</BODY>");
      out.println("</HTML>");

    } catch (RuntimeException e) {
      out.println("<script language=\"javascript\">");
      out.println("alert(\"You need to log in to use this service!\");");
      out.println("</script>");

      out.println("<a href='index.html'>Click Here</a> to go to the main page.<br><br>");

      out.println(
          "Or Click on the button to exit<FORM><INPUT onClick=\"javascipt:window.close()\" TYPE=\"BUTTON\" VALUE=\"Close Browser\" TITLE=\"Click here to close window\" NAME=\"CloseWindow\" STYLE=\"font-family:Verdana, Arial, Helvetica; font-size:smaller; font-weight:bold\"></FORM>");

      log(e.getMessage());
      return;
    }
  }
Exemple #26
0
 // To connect to the specified database.
 private static Connection getConnected(
     String drivername, String dbstring, String username, String password) throws Exception {
   Class drvClass = Class.forName(drivername);
   DriverManager.registerDriver((Driver) drvClass.newInstance());
   return (DriverManager.getConnection(dbstring, username, password));
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");

    Connection conn = null;
    System.out.println("Reached here 1");
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String user = "";
    String userpass = "";
    String strQuery = "";

    Statement st = null;
    ResultSet rs = null;
    HttpSession session = request.getSession(true);

    try {
      Class.forName(driver);

      conn = DriverManager.getConnection("jdbc:odbc:test", "", "");

      if (request.getParameter("user") != null
          && request.getParameter("user") != ""
          && request.getParameter("userpass") != null
          && request.getParameter("userpass") != "") {
        user = request.getParameter("user").toString();
        userpass = request.getParameter("userpass").toString();
        strQuery = "select * from register ";

        st = conn.createStatement();
        System.out.println("Reached here 2");

        rs = st.executeQuery(strQuery);

        System.out.println("Reached here 3");
        String cpass = null;
        String name = null;
        while (rs.next()) {
          if (rs.getString(3).equals(user)) {
            name = rs.getString(1);
            cpass = rs.getString("pass");
            break;
          }
        }
        session.setAttribute("sname", name);

        System.out.println("Reached Here 4");

        StringBuffer q = pack.calc(userpass);
        String q1 = q.toString();
        System.out.println("Reached Here 5");
        if (cpass.equals(q1)) {

          RequestDispatcher rd =
              this.getServletConfig().getServletContext().getRequestDispatcher("/home.jsp");
          rd.forward(request, response);

        } else {
          RequestDispatcher rd =
              this.getServletConfig().getServletContext().getRequestDispatcher("/login5.jsp");
          rd.forward(request, response);
        }
      }

      conn.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #28
0
  public void service(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/xml");
    PrintWriter out = res.getWriter();

    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    HttpSession session = req.getSession(true);

    String url = "";
    String nom = "";
    String mdp = "";

    try {
      // Enregistrement du Driver
      Class.forName("org.postgresql.Driver");

      // Chargement du fichier Props
      Properties prop = new Properties();
      try {
        prop.load(new FileInputStream(getServletContext().getRealPath("/Props.txt")));
        url = prop.getProperty("url");
        nom = prop.getProperty("nom");
        mdp = prop.getProperty("mdp");
      } catch (Exception e) {
        out.println(e.getMessage());
      }

      // Connexion a la base
      con = DriverManager.getConnection(url, nom, mdp);
      stmt = con.createStatement();

      rs =
          stmt.executeQuery(
              "SELECT prix,libelle,pno From produits WHERE prix=(select MAX(prix) FROM produits) limit 1;");

      int prix = 0;
      String libelle = "";
      int pno = 0;

      if (rs.next()) {
        prix = Integer.parseInt(rs.getString("prix"));
        libelle = rs.getString("libelle");
        pno = Integer.parseInt(rs.getString("pno"));
      }

      out.println("<data>");
      out.println("<prix>" + prix + "</prix>");
      out.println("<libelle>" + libelle + "</libelle>");
      out.println("<pno>" + pno + "</pno>");
      out.println("</data>");

    } catch (Exception e) {
      out.println(e.getMessage());
    } finally {
      try {
        stmt.close();
        con.close();
      } catch (Exception e) {
        out.println(e.getMessage());
      }
    }
  }
Exemple #29
0
	public void doPost (HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
	{
		Connection con=null;
		pw=res.getWriter();
		Statement stmt=null;
		ResultSet rr=null;
		ResultSetMetaData rsmd;
		res.setContentType("text/html");
		
		try
		{
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		con=DriverManager.getConnection("jdbc:odbc:sri","scott","tiger");
		stmt=con.createStatement();
		String inm="'"+req.getParameter("txtinm")+"'";
		String q="'"+req.getParameter("txtq")+"'";
		String t=req.getParameter("txtr");
		char type=t.charAt(0);
                                System.out.println((char)type);
		pw.println("Item name "+inm);
                                pw.println("Quantity "+q);
		pw.println("Item Type "+t);
		pw.println((char)type);
		String qry1=null;
		switch(type)
		{
			case 'H':
			case 'h':
				qry1="select rate,iname from hware where iname="+inm;
				pw.println(qry1);
				// rr=stmt.executeQuery("select rate from hware where iname="+inm);
				rr=stmt.executeQuery(qry1);
				pw.println("Query is Executed...");
				break;
			case 'S':
			case 's':      qry1="select rate,iname from sware where iname="+inm;
				pw.println(qry1);
				break;
			
			case 'M':
			case 'm':   rr=stmt.executeQuery("select rate,title from music where title="+inm);
				break;
			
			case 'B':
			case 'b': rr=stmt.executeQuery("select rate,title from books where title="+inm);
				break;
			default:
				{
				pw.println("Invalid choice");
				 myflag='n';
				}
                                                           
		}
		        pw.println("Concerned Statement Prepared and Executed...");
						
                                pw.println((char)type+" Valid item type "+myflag);
		
		/*rsmd=rr.getMetaData();
                                int col=rsmd.getColumnCount();
                                pw.println("The Above Query has fetched "+col+ " Columns");*/
		String name="";
		while(rr.next())	
                                {
		String rate=rr.getString(1);
		int amount=Integer.parseInt(rate);
                                name=rr.getString(2);
                                  System.out.println(" "+rate+" "+name);
		pw.println(" "+amount+" "+name);
		pw.println("\n"+myflag);
		System.out.println("Valid item name "+rr.getString(2)+"     "+myflag);
		}
		pw.println(" "+myflag);
                                 if(myflag=='y')
                                  {
			pw.println("\nOK");
		pw.println("Valid item name "+name+"     "+myflag);
		if(rr==null)
		{
			pw.println("Not a valid item");
			myflag='n';
		}
		pw.println("Valid item name "+name+"     "+myflag);
                                  if(myflag=='y')
                                  {
                                        pw.println(" "+inm+" "+q);
                                       rr=stmt.executeQuery("select * from reges where flag='y'");
		if(rr==null)
		{
			pw.println("\nSign in first");
			//System.exit(0);
                                                 myflag='n';
		}
		pw.println("Signed in "+rr.getString(1)+"     "+myflag);
                                    if(myflag=='y')
                                   {
		String data="'"+rr.getString(1)+"'";	
		String qry="insert into cart values("+inm+","+q+","+data+")";
		pw.println("Query is "+qry);
		int rs=stmt.executeUpdate(qry);
		pw.println("1 row inserted");
                          } 
                           }  
                            }
	           	}		

		catch(ClassNotFoundException e){}
		catch(SQLException e){}
	}
Exemple #30
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector =
          (org.glassfish.jsp.api.ResourceInjector)
              application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("<!DOCTYPE html>\n");
      out.write("<html>\n");
      out.write("    <head>\n");
      out.write(
          "        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
      out.write("        <title>Fine</title>\n");
      out.write("        <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">    \n");
      out.write("\n");
      out.write("    </head>\n");
      out.write("    <body style = \"background-image: url(lib2.jpg)\">         \n");
      out.write("    <center>\n");
      out.write("        <h1>Update Fines information</h1>\n");
      out.write("        <form name=\"Update\" action=\"Fines_upd.jsp\">\n");
      out.write("            <table border=\"0\" width=\"3\" cellspacing=\"2\">\n");
      out.write("                <thead>\n");
      out.write("                    <tr>\n");
      out.write("                        <th>Update Fines</th>\n");
      out.write("                        <th></th>\n");
      out.write("                    </tr>\n");
      out.write("                </thead>\n");
      out.write("                <tbody>\n");
      out.write("                    <tr>\n");
      out.write("                        <td>Update Fine table with todays Data</td>\n");
      out.write(
          "                        <td><input type=\"submit\" value=\"Update / View Fines\" name=\"SUBMIT\"/></td>\n");
      out.write("                    </tr>\n");
      out.write("                </tbody>\n");
      out.write("            </table>           \n");
      out.write("        </form>\n");
      out.write("        <h1>Check your Fines Here</h1>\n");
      out.write("        <form name=\"Fines\" action=\"Fines.jsp\">\n");
      out.write("            <table border=\"0\" width=\"3\" cellspacing=\"2\">\n");
      out.write("                <thead>\n");
      out.write("                    <tr>\n");
      out.write("                        <th>Get Fine Details</th>\n");
      out.write("                        <th></th>\n");
      out.write("                    </tr>\n");
      out.write("                </thead>\n");
      out.write("                <tbody>\n");
      out.write("                    <tr>\n");
      out.write("                        <td>Card No</td>\n");
      out.write(
          "                        <td><input type=\"text\" name=\"Card_no\" value=\"\"/></td>\n");
      out.write("                    </tr>\n");
      out.write("                    <tr>\n");
      out.write("                        <td></td>\n");
      out.write(
          "                        <td><input type=\"submit\" value=\"Get Fines\" name=\"SUBMIT\" /></td>\n");
      out.write("                    </tr>\n");
      out.write("                </tbody>\n");
      out.write("            </table>        \n");
      out.write("            ");

      Connection con = null;
      String[] selected_Checkboxes = request.getParameterValues("chk");
      PreparedStatement pst = null;
      ResultSet result = null;
      ResultSet resUpd = null;
      con =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/lbms_db?zeroDateTimeBehavior=convertToNull",
              "root",
              "admin12");
      String Card_no = request.getParameter("Card_no");
      String button = null;
      Date dt = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
      String current_date = sdf.format(dt);
      if (Card_no != null && selected_Checkboxes == null) {
        String selSql =
            "SELECT  l.card_no, SUM(f.fine_amt) AS total_fine, f.paid  "
                + "FROM book_loans l, fines f  "
                + "WHERE l.loan_id = f.loan_id AND "
                + "l.card_no = "
                + Card_no
                + " "
                + "GROUP BY l.card_no";
        pst = con.prepareStatement(selSql);
        result = pst.executeQuery();
        String box = null;
        String paid;
        String pay;
        Boolean chk = false;
        out.println("<table>");
        pay = "<form action='Fines.jsp'>";
        out.println(pay);
        out.println("<tr>");
        out.println("<th>Card No</th>");
        out.println("<th>Fine_Amt</th>");
        out.println("<th>Paid OR Not</th>");
        out.println("</tr>");
        while (result.next()) {
          chk = true;
          paid = "No";
          if (result.getBoolean("f.paid")) {
            paid = "Yes";
          }

          out.println("<tr>");
          out.println(
              "<td>"
                  + result.getInt("l.card_no")
                  + "</td><td>"
                  + result.getString("total_fine")
                  + "</td><td>"
                  + paid
                  + "</td>");
          out.print("<td>");
          box = "<input name='chk' value=" + result.getInt("l.card_no") + " type='checkbox'>";
          out.print(box);
          out.print("</td>");
          out.print("</tr>");
        }

        if (chk == true) {
          out.println("<tr>");
          out.print("<td>");
          button = "<input type='submit' value='Pay Fine' name='Pay'>";
          out.print(button);
          out.print("</td>");
          out.println("</tr>");
        } else {

          out.write(
              "<dialog open> <font color = 'green'>No Fine information. You owe nothing! Thank You</font> </dialog>");
        }
        out.println("</form>");
        out.println("</table>");
      } else if (selected_Checkboxes != null) {
        String sqlLoan = null;
        ResultSet resultLoan = null;
        String sqlUpdFine = null;
        PreparedStatement pstUpd = null;
        String sqlBook = null;
        ResultSet rsltBook = null;
        char chkouts = 'N';

        int length_chk = selected_Checkboxes.length;
        for (int i = 0; i < length_chk; i++) {
          // Check whether the Book is returned before paying the fine.
          sqlBook =
              "SELECT COUNT(loan_id) AS no_chkouts FROM book_loans WHERE card_no = "
                  + selected_Checkboxes[i]
                  + " AND date_in = '0000-00-00' AND due_date < "
                  + current_date
                  + "";
          pst = con.prepareStatement(sqlBook);
          rsltBook = pst.executeQuery();
          while (rsltBook.next()) {
            if (rsltBook.getInt("no_chkouts") > 0) {
              chkouts = 'Y';
            }
          }
          if (chkouts == 'Y') {

            out.write(
                "<dialog open> <font color = 'red'>You have outstanding due checkouts!. Please return the books and then Pay the fine</font> </dialog>");
          }
          // Get the corresponding loan_Ids for each customer from Fines table

          sqlLoan =
              "SELECT loan_id FROM book_loans WHERE card_no = "
                  + selected_Checkboxes[i]
                  + " AND date_in IS NOT NULL AND due_date < date_in";
          pst = con.prepareStatement(sqlLoan);
          resultLoan = pst.executeQuery();
          while (resultLoan.next()) {
            sqlUpdFine =
                "UPDATE fines SET paid = true WHERE loan_id = " + resultLoan.getInt("loan_id") + "";
            pstUpd = con.prepareStatement(sqlUpdFine);
            pstUpd.executeUpdate();
            out.println("Payment Updated Successfully");
          }
        }
      }

      out.write("\n");
      out.write("        </form>        \n");
      out.write("    </center>\n");
      out.write("</body>\n");
      out.write("</html>\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }