Kontroler

Tutaj umieściłem połączenie z serwerem WWW. W tej chwili nie działa, wydaje się, że wymaga sporo debugowania, ponieważ nie powiedziano mi o tym zbyt wiele, walczę z kontekstem.


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * where the methods {@menuOptions} {@code} are run from 
 * @Jennifer Walsh 
 */

public class Controller {

    public static void main(String[] args) throws IOException, SQLException, Exception {
        menuOptions(); 

        try {       
            HttpServer server = HttpServer.create(new InetSocketAddress(8005), 0);

            server.createContext("/", new HttpHandler()); {

            @Override
            public void handle (HttpExchange he) throws IOException {
                final String head = "<html><head></>head><table><tr><th>Book ID</th><th>Title</th<</tr>"; 
                final String foot = "</table></body><html>";
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(he.getResponseBody()));

                ArrayList<Books>bookList = booksDAO.getAllBooks();  // need to get correct class etc

            he.sendResponseHeaders(200,0); //send 200 OK Http status code
            out.write(head);

            for (Books b:bookList)  {
                out.write(
                "<tr><td>" +c.getBook_id()+ 
                "</td><td>" c.getTitle()
                "</td><td>" + b. getAuthor()
                + "</td><td>" + b.getYear ()
                + "</td><td>" + b.getEdition()
                + "</td><td>" + b.getPublisher()
                + "</td><td>" + b.getIsbn()
                + "</td><td>" + b.getCondition()
                + "</td><td>" + b.getPrice()
                + "</td><td>" + b.getNotes()+"</td></tr>" 
                );
    } // end for loop 


} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}
} ); 
// POST operation 
server.createContext("/post",new HttpHandler() { 
    @Override
    public void handle (HttpExchange he) throws IOException {
        // Output HTML form
        he.sendResponseHeaders(200, 0);
        //BufferedWriter out = new BufferedWriter (new OutputStreamWriter(he.getRequestBody()));
        BufferedWriter out = new BufferedWriter (new OutputStreamWriter(he.getResponseBody()));  // copied from above but should be line 63
        out.write("<html><head></head><body><form method=\"POST\" action=\"/add_write\">" );
        out.write("ID:<input ID=\"ID\">br>");
        out.write("Title:<input title=\"Title\">br>");
        out.write("Author:<input Author=\"Author\">br>");
        out.write("Year:<input year=\"year\">br>");
        out.write("Edition:<input edition=\"Edition\">br>");
        out.write("Publisher:<input publisher=\"Publisher\">br>");
        out.write("ISBN:<input isbn=\"ISBN\">br>");
        out.write("Cover:<input cover=\"Cover\">br>");
        out.write("Condition:<input condition=\"Condition\">br>");
        out.write("Price:<input price=\"Price\">br>");
        out.write("Notes:<input notes=\"Notes\">br>");
        out.write("<input type=\"Submit\">");
        out.write("</form></body></html>");
        out.close();                    
    } // ends IOException               
}); // http handler 


server.createContext("/add_write", new HttpHandler () { 
    //process data from the added form
    @Override
    public void handle(HttpExchange he) throws IOException {
        HashMap<String, String> post = new HashMap<String,String>();
        //read the request body 
        BufferedReader in = new BufferedReader(new InputStreamReader(he.getRequestBody())); 
        String line = ""; 
        String request = "";
        while ((line = in.readLine()) != null) {
            request = request + line; 
                                                }
        // individual key=value pairs are delimited by ampersands
        String[] pairs = request.split("&");

        for (int i=0;i < pairs.length;i++) {
            //each key=value pair is separated by equals, and both halves require URL decoding
            String pair = pairs[i];
            post.put(URLDecoder.decode(pair.split("=")[0],"UTF-8"), URLDecoder.decode(pair.split("=")[0])); 
                                        }


        // should have HashMap of posted data in our "post" variable
        Books c; 
        c= new Books (post.get("book_id"),post.get("title"), post.get("author"), post.get("year"), 
                    post.get("edition"), post.get("publisher"), post.get("isbn"), 
                    post.get("cover"), post.get("condition"),post.get("price"),
                    post.get("notes")); 


        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(he.getResponseBody()));
        try { 
            booksDAO.insertBookW(c); 
            he.sendResponseHeaders(200, 0);
            out.write("Success");
            }

        catch (SQLException se) {
            he.sendResponseHeaders(500, 0);
            out.write("Error Adding Contact");
                                }
    }
} 
); */
            ); 

            }   


/* Method - menuOptions 
 * Switch clause to enable user to make choices. 
 * 
 */

public static void menuOptions ()throws SQLException {

    /*ArrayList to store allBooks 
     * returnedBook to store relevant ID
     */
    ArrayList <Books> allBooks = new ArrayList <Books> ();
    Books returnedBook;                 

    System.out.println ("Welcome! ");
    System.out.println ("------------------------------------------------------");
    System.out.println ("You have found Jenny's Book Management System");
    System.out.println ("-------------------------------------------------------");
    System.out.println ("Please enter your username: ");
    System.out.println("-------------------------------------------------------");
    System.out.println("Please enter your password:  ");
    System.out.println("-------------------------------------------------------");

    while (true) {

    System.out.println ("What would you like to do today?");
    System.out.println ("1 - Retrieve all books.");
    System.out.println ("2 - Search for a book.");
    System.out.println ("3 - Insert new book into the database.");
    System.out.println ("4 - Update existing book price details.");
    System.out.println ("5 - Delete books from the database.");
    System.out.println ("6 - Exit. ");

    System.out.println ("Press to make your choice: ");
    Scanner input = new Scanner(System.in); 
    int choice = input.nextInt();

    switch(choice) {
      /*switch to run each method 
       * break clause once done
       */ 

    case 1:

          allBooks = booksDAO.getAllBooks();                                    // retrieves all books 
                for (Books b : allBooks) {                                      // loop 

                    System.out.println ("---------------------------------");   
                    System.out.println (b); }                                   // return 
        break;                                  

      case 2:

            System.out.println ("Please enter the book ID you wish to search for: ");  // searches the database based on ID
            String searchBookID = input.nextLine();                                     // allocates to a variable 
            searchBookID = input.nextLine();            


            returnedBook = booksDAO.searchBookID(searchBookID);                 // takes the input from the user - accesses the database  
                                                                                // runs method, searching against the user input 
            System.out.println (returnedBook);                                  // returns it to the screen 

        break;

      case 3: 

          booksDAO.insertBook();                                                            // method  - insert a new book  
          System.out.println ("The book has been added to the database successfully.");     

          break;

      case 4:

            booksDAO.updateBookPrice();                                                     // method - update book price
            System.out.println("The books price has been updated on the database. ");      

          break;

      case 5:     

          System.out.println ("Please enter the book ID you would you like to delete:"); 

          // stores the user input 
          String deleteBookID = input.nextLine();
          deleteBookID = input.nextLine();
          // search the database based on book id

          boolean ans1=true;

          System.out.println(ans1);

            if (ans1) {
                System.out.println("The book has been found. "); 
            booksDAO.deleteBookID(deleteBookID); 

            }

            else
                System.out.println("The book cannot be found."); 
            break; 

      case 6: 
          // exit option 

          System.out.println ("Thank you. Goodbye!"); 

      default: 

          System.out.println ("You have not made a selection. Goodbye! "); 

          break;

    }
    }
}
} 

Books.java - gdzie mam wszystkie moje zmienne oraz metody pobierające i ustawiające

package sqlBooks;

import java.sql.SQLException;

/** Book class - all (11) variables set to string 
 *    constructors 
 *  stringToString 
 *  getters and setters 
 *  @author Jennifer Walsh 
 */

public class Books {
    private String book_id;   
    private String title;
    private String author;
    private String year;
    private String edition;
    private String publisher; 
    private String isbn; 
    private String cover; 
    private String condition; 
    private String price; 
    private String notes; 

    // constructors 
    public Books (String book_id, String title, String author, String year, String edition, 
            String publisher, String isbn,String cover, String condition, String price, String notes) {

        this.book_id=book_id; 
        this.title=title;
        this.author=author;
        this.year=year; 
        this.edition=edition; 
        this.publisher=publisher; 
        this.isbn=isbn; 
        this.cover=cover;
        this.condition=condition;
        this.price=price;
        this.notes=notes; 
}
        // Outputs sensibly on request 
    public String toString() { 
        String s = "Book_id: "+ this.book_id+ '\n' +
                "Title: "+ this.title+ '\n' + 
                "Author: " + this.author+ '\n' +
                "Year (released): "  + this.year + '\n' +
                "Edition: " + this.edition + '\n' + 
                "Publisher: " + this.publisher + '\n' +
                "ISBN: " + this.isbn + '\n' + 
                "Cover: " + this.condition + '\n' + 
                "Condition: " + this.cover + '\n' + 
                "Price: " + this.price + '\n' +
                "Notes: " + this.notes + '\n';

        return s;   

    }

    // getters and setters 

        public String getBook_id() {   
        return book_id;
    }

    public void setBook_id(String book_id) {
        this.book_id = book_id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getEdition() {
        return edition;
    }

    public void setEdition(String edition) {
        this.edition = edition;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getCover() {
        return cover;
    }

    public void setCover(String cover) {
        this.cover = cover;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }
}

BooksDAO Połączenie z bazą danych - działało, ale ponieważ się nie kompiluje (od dodania elementów serwera), nie wiem, czy nadal będzie działać.

package sqlBooks;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Scanner;

public class booksDAO {
    /** Class     
     *    
     * allocates variables and set to null 
     */
    static Connection c = null;      
    static Statement s = null;          
    ResultSet r = null;             

    /**
     * / Method to establish the Database connection
     * @return connection or NotFoundException when unsuccessful 
     */

       private static Connection getDBConnection() {     

              try { 
                    Class.forName("org.sqlite.JDBC");  // driver
                    c = DriverManager.getConnection("jdbc:sqlite:Booksdb.sqlite");              // driver manager imported above
                    s = c.createStatement();
              }
              catch (ClassNotFoundException e) { 
                  e.printStackTrace();
              }

              catch (SQLException e) {                                  // imported exception above
                     System.out.println(e.getMessage());
                     }
              return c;                                                 
       }

       public void closeConnection() {                              // method to close the connection 
           try {
               if(s!=null) {                                        // if s != to null, statement close
                   s.close ();
               }
               if (c!=null) {                                       // if connection !=null, 
               }

               } catch (SQLException e) {
                   e.printStackTrace();
           }
       }

/** Method to retrieve all books     
 * @return bookList 
 * @throws SQLException
 */

public static ArrayList<Books> getAllBooks() throws SQLException {

              System.out.println ("Retrieving all books ...");

              Connection dbconnection = null;               

              Statement statement = null;                   

              ResultSet result = null;                      

              String query = "Select * FROM books;";

              Books temp = null;                                // books object - set to null

              ArrayList <Books> bookList = new ArrayList <> ();         

              try {
                     dbconnection = getDBConnection ();  // Establish connection 

                     statement = dbconnection.createStatement(); 

                     System.out.println("DBQuery = " + query);  // Print out what the query to the database was 

                     result = statement.executeQuery(query);   

                     while (result.next()) {   

                           String book_id = result.getString("ID");  // Retrieves the String named "ID" from the database  

                           String title = result.getString("Title");

                           String author = result.getString ("Author");

                           String year = result.getString("Year");

                           String edition = result.getString("Edition");

                           String publisher = result.getString("Publisher");

                           String isbn = result.getString("ISBN");

                           String cover = result.getString("Cover");

                           String condition = result.getString ("Condition");

                           String price = result.getString("Price");

                           String notes = result.getString ("Notes");

                           bookList.add(new Books(book_id, title, author, year, edition,  

                           publisher, isbn,cover, condition, price, notes)); 

                           }     
                     }

              finally {
                  /**     If result is null, 
                     will not return anything and close the console.
                   */ 
                     if (result != null) { result.close(); }         

                     if (statement != null)     { statement.close(); }

                     if (dbconnection != null) { dbconnection.close(); }   

                           } return bookList;

              }

/** Method to search the database based on ID 
 *  @return foundBooks 
 * @throws SQLException
 */ 

public static Books searchBookID (String book_id) throws SQLException  {

       Books foundBooks;

       System.out.println ("Retrieving ...");

       Connection dbconnection = null; 

       Statement statement = null;     

       ResultSet result = null;        

       String query = "SELECT * FROM books WHERE ID =" + book_id + ";" ;

       System.out.println(query); 

       try {

              dbconnection = getDBConnection ();

              statement = dbconnection.createStatement();

              System.out.println("----------------------");

              result = statement.executeQuery(query);

              // Retrieving data from a SQL query, into a books type & initialising variables using the constructor

              foundBooks = new Books (result.getString ("ID"),      result.getString("Title"),          result.getString ("Author"),

              result.getString("Year"),                             result.getString("Edition"),        result.getString("Publisher") ,

              result.getString("ISBN"),                             result.getString("Cover"),          result.getString ("Condition"),

              result.getString("Price"),                            result.getString ("Notes"));
              }

       finally {

              if (result != null) { result.close(); } 

              if (statement != null)     { statement.close(); }

              if (dbconnection != null) { dbconnection.close(); }   

               }

       return foundBooks;
       }         

/** Method to delete a book based on ID  
 *    sql query includes conversion; string to int
 * @return
 * @throws SQLException
 */

public static boolean deleteBookID (String book_id) throws SQLException {

              System.out.println ("Deleting ...");

              Connection dbconnection = null; 

              Statement statement = null;     
              int result = 0;        

              String query = "DELETE FROM books WHERE ID =" + Integer.parseInt(book_id)+ ";" ; 

              try {

                     dbconnection = getDBConnection ();

                     statement = dbconnection.createStatement();

                     System.out.println("DBQuery = " + query);

                     result = statement.executeUpdate(query);
                     }

             finally {

                     if (statement != null)     { statement.close(); }

                     if (dbconnection != null) { dbconnection.close(); }   

                     }

            return true;
              }

/** Method to retrieve all the book details from the user + insert into the database 
 *    
 * @return String
 * @throws SQLException
 */

public static void insertBook() throws SQLException {  

              Connection dbconnection = null; 

              Statement statement = null;     

              int result = 0;        

              // Get book data from user 
              System.out.println ("Please input the ID for the book you would like to enter today: "); 
                Scanner input = new Scanner(System.in); 
                String bookID = input.nextLine();

                System.out.println ("Please input the title of the book you would like to enter today: "); 
                 String title = input.nextLine();

                System.out.println ("Please input the authors name of the book you would to enter today: "); 
                 String author = input.nextLine();

                System.out.println ("Please input the year the book was published: "); 
                 String year = input.nextLine();

                System.out.println ("Please input the edition of the the book you wish to enter:  "); 
                 String edition = input.nextLine();

                System.out.println ("Please input the name of the publisher of the book you would to enter today: "); 
                 String publishers = input.nextLine();

                System.out.println ("Please input the isbn of the book you would to enter today: "); 
                 String isbn = input.nextLine();

                System.out.println ("Please input the cover type of the book you would to enter today: "); 
                 String cover = input.nextLine();

                System.out.println ("Please input the condition of the book you would to enter today: "); 
                 String condition = input.nextLine();

                System.out.println ("Please input the price of the the book you wish to enter:  "); 
                 String price = input.nextLine();

                System.out.println ("Please input any notes regarding the book you would to enter today: "); 
                 String notes = input.nextLine();


              // add book to the database 

              String query = "INSERT INTO books VALUES ( "+Integer.parseInt(bookID)+ ","
                                                    + "'"+ title + "',"
                                                    + "'"+ author + "',"
                                                    +"'"+ year + "',"
                                                    +"'"+ edition + "',"
                                                    + "'"+ publishers + "',"
                                                    + "'"+isbn + "',"
                                                    + "'"+cover + "',"
                                                    + "'"+condition + "',"
                                                    + "'"+price + "'," 
                                                    + "'"+notes + "')"; 

              try {

                     dbconnection = getDBConnection ();

                     statement = dbconnection.createStatement();

                     System.out.println("DBQuery = " + query);

                     result = statement.executeUpdate(query);

                     System.out.println(result); 

                        }

              finally {

                  // if (result != null) { result.close(); } // If result is null, it will not return anything and close the console.

                     if (statement != null)     { statement.close(); }

                     if (dbconnection != null) { dbconnection.close(); }   

              } 
       }

// Insert Book into the web interface 

public static void insertBookW(Books newBook) throws SQLException {  

    Connection dbconnection = null; 

    Statement statement = null;     
    ResultSet result = null;       

    // add book into the database 

    String query = "INSERT INTO books ("+ "'" + newBook.getBook_id()+ "'," 
                                        +   "'" + newBook.getTitle()+ "'," 
                                        + "'" +  newBook.getAuthor() + "'," 

                                        + "'" + newBook.getYear() + "',"

                                        + "'"+newBook.getEdition() + "',"

                                        +   "'"+ newBook.getPublisher() + "',"

                                        +   "'" + newBook.getIsbn() + "',"

                                        +   "'" + newBook.getCover() + "',"

                                        +   "'" +newBook.getCondition() + "',"

                                        +   "'"+newBook.getPrice() + "',"

                                        +   "'"+ newBook.getNotes() + "';)";     





   System.out.println("^^^^^9"+ query);      
    try {

           dbconnection = getDBConnection ();

           statement = dbconnection.createStatement();

           System.out.println("DBQuery = " + query);

           result = statement.executeQuery(query);

           while (result.next()) {                      // execute SQL query

                 String book_id = result.getString("ID");  
          }
    }

    finally {

           if (result != null) { result.close(); }                  // If result is null, 
                                                                    //it will not return anything and close the console.

           if (statement != null)     { statement.close(); }

           if (dbconnection != null) { dbconnection.close(); }   

    } 
}
/** Method to to update book price details based on ID    
 *    
 * @return
 * @throws SQLException
 */


public static void updateBookPrice () throws SQLException {  

    Connection dbconnection = null;                 // connection variable

    Statement statement = null;                     // to allow us to do queries

    int result = 0;         



      System.out.println ("Please enter the book ID you would you like to update the pricing for: "); 
      Scanner userInput = new Scanner(System.in); 

    // stores the user input 
      String targetBook=userInput.next();


      // Retrieve updated info from user 
        System.out.println ("Please enter the books updated price: "); 
        String changeBookPrice = userInput.nextLine(); 
        changeBookPrice = userInput.nextLine();


        String query = "UPDATE books set price = '" + changeBookPrice + "' WHERE book_id= " + targetBook + ";";
        System.out.println(query);


        try {

            dbconnection = getDBConnection ();

            statement = dbconnection.createStatement();

            System.out.println("DBQuery = " + query);

            result = statement.executeUpdate(query);
            }

    finally {

            if (statement != null)     { statement.close(); }

            if (dbconnection != null) { dbconnection.close(); }   

            }


// Method to check log-in (User name & PW) details 

//public static void checkLogIn (String user_name, String password) {   // method - pass 2 parameters; strings
//
//       ArrayList<String> user_name = new ArrayList<String>();             // Create an array list called user_name, of type string
//
//       ArrayList<String> password = new ArrayList<String>();              // Create an array list called password, of type string
//
//       username.add("John");  // add to the array list - user_name
//
//       username.add("Cath");
//     
//       password.add("1234");  // add to the array list - password
//
//       password.add(("abcd"); 
//
//       System.out.println ("Please enter your user_name.");  //
//
//       Scanner reader = new Scanner(System.in);
//      
//       System.out.println ("Please enter your password.");
//
//       Scanner checker = new Scanner(System.in);
//    
//       if (username.contains( "****" ) & password.contains("*****")) {
//
//        System.out.println("Log-in successful.");
//
//    } else {
//
//        System.out.println("Your user_name or password is incorrect.");
//
//    }
//}
//         System.out.println ("Please enter your password.");
//     }



}} 


Przepraszamy za ogromną ilość wysłanego kodu.

0
Jenny 19 grudzień 2019, 18:06
Masz wybór między natywnym JDBC Javy a jednym z wielu odpowiednich bibliotek ORM (sugerowałbym Hibernację ORM). Jedyny moment, w którym sugerowałbym użycie surowego JDBC, to wtedy, gdy absolutnie 100 000% NIE MOŻNA dodać dodatkowych bibliotek, ponieważ cały dodatkowy boilerplate prawie nigdy nie jest tego wart.
 – 
cbryant02
19 grudzień 2019, 18:12
Nie możesz utworzyć instancji HttpHandler, ponieważ jest to abstract. Aby to zadziałało, potrzebujesz własnej implementacji.
 – 
Abhyudaya Sharma
19 grudzień 2019, 18:14
Niestety nie mam wyboru, ponieważ jest to zalecona praca uniwersytecka (krótki kurs programowania w języku Java) @cbryant02
 – 
Jenny
19 grudzień 2019, 18:17
- jakieś sugestie? Dosłownie powiedziano mi, że to jest kod, którego używamy i niewiele więcej poza tym powinienem mieć mgliste pojęcie o tym, co robi.
 – 
Jenny
19 grudzień 2019, 18:18
Kod jest zły. Zamień new HttpHandler() na new ShowHandler() i powinien się skompilować. Jeśli chodzi o kod bazy danych, sugerowałbym zapoznanie się ze wstępem do Oracle i/lub Baeldung do JDBC.
 – 
cbryant02
19 grudzień 2019, 18:25

1 odpowiedź