0% found this document useful (0 votes)
40 views

Assignment V

This document outlines the implementation of a Java Servlet-based e-shop, detailing the setup of a MySQL database, Apache Tomcat server, and the creation of a client-side HTML form. It includes instructions for creating a database table, writing a servlet to handle client requests, and processing SQL queries to display book information. The document serves as a comprehensive guide for developing a 3-tier web application using Java Servlet technology.

Uploaded by

Sarvesh Varadkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Assignment V

This document outlines the implementation of a Java Servlet-based e-shop, detailing the setup of a MySQL database, Apache Tomcat server, and the creation of a client-side HTML form. It includes instructions for creating a database table, writing a servlet to handle client requests, and processing SQL queries to display book information. The document serves as a comprehensive guide for developing a 3-tier web application using Java Servlet technology.

Uploaded by

Sarvesh Varadkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Assignment-V

Title: Java Server-side Programming: A Java Servlet e-Shop Case Study

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.

A typical 3-tier client/server web database application consists of 5 components:


1. A HTTP Server (or commonly known as a Web Server), such as Apache HTTP Server,
Apache Tomcat Server, Microsoft Internet Information Server (IIS), Nginx, Google Web
Server (GWS), and etc..
2. A HTTP Client, commonly known as a Web Browser, such as FireFox, Chrome, MSIE,
Safari, and etc.
3. A Relational Database, such as MySQL, PostgreSQL, Oracle, IBM DB2, MS SQL
Server, MS Access, SAP SyBase, and etc.
4. Client-side program, running inside the browser, which sends request to the server and
receives server's response. Client-side program can be written in many technologies, e.g.,
HTML form, JavaScript, VBScript, and others.
5. Server-side program, running inside the HTTP server, which receives and processes
clients' requests. The server-side program extracts the query parameters submitted by the
client-side program and queries the database. Server-side program can also be written in
many ways, e.g., Java Servlet/JSP/JSF, ASP, PHP, Python, JavaScript, and others.
The client and server interact with each other by exchanging messages using a protocol called
HTTP (HyperText Transfer Protocol). HTTP is an asymmetric request-response protocol. A
client sends a request message to the server. The server processes the request and returns
a response message. In other words, in HTTP, the client pulls information from the server,
instead of server pushes information to the client. An HTTP server typically runs over TCP/IP,
with a server IP address and on a TCP port number. The default TCP port number for HTTP is
80.
A typical use case for a webapp is as follows:
1. A client issue an URL to request and download an HTML page containing an HTML
form (or other client-side programs).
2. The client enters the requested data into the form (such as search criteria), and submits
these query parameters back to a server-side program for processing.
3. The server-side program extracts the query parameters, performs the database query, and
returns the query results back to the requesting client.
4. The client displays the query results, and repeats the above steps for further request-
response exchange.
In this article, we shall build our webapp in Java and MySQL. We shall write our server-side
programs in Java servlets. We shall write our client-side programs in HTML forms.

2. Setting up the E-Shop's Database in MySQL


The first step in building our e-shop is to setup a database. We shall call our database
"ebookshop" which contains one table "books". The table "books" has 5
columns: id, title, author, price and qty. The id column is the primary key of the table.
Database: ebookshop
Table: books
+-------+----------------------------+---------------+---------+-------+
| id | title | author | price | qty |
| (INT) | (VARCHAR(50)) | (VARCHAR(50)) | (FLOAT) | (INT) |
+-------+----------------------------+---------------+---------+-------+
| 1001 | Java for dummies | Tan Ah Teck | 11.11 | 11 |
| 1002 | More Java for dummies | Tan Ah Teck | 22.22 | 22 |
| 1003 | More Java for more dummies | Mohammad Ali | 33.33 | 33 |
| 1004 | A Cup of Java | Kumar | 44.44 | 44 |
| 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 |
+-------+----------------------------+---------------+---------+-------+
MySQL
If you are new to MySQL, read "How to Set Up MySQL and Get Started".
Start the MySQL server. Take note of the server's TCP port number. I shall assume that MySQL
server is running on port 3306. The default TCP port number for MySQL server is 3306.

// For Windows: assume that MySQL is installed in "c:\myWebProject\mysql"


c:
cd \myWebProgram\mysql\bin
mysqld --console

// 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

// For macOS: assume that MySQL is installed in "/usr/local/mysql"


cd /usr/local/mysql/bin
./mysql -u myuser -p

You can run the following SQL script to set up the database:

create database if not exists ebookshop;

use ebookshop;

drop table if exists books;


create table books (
id int,
title varchar(50),
author varchar(50),
price float,
qty int,
primary key (id));

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);

select * from books;

3. Setting up HTTP Server with Apache Tomcat


Next, we have to setup an HTTP server to host our webapp. In this case study, we shall use
Apache Tomcat Server as our HTTP server. Read "How to install Apache Tomcat server". I
shall assume that our Tomcat is running in TCP port number 9999.

4. Setting up the E-Shop Webapp under Apache Tomcat


Step 1: Create the Directory Structure for a new Webapp "ebookshop"
First of all, choose a name for your webapp. In this case study, we shall call it "ebookshop".
Navigate to Tomcat's "webapps" sub-directory, and create the following directory structure:
1. Under Tomcat's "webapps" directory, create you web application root directory
"ebookshop".
2. Under "ebookshop", create a sub-directory "WEB-INF" (case sensitive, uppercase, a
dash not underscore).
3. Under "WEB-INF", create a sub-directory "classes" (case sensitive, lowercase, plural).
You need to keep your web resources in the proper directories:
1. "ebookshop": The is called the context root (or document base directory) of your
webapp. You should keep all your HTML files and resources visible to the web users
(e.g., CSS, images, scripts) here.
2. "ebookshop\WEB-INF": This directory, although under the context root, is not visible to
the web users. This is where you keep your application's configuration files "web.xml".
3. "ebookshop\WEB-INF\classes": This is where you keep all the Java source files and
classes.
Step 2: Start the Tomcat Server
To start the Tomcat server:
 For Windows: start a CMD shell and run the batch file "startup.bat" under Tomcat's "bin"
directory. Tomcat will be started in a new console window.
 For macOS and Linux: start a Terminal and run "./catalina.sh run"under Tomcat's "bin"
directory.
Monitor the Tomcat console, as the error messages, and output of System.out.println() from
your programs will be sent to this console. Observe the Tomcat's TCP port number.
.....
xxxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory
Deploying web application directory [xxx\webapps\ebookshop]
xxxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory
Deployment of web application directory [xxx\webapps\ebookshop] has finished in [188] ms
......
xxxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler
["http-nio-9999"]
xxxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-
nio-8009"]
xxxxxx INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 1927 ms
Step 3: Access the Tomcat Server
The Tomcat Server has been started on TCP port 9999. The default TCP port number for HTTP
protocol is 80. To access an HTTP server not running on the default TCP port 80, the port
number must be explicitly specified in the URL.
To access your Tomcat Server, start a web browser (e.g., FireFox, IE, Chrome or Safari) and
issue the following URL:

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.

Step 5: Shutting down the Tomcat Server .


To orderly shutdown the Tomcat web server, press control-c from the Tomcat's console; or run
the script "shutdown.bat" (Windows) or "./shutdown.sh" (macOS/Linux) under Tomcat's "bin"
directory.

5. Writing a Client-Side HTML Form


Let's write an HTML script to create a query form using checkboxes. Save the HTML file as
"querybook.html" in your application root directory "ebookshop".
<html>
<head>
<title>Yet Another e-Bookshop</title>
</head>
<body>
<h2>Yet Another e-Bookshop</h2>
<form method="get" action="http://localhost:9999/ebookshop/query">
Choose an author:<br /><br />
<input type="checkbox" name="author" value="Tan Ah Teck" />Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali" />Ali
<input type="checkbox" name="author" value="Kumar" />Kumar
<input type="submit" value="Search" />
</form>
</body>
</html>

Browse the HTML page by issuing the URL:

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 '+'.

6. Writing Database Query Servlet

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

// For macOS: Assume that Tomcat is installed in "~/myWebProject/tomcat"


cd ~/myWebProject/tomcat/webapps/ebookshop/WEB-INF/classes
// Need to use $HOME instead of ~ in the "javac" command
javac -cp .:$HOME/myWebProject/tomcat/lib/servlet-api.jar QueryServlet.java
Step 3: Test the Servlet
You can now try to invoke the servlet by issuing a request URL with proper query parameter:

http://localhost:9999/ebookshop/query?author=Tan+Ah+Teck

The request URL "/query" is mapped to the servlet "QueryServlet.class", as configured


via @WebServlet("/query"), as follows:
Try "View Source" (or "View Page Source") in your browser to study the output produced by
the servlet. It is important to note that the client has no access to the servlet's program codes,
but merely the outputs produced by the servlet.
<html>
<head><title>Query Results</title></head>
<body>
<h3>Thank you for your query.</h3>
<p>Your SQL statement: SELECT * FROM books WHERE author = 'Tan Ah Teck' AND qty
> 0 ORDER BY author ASC, title ASC</p>
<p>Tan Ah Teck, Java for dummies, $11.11</p>
<p>Tan Ah Teck, More Java for dummies, $22.22</p>
<p>==== 2 records found ====</p>
</body></html>

Step 5: Invoke the Servlet from the HTML Form


Use the HTML form that you have created earlier (i.e., "querybook.html") to trigger this
servlet. Take note that the request URL is coded in the <form>'s action attribute.

You might also like