Assignment 4
Assignment 4
Objective
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/
userid = root, password <the password you used when installing MySQL>
Using Eclipse EE & Tomcat to create and test a dynamic web application
1
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse
<!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>
2
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse
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;
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();
}
}
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
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>
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
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
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(
DB_URL, USER, PASS);
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();
6
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse
// close connection
conn.close();
} catch (Exception e) {
// Handle errors
e.printStackTrace();
} // end try
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;
// 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";
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
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
11
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse
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.
<!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
-----------------------------------------------------------------
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;
-----------------------------------------------------------------
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;
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;
// 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";
14
CST363 Assignment 4 – dynamic java web app using Tomcat & Eclipse
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