חלקPart 7: Java בעולם האמיתיJava in the real world
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
JDBC ו-HttpClientJDBC & HttpClient
מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.
A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.
הנקודות החשובותKey points
- JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
- SQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (
' OR '1'='1).SQL injection: When user input is glued into an SQL string, the input can change the query (' OR '1'='1). - חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
- כל ערך נכנס דרך
?ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through?andsetString/setInt, never by gluing strings. - כדי להריץ באמת, התוכנית מרימה שרת HTTP קטן על המחשב עצמו (
HttpServerמה-JDK), ואז שולחת אליו בקשות עם HttpClient.To really run, the program starts a tiny HTTP server on the machine itself (HttpServerfrom the JDK), then sends it requests with HttpClient. - הפלט אמיתי מזמן הבנייה.The output is real, from build time.
mainמדבר רק עםBookRepository.maintalks only toBookRepository.- היום המימוש בזיכרון; מחר
JdbcBookRepositoryעם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow aJdbcBookRepositorywith the code from the first refresher, without changing a line of main. - מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository
מונחיםTerms
- JDBCJDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:
DriverManager.getConnection,PreparedStatement,ResultSet. כל מסד (PostgreSQL, MySQL, H2) מגיע עם driver משלו.Java's standard way to talk to a database:DriverManager.getConnection,PreparedStatement,ResultSet. Each database (PostgreSQL, MySQL, H2) comes with its own driver. - SQL injectionSQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (
' OR '1'='1). פרמטרים (?) שולחים את הקלט בנפרד, כנתון ולא כקוד.When user input is glued into an SQL string, the input can change the query (' OR '1'='1). Parameters (?) send the input separately, as data and not as code. - RepositoryRepository: interface שמסתיר איפה הנתונים נשמרים (
save,findByAuthor). מימוש אחד מדבר עם מסד נתונים, ואחר שומר בזיכרון לבדיקות.An interface hiding where data is kept (save,findByAuthor). One implementation talks to a database, another keeps it in memory for tests. - HttpClientHttpClient:
HttpClient.newHttpClient()ו-client.send(request, BodyHandlers.ofString()): שולח בקשת HTTP ומחזירHttpResponseעםstatusCode(),headers()ו-body().HttpClient.newHttpClient()andclient.send(request, BodyHandlers.ofString()): sends an HTTP request and returns anHttpResponsewithstatusCode(),headers()andbody(). - קוד סטטוסstatus code: מספר בתשובת HTTP: 200 הצליח, 201 נוצר, 400 בקשה שגויה, 404 לא נמצא, 500 שגיאת שרת.A number in an HTTP response: 200 OK, 201 created, 400 bad request, 404 not found, 500 server error.
- JDBCJDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:
DriverManager.getConnection,PreparedStatement,ResultSet. כל מסד (PostgreSQL, MySQL, H2) מגיע עם driver משלו.Java's standard way to talk to a database:DriverManager.getConnection,PreparedStatement,ResultSet. Each database (PostgreSQL, MySQL, H2) comes with its own driver. - SQL injectionSQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (
' OR '1'='1). פרמטרים (?) שולחים את הקלט בנפרד, כנתון ולא כקוד.When user input is glued into an SQL string, the input can change the query (' OR '1'='1). Parameters (?) send the input separately, as data and not as code. - RepositoryRepository: interface שמסתיר איפה הנתונים נשמרים (
save,findByAuthor). מימוש אחד מדבר עם מסד נתונים, ואחר שומר בזיכרון לבדיקות.An interface hiding where data is kept (save,findByAuthor). One implementation talks to a database, another keeps it in memory for tests. - HttpClientHttpClient:
HttpClient.newHttpClient()ו-client.send(request, BodyHandlers.ofString()): שולח בקשת HTTP ומחזירHttpResponseעםstatusCode(),headers()ו-body().HttpClient.newHttpClient()andclient.send(request, BodyHandlers.ofString()): sends an HTTP request and returns anHttpResponsewithstatusCode(),headers()andbody(). - קוד סטטוסstatus code: מספר בתשובת HTTP: 200 הצליח, 201 נוצר, 400 בקשה שגויה, 404 לא נמצא, 500 שגיאת שרת.A number in an HTTP response: 200 OK, 201 created, 400 bad request, 404 not found, 500 server error.
Cheatsheet
JDBC עם PreparedStatementJDBC with PreparedStatement
try (Connection db = DriverManager.getConnection("jdbc:h2:mem:shelf")) {
db.createStatement().execute("CREATE TABLE book (title VARCHAR(100), author VARCHAR(100), year INT)");
try (PreparedStatement insert = db.prepareStatement("INSERT INTO book VALUES (?, ?, ?)")) {
insert.setString(1, "Dune");
insert.setString(2, "Herbert");
insert.setInt(3, 1965);
insert.executeUpdate();
}
try (PreparedStatement q = db.prepareStatement("SELECT title, year FROM book WHERE author = ?")) {
q.setString(1, "Herbert");HttpClient מול שרת קטןHttpClient against a tiny server
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/books/1", ex -> {
byte[] body = "{\"title\": \"Dune\", \"year\": 1965}".getBytes();
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort();Repository: הנתונים מאחורי interfaceRepository: data behind an interface
BookRepository repo = new InMemoryBookRepository();
repo.save(new Book("Emma", "Austen", 1815));
repo.save(new Book("Dune", "Herbert", 1965));
repo.save(new Book("Persuasion", "Austen", 1817));
System.out.println(repo.findByAuthor("Austen"));
System.out.println(repo.findByTitle("Hamlet").isPresent());שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|