Slide Chương 12 Ptit
Slide Chương 12 Ptit
Slide Chương 12 Ptit
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Develop data access classes that use JDBC to provide all of the
methods that your servlets need to work with a database. 2. Develop
a utility class that allows you to get a connection from a connection
pool.
3. Develop servlets that use the methods of your data classes.
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 2
Objectives (continued)
Knowledge
1. Describe how a web application can use the DriverManager,
Connection, Statement, PreparedStatement, and ResultSet classes to
get data from a database.
2. Explain how prepared statements can improve the performance and
security of database operations.
3. Describe the use of a ResultSetMetaData object.
4. Explain how connection pooling can improve the performance of a
web application.
5. Describe O/R (object-relational) mapping.
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 3
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 5
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 6
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 8
ResultSet methods
for forward-only, read-only result sets
Method Description
next() Moves the cursor to the next row in the result set. last()
Moves the cursor to the last row in the result set. close()
Releases the result set’s resources. getRow() Returns an int value
that identifies the current row of the result set.
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 10
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 11
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 12
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 13
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 14
Update a row
String query = "UPDATE Product SET " +
"ProductCode = '" + product.getCode() + "', " +
"ProductDescription = '" + product.getDescription() + "', " +
"ProductPrice = '" + product.getPrice() + "' " +
"WHERE ProductCode = '" + product.getCode() + "'";
Statement statement = connection.createStatement();
int rowCount = statement.executeUpdate(query);
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 15
How to use the executeUpdate method to…(cont.)
Delete a row
String query = "DELETE FROM Product " +
"WHERE ProductCode = '" + productCode + "'"; Statement
statement = connection.createStatement();
int rowCount = statement.executeUpdate(query);
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 16
Warning
• If you build an SQL statement from user input and use a method
of the Statement object to execute that SQL statement, you may
be susceptible to an SQL injection attack.
• An SQL injection attack allows a hacker to bypass authentication
or execute SQL statements against your database that can read
data, modify data, or delete data.
• To prevent most types of SQL injection attacks, use prepared
statements.
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 17
To modify a row
String preparedSQL = "UPDATE Product SET "
+ " ProductCode = ?, "
+ " ProductDescription = ?, " + " ProductPrice
= ?"
+ "WHERE ProductCode = ?";
PreparedStatement ps =
connection.prepareStatement(preparedSQL); ps.setString(1,
product.getCode());
ps.setString(2, product.getDescription());
ps.setDouble(3, product.getPrice());
ps.setString(4, product.getCode());
ps.executeUpdate();
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 18
To delete a row
String preparedQuery = "DELETE FROM Product "
+ "WHERE ProductCode = ?";
PreparedStatement ps =
connection.prepareStatement(preparedQuery); ps.setString(1,
productCode);
ps.executeUpdate();
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 19
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 23
<p><b>SQL result:</b></p>
${sqlResult}
</body>
</html>
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 24
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 25
The SQLGatewayServlet class (continued)
// get a connection
String dbURL = "jdbc:mysql://localhost:3306/murach"; String
username = "murach_user";
String password = "sesame";
Connection connection = DriverManager.getConnection( dbURL,
username, password);
// create a statement
Statement statement = connection.createStatement();
if (sqlType.equalsIgnoreCase("select")) { // create
the HTML for the result set ResultSet resultSet
= statement.executeQuery(sqlStatement); sqlResult =
SQLUtil.getHtmlTable(resultSet); resultSet.close();
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 26
The SQLGatewayServlet class (continued)
} else {
int i = statement.executeUpdate(sqlStatement); if (i == 0) { //
a DDL statement
sqlResult =
"<p>The statement executed successfully.</p>"; } else { // an INSERT,
UPDATE, or DELETE statement sqlResult =
"<p>The statement executed successfully.<br>" + i + " row(s)
affected.</p>"; }
}
}
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
sqlResult = "<p>Error loading the database driver: <br>" +
e.getMessage() + "</p>";
} catch (SQLException e) {
sqlResult = "<p>Error executing the SQL statement: <br>" +
e.getMessage() + "</p>";
}
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 27
The SQLGatewayServlet class (continued)
HttpSession session = request.getSession();
session.setAttribute("sqlResult", sqlResult);
session.setAttribute("sqlStatement", sqlStatement);
Note
• The web.xml file for this application maps the
SQLGatewayServlet class to the /sqlGateway
URL.
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 28
import java.sql.*;
htmlTable.append("<table>");
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 29
htmlTable.append("</table>");
return htmlTable.toString();
}
}
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 30
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 31
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 33
A context.xml file
that configures a connection pool
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ch12email">
</Context>
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 34
A class that defines a connection
pool package murach.data;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource)
ic.lookup("java:/comp/env/jdbc/murach"); } catch
(NamingException e) {
System.out.println(e);
}
}
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 35
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 36
database pool.freeConnection(connection);
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 37
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 38
<label class="pad_top">Email:</label>
<input type="email" name="email" value="${user.email}"
required><br>
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 40
<label> </label>
<input type="submit" value="Join Now" class="margin_left">
</form>
</body>
</html>
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 41
import murach.business.User;
import murach.data.UserDB;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException { String
url = "/index.html";
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 42
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 43
The code for the servlet (continued)
// validate the parameters
if (UserDB.emailExists(user.getEmail())) { message = "This email
address already exists.<br>" + "Please enter another email
address."; url = "/index.jsp";
}
else {
message = "";
url = "/thanks.jsp";
UserDB.insert(user);
}
request.setAttribute("user", user);
request.setAttribute("message", message); }
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 44
The UserDB class
package murach.data;
import java.sql.*;
import murach.business.User;
String query
= "INSERT INTO User (Email, FirstName, LastName) " + "VALUES
(?, ?, ?)";
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 45
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 47
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 48
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 49
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 50
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 51
import java.sql.*;
public class DBUtil {
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 52
Murach's Java Servlets/JSP (3rd Ed.), C12 © 2014, Mike Murach & Associates, Inc. Slide 53