Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Objective

• write a Java web application using Java EE servlet architecture.


• Use JDBC to connect to MySQL database.
• Use JDBC prepared statements to perform SQL select, insert, update, delete
• Process a JDBC result set that may have zero, one or many rows.

Software installation
• Install Java 1.8 jdk
• Download and install Tomcat V8.5
o https://tomcat.apache.org/download-80.cgi
• MySQL Connector jdbc jar file
o copy mysql-connector-java-8.0.13.jar from ilearn  to tomcat/lib directory.
• Download and unzip eclipse EE (Must be EE version)
o https://www.eclipse.org/downloads/packages/release/2019-06/r/eclipse-ide-
enterprise-java-developers

Online References

• http://www.mysqltutorial.org/mysql-jdbc-tutorial/

Have a userid and password for MySQL handy.

userid = root, password <the password you used when installing MySQL>

Using Eclipse EE & Tomcat to create and test a dynamic web application

1. new -> dynamic web application


2. specify a new runtime server Tom 8.5 and select the directory where Tomcat was installed
3. You can start and stop the server using eclipse panels and view the web server console.
4. When creating a new servlet, it will be necessary to restart the server for the new servlet to take
effect. Modifying an existing servlet does not require a server restart.

1
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Part 1: simple static html page


HTML consists of text to display on a browser window and tags that tell the browser how to format the
text.
A simple page consists of tags for <html>, <body>, headings <h1>, <h2>, paragraph <p>, and hyper link
<a>.

<!DOCTYPE html>
<html>
<body>
<h1>Welcome to my page!</h1>
<p>For information about html visit
<a href="https://www.w3.org/MarkUp/Guide/">David Raggett's Guide to
HTML</a>
</p>
<p>Also see
<a href="https://www.w3.org/MarkUp/Guide/Advanced.html">Advanced Guide
to HTML</a>
</p>
</body>
</html>

Enter the URL at your browser http://localhost:8080/firstapp/index.html

2
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Part 2: a simple dynamic page


The type of page we created in part 1 is a static html page. To create a more dynamic, interactive page we
to code a Java servlet class. The html content is created by the servlet rather than coming from a file.
This allows us to make the content dynamic.
package dw;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TimeServlet")
public class TimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html> <html> <body> <h1>Welcome to
my dynamic page!</h1> <p>");
String time = new java.util.Date().toString();
out.println("Current time: "+time);
out.println("</p> </body> </html>");
out.flush();
}
}

Enter the url at a browser http://localhost:8080/FirstApp/TimeServlet

If the page is not working, check for error messages in the tomcat console.

3
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Part 3: a dynamic page that uses an HTML form and SQL


Using mysql workbench, create the following table in a database. It will keep track of visitors to our web
page in a users table.
create table users (lastName varchar(35),
firstName varchar(35),
visitCount int,
primary key(lastname, firstName));

Create the HTML file. This is a form with entry fields that allow user to enter data. When the user
presses SUBMIT button, the request containing the entry field values is sent to the server and processed
by a servlet.
• action= specified the name of the servlet to call. This name become part of the URL.
• input tag specify entry fields for user to enter data
• input tag with type=”submit” creates the Submit button.

<!DOCTYPE html>
<html>
<body>
<form action = "VisitServlet" method = "POST">
First Name: <input type = "text" name = "first_name" />
<br/>
Last Name: <input type= "text" name = "last_name" />
<br/>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

Enter the url at a browser http://localhost:8080/FirstApp/visitform.html

When the user fills in the form and presses Submit, the browser goes a request with
url = http://localhost:8080/FirstApp/VisitServlet
the data from the user is in the message body of the http request as name:value pairs.

4
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

http request message body: “first_name=David&last_name=Wisneski”

Part 4: process form data with servlet


The process is
• retrieve the user data using request.getParameter( ) method
• register jdbc driver and get a database connection using database server URL and a MySQL
userid and password
• create a prepared statement using a string containing an sql statement with parameter markers (?)
• set the values of the parameter markers
• execute the query that returns a result set. in this example the result will either have zero or one
row. If there is no row this means this is the first time visitor.
• prepare an update or insert statement and call executeUpdate method. executeUpdate returns the
number of rows modified in the database. In this example it should be the value 1.
• write HTML to the response.

package dw;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/VisitServlet")
public class VisitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/WORLD";

// Database credentials
static final String USER = "root";
static final String PASS = "cst363SP2019";

// SQL statements
String sql = "SELECT visitCount from users where lastName=? and
firstName=?";
String usql = "UPDATE users SET visitCount=visitCount+1 WHERE
lastName=? and firstName=?";
String isql = "INSERT users (lastName, firstName, visitCount)
values (?, ?, 1) ";

5
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
PreparedStatement pstmt = null;
String msql;
int visitCount = 0;

// get user data


String last_name = request.getParameter("last_name");
String first_name = request.getParameter("first_name");

response.setContentType("text/html"); // Set response


content type
PrintWriter out = response.getWriter();

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
conn = DriverManager.getConnection(
DB_URL, USER, PASS);

// prepare sql select


pstmt = conn.prepareStatement(sql);
pstmt.setString(1, last_name);
pstmt.setString(2, first_name);
ResultSet rs = pstmt.executeQuery();

if (rs.next()) {
visitCount = rs.getInt("visitCount") + 1;
// returning visitor. do sql update
msql = usql;
} else {
// first time visitor. do sql insert
visitCount = 1;
msql = isql;
}
rs.close();
pstmt.close();

// now prepare and execute update or insert


// sql statement
pstmt = conn.prepareStatement(msql);
pstmt.setString(1, last_name);
pstmt.setString(2, first_name);

int nrows = pstmt.executeUpdate();


// nrows is number of rows updated
// should be 1

6
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

System.out.println("VisitServlet. nrows=" + nrows);

// close connection
conn.close();
} catch (Exception e) {
// Handle errors
e.printStackTrace();
} // end try

// return html and display visitCount


out.println("<!DOCTYPE HTML><html><body>");
out.println("<p>Thank you for visiting.</p>");
out.println("<p>This is visit number " + visitCount + ".</p>");
out.println("</body></html>");
out.flush();
}
}

Prevent sql-injection attacks: For security reasons to prevent against malicious web site attacks, it is
important to use prepared statements with parameters instead of using string concatenation to insert the
user entered values into an sql string.

7
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Part 5: servlet that return multiple rows using HTML table tag
The following servlet will return all rows in the users table.
<table> </table> mark the begin and end of the table.
<tr> </tr> mark begin and end of each row.
<th> </th> are for each column heading.
<td> </td> are for each column value.
For more information about table tags see https://www.w3schools.com/tags/tag_table.asp

@WebServlet("/TableServlet")
public class TableServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// JDBC driver name and database URL


static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/WORLD";

// Database credentials
static final String USER = "root";
static final String PASS = "cst363SP2019";

// SQL statements
String sql = "SELECT lastName, firstName, visitCount from users
order by lastName, firstName";

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

Connection conn = null;


PreparedStatement pstmt = null;

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
conn = DriverManager.getConnection(DB_URL,
USER, PASS);
// prepare sql select
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();

out.println("<!DOCTYPE HTML><html><body>");

8
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

out.println("<table>
<tr><th>LastName</th><th>FirstName</th> <th>VisitCount</th></tr>");
while (rs.next()) {
out.println("<tr>");

out.println("<td>"+rs.getString("lastName")+"</td>");

out.println("<td>"+rs.getString("firstName")+"</td>");

out.println("<td>"+rs.getInt("visitCount")+"</td>");
out.println("</tr>");
}
rs.close();
out.println("</table>");
out.println("</body></html>");

pstmt.close();
conn.close();
out.flush();
} catch (Exception e) {
// Handle errors
e.printStackTrace();
} // end try
}
}

Comments:
Some students with experience doing web application might ask
• Why don’t I use JSPs to create the HTML output instead of using out.print( ) statements?
• Why don’t I use HTML5 and CSS to create better looking page?
• Why don’t I use server framework like Hibernate or JPA that does all the SQL for you?
• Coding a userid and password in Java source code is not secure.
• Why don’t I use connection pooling?
These are all good and valid questions and if were a course in web app development we would discuss
these things. But the purpose of this course is to focus on SQL and how SQL is used in an application
program; in this case a Java application.
The objective of this assignment is for you to learn about JDBC, connections, prepared statements and
result sets.

9
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Part 6: Practice coding html forms and servlets


• this assignment uses the WORLD sample database for MySQL
• code an HTML form that allows a user to a partial name for a country.
• Using SQL LIKE predicate (or reqexp predicate) retrieve all counties whose name matches the
partial name. If the user enters ‘united’, all country whose name include the word ‘united’ would
be returned. Display the output as a html table.
• create a second form that allows user to enter a country code and a new value for population. The
servlet will update the country population value and display the code, name and new population
value for the country.
o html form parameters are always string values. But population in the database is int. you
will have to convert from string to int and use the int value to set the value in the
prepared statement.

Example of searching for countries with name that includes ‘sta’ and display of search result.

10
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

Example of form to update country population and result of successful update.

11
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

What to submit for this assignment? Submit 3 files.

1. A PDF file contains 4 screen shots like ones above. Form to search for country, search result,
form to enter population update, display of updated country population.

2. The java source code for the search servlet


a. retrieve the search value using request.getParameter( ) method
b. use a prepared SELECT statement that uses LIKE or REGEXP and a sql parameter
marker
c. set the value of parameter marker
d. uses html table tags to format the result set rows

3. The java source code for the population update servlet


a. You servlet should retrieve the 3 parameters from the request using request.getParameter
method and make any needed conversions to int values.
b. execute parameterized update sql statement and check that one row is updated.
c. execute parameterized select sql to retrieve updated row for the country code.
d. display the code, name and population values for the updated row.

Code for the Assignment:


index.html

<!DOCTYPE html>
<html>
<body>
<h1>Welcome to my page!</h1>
<p>For information about html visit
<a href="https://www.w3.org/MarkUp/Guide/">David Raggett's Guide to HTML</a> </p>
<p>Also see
<a href="https://www.w3.org/MarkUp/Guide/Advanced.html">Advanced Guide to HTML</a> </p>
</body>
</html>

-----------------------------------------------------------------

nameform.html

<!DOCTYPE html>
<html>
<body>
<form action = "NameServlet" method = "POST">
First Name: <input type = "text" name = "first_name" />
<br/>
Last Name: <input type= "text" name = "last_name" />
<br/>

12
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

<input type = "submit" value = "Submit" />


</form>
</body>
</html>

-----------------------------------------------------------------

visitform.html

<!DOCTYPE html>
<html>
<body>
<form action = "VisitServlet" method = "POST">
First Name: <input type = "text" name = "first_name" />
<br/>
Last Name: <input type= "text" name = "last_name" />
<br/>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

-----------------------------------------------------------------
TimeServelet.java

@WebServlet("/TimeServlet")
public class TimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html> <html> <body> <h1>Welcome to my dynamic
page!</h1> <p>");
String time = new java.util.Date().toString();
out.println("Current time: "+time);
out.println("</p> </body> </html>");
out.flush();
}
}

-----------------------------------------------------------------

13
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

NameServlet.java

@WebServlet("/NameServlet")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

String firstName = request.getParameter("first_name");


String lastName = request.getParameter("last_name");

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html> <html> <body> <h1>Welcome to my dynamic name
page!</h1>");
String time = new java.util.Date().toString();
out.println("<p>Current time: "+time+ "</p>");
out.println("<p>Last Name: "+lastName+"</p>");
out.println("<p>First Name: "+firstName+"</p>");
out.println("</body> </html>");
out.flush();
}
}

-----------------------------------------------------------------

TableServlet.java

@WebServlet("/TableServlet")
public class TableServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// JDBC driver name and database URL


static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/WORLD";

// Database credentials
static final String USER = "root";
static final String PASS = "cst363SP2019";

// SQL statements
String sql = "SELECT lastName, firstName, visitCount from users order by lastName,
firstName";

protected void doGet(HttpServletRequest request, HttpServletResponse response)

14
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse

throws ServletException, IOException {


Connection conn = null;
PreparedStatement pstmt = null;

response.setContentType("text/html"); // Set response content type


PrintWriter out = response.getWriter();

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// prepare sql select
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();

out.println("<!DOCTYPE HTML><html><body>");
out.println("<table> <tr><th>LastName</th><th>FirstName</th>
<th>VisitCount</th></tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>"+rs.getString("lastName")+"</td>");
out.println("<td>"+rs.getString("firstName")+"</td>");
out.println("<td>"+rs.getInt("visitCount")+"</td>");
out.println("</tr>");
}
rs.close();
out.println("</table>");
out.println("</body></html>");

pstmt.close();
conn.close();
out.flush();
} catch (Exception e) {
// Handle errors
e.printStackTrace();
} // end try
}
}

15

You might also like