Skip to content

Commit 30ae03e

Browse files
authored
Update IndexController.java
1 parent 21edf9a commit 30ae03e

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

src/main/java/com/github/hackathon/advancedsecurityjava/Controllers/IndexController.java

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import java.sql.Connection;
44
import java.sql.DriverManager;
5+
import java.sql.PreparedStatement;
56
import java.sql.ResultSet;
67
import java.sql.SQLException;
7-
import java.sql.Statement;
88
import java.util.ArrayList;
99
import java.util.List;
1010

@@ -28,31 +28,37 @@ public List<Book> getBooks(@RequestParam(name = "name", required = false) String
2828
@RequestParam(name = "read", required = false) Boolean bookread) {
2929
List<Book> books = new ArrayList<Book>();
3030

31-
Statement statement = null;
31+
PreparedStatement statement = null;
3232

3333
try {
3434
// Init connection to DB
3535
connection = DriverManager.getConnection(Application.connectionString);
3636

37-
statement = connection.createStatement();
38-
String query = null;
37+
String query = "SELECT * FROM Books WHERE 1=1";
38+
List<Object> parameters = new ArrayList<>();
3939

4040
if (bookname != null) {
41-
// Filter by book name
42-
query = "SELECT * FROM Books WHERE name LIKE '%" + bookname + "%'";
43-
} else if (bookauthor != null) {
44-
// Filter by book author
45-
query = "SELECT * FROM Books WHERE author LIKE '%" + bookauthor + "%'";
46-
} else if (bookread != null) {
47-
// Filter by if the book has been read or not
48-
Integer read = bookread ? 1 : 0;
49-
query = "SELECT * FROM Books WHERE read = '" + read.toString() + "'";
50-
} else {
51-
// All books
52-
query = "SELECT * FROM Books";
41+
query += " AND name LIKE ?";
42+
parameters.add("%" + bookname + "%");
5343
}
5444

55-
ResultSet results = statement.executeQuery(query);
45+
if (bookauthor != null) {
46+
query += " AND author LIKE ?";
47+
parameters.add("%" + bookauthor + "%");
48+
}
49+
50+
if (bookread != null) {
51+
query += " AND read = ?";
52+
parameters.add(bookread ? 1 : 0);
53+
}
54+
55+
statement = connection.prepareStatement(query);
56+
57+
for (int i = 0; i < parameters.size(); i++) {
58+
statement.setObject(i + 1, parameters.get(i));
59+
}
60+
61+
ResultSet results = statement.executeQuery();
5662

5763
while (results.next()) {
5864
Book book = new Book(results.getString("name"), results.getString("author"), (results.getInt("read") == 1));
@@ -76,4 +82,4 @@ public List<Book> getBooks(@RequestParam(name = "name", required = false) String
7682
}
7783
return books;
7884
}
79-
}
85+
}

0 commit comments

Comments
 (0)