Assignment V
Assignment V
Problem Statement: Implement the sample program demonstrating the use of Servlet.
e.g., Create a database table ebookshop (book_id, book_title, book_author, book_price,
quantity) using database like Oracle/MySQL etc. and display (use SQL select query) the table
content using servlet.
1. Introduction
In this case study, we shall develop an e-shop based on the Java Servlet Technology. This e-
shop is a typical Internet business-to-consumer (B2C) 3-tier client/server database application,
as illustrated below.
// For macOS
// Use graphical control at "System Preferences" -> MySQL
Start a MySQL client. I shall also assume that there is an authorized user called "myuser" with
password "xxxx".
// For Windows: assume that MySQL is installed in "c:\myWebProject\mysql"
c:
cd \myWebProject\mysql\bin
mysql -u myuser -p
You can run the following SQL script to set up the database:
use ebookshop;
insert into books values (1001, 'Java for dummies', 'Tan Ah Teck', 11.11, 11);
insert into books values (1002, 'More Java for dummies', 'Tan Ah Teck', 22.22, 22);
insert into books values (1003, 'More Java for more dummies', 'Mohammad Ali', 33.33, 33);
insert into books values (1004, 'A Cup of Java', 'Kumar', 44.44, 44);
insert into books values (1005, 'A Teaspoon of Java', 'Kevin Jones', 55.55, 55);
http://localhost:9999
The "localhost" is a special hostname (with IP address of 127.0.0.1) meant for local loop-
back testing.
You could also use the IP address to access your HTTP server. You can find out your IP address
by running program such as "ipconfig", "winipcfg" (Windows), "ifconfig" (macOS/Linux), and
etc.
You shall see the welcome page of Tomcat Server.
http://localhost:9999/ebookshop/querybook.html
Check a box (e.g., Ah Teck) and click the "Search" button. A request will be issued to the URL
specified in the <form>'s action attribute. You are expected to receive an Error "404 Page Not
Found" at this stage as you have yet to write the server-side program (i.e., "query").
But observe the URL generated:
The query parameter, in the form of name=value pair, are extracted from the <input> tag
(e.g., author=Tan+Ah+Tack). It is appended behind the URL, separated by a '?'.
Check two boxes (e.g., "Ah Teck" and "Ali") and submit the request, the URL is:
http://localhost:9999/ebookshop/query?author=Tan+Ah+Teck&author=Mohammad+Ali
Two name=value pairs are sent to the server, separated by an '&'.
Also take note that blank is replaced by '+'. This is because special characters are not permitted
in the URL. They are encoded as %xx where xx is the hex code in ASCII. For example, '~' is
encoded as %7e; blank is encoded as %20 or '+'.
The next step is to write the server-side program, which responses to the client's request by
querying the database and returns the query results. We shall use Java servlet technology in our
servlet-side programming.
6.1 Java Database Programming
The steps involved in Java database programs are:
1. Allocate a Connection object.
2. Allocate a Statement object, under the Connection object created.
3. Query database:
a. Execute a SQL SELECT query by calling the executeQuery() method of
the Statement object, which returns the query results in a ResultSet object; or
b. Execute a SQL INSERT|UPDATE|DELETE command by calling
the executeUpdate() method of the Statement object, which returns
an int indicating the number of rows affected.
4. Process the query result.
5. Free the resources by closing the Statement and Connection.
6.2 Database Servlet
Let write a servlet that queries the database based on the client's request.
Step 1: Write the Servlet "QueryServlet.java"
Enter the following codes and save as "QueryServlet.java" under your web application
"classes" directory, i.e., "ebookshop\WEB-INF\classes\". You must keep all your servlets
in "ebookshop\WEB-INF\classes", because that is where Tomcat picks up the servlets.
1 // To save as "ebookshop\WEB-INF\classes\QueryServlet.java".
2 import java.io.*;
3 import java.sql.*;
4 import jakarta.servlet.*; // Tomcat 10
5 import jakarta.servlet.http.*;
6 import jakarta.servlet.annotation.*;
7 //import javax.servlet.*; // Tomcat 9
8 //import javax.servlet.http.*;
9 //import javax.servlet.annotation.*;
10
11 @WebServlet("/query") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards)
12 public class QueryServlet extends HttpServlet {
13
14 // The doGet() runs once per HTTP GET request to this servlet.
15 @Override
16 public void doGet(HttpServletRequest request, HttpServletResponse response)
17 throws ServletException, IOException {
18 // Set the MIME type for the response message
19 response.setContentType("text/html");
20 // Get a output writer to write the response message into the network socket
21 PrintWriter out = response.getWriter();
22 // Print an HTML page as the output of the query
23 out.println("<html>");
24 out.println("<head><title>Query Response</title></head>");
25 out.println("<body>");
26
27 try (
28 // Step 1: Allocate a database 'Connection' object
29 Connection conn = DriverManager.getConnection(
30 "jdbc:mysql://localhost:3306/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&s
31 "myuser", "xxxx"); // For MySQL
32 // The format is: "jdbc:mysql://hostname:port/databaseName", "username", "password"
33
34 // Step 2: Allocate a 'Statement' object in the Connection
35 Statement stmt = conn.createStatement();
36 ){
37 // Step 3: Execute a SQL SELECT query
38 String sqlStr = "select * from books where author = "
39 + "'" + request.getParameter("author") + "'" // Single-quote SQL string
40 + " and qty > 0 order by price desc";
41
42 out.println("<h3>Thank you for your query.</h3>");
43 out.println("<p>Your SQL statement is: " + sqlStr + "</p>"); // Echo for debugging
44 ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
45
46 // Step 4: Process the query result set
47 int count = 0;
48 while(rset.next()) {
49 // Print a paragraph <p>...</p> for each record
50 out.println("<p>" + rset.getString("author")
51 + ", " + rset.getString("title")
52 + ", $" + rset.getDouble("price") + "</p>");
53 count++;
54 }
55 out.println("<p>==== " + count + " records found =====</p>");
56 } catch(Exception ex) {
57 out.println("<p>Error: " + ex.getMessage() + "</p>");
58 out.println("<p>Check Tomcat console for details.</p>");
59 ex.printStackTrace();
60 } // Step 5: Close conn and stmt - Done automatically by try-with-resources (JDK 7)
61
62 out.println("</body></html>");
63 out.close();
64 }
65 }
Recall that the HTML form that we created earlier submits query parameters in the form
of name=value pairs, (e.g., author=Tan+Ah+Teck), as part of the request. In the processing
servlet, we need to extract the author name (e.g., "Tan Ah Teck") from the request to form a
SQL SELECT query (e.g., SELECT * FROM books WHERE author='Tan Ah Teck'). This is
done via the method request.getParameter(name), which returns the value of
the name=value pair.
For example, suppose that the URL is:
http://localhost:9999/ebookshop/query?author=Tan+Ah+Teck
The method request.getParameter("author") returns a String "Tan Ah Teck". The
resultant sqlStr becomes:
SELECT * FROM books WHERE author='Tan Ah Teck' AND qty > 0 ORDER BY author
ASC, title ASC
Note that you do not have to handle encoded characters such as '+', %20, '?' and '&'. They will
be properly decoded by the getParameter() method.
Step 2: Compile
Compile the source code "QueryServlet.java" into "QueryServlet.class".
// For Windows: Assume that Tomcat is installed in "c:\myWebProject\tomcat"
c:
cd \myWebProject\tomcat\webapps\ebookshop\WEB-INF\classes
javac -cp .;c:\myWebProject\tomcat\lib\servlet-api.jar QueryServlet.java
http://localhost:9999/ebookshop/query?author=Tan+Ah+Teck