Books
in black and white
Main menu
Share a book About us Home
Books
Biology Business Chemistry Computers Culture Economics Fiction Games Guide History Management Mathematical Medicine Mental Fitnes Physics Psychology Scince Sport Technics
Ads

More Java Pitfalls Share Reactor - Daconta M,C.

Daconta M,C. More Java Pitfalls Share Reactor - Wiley publishing, 2003. - 476 p.
ISBN: 0-471-23751-5
Download (direct link): morejavapitfallssharereactor2003.pdf
Previous << 1 .. 129 130 131 132 133 134 < 135 > 136 137 138 139 140 141 .. 166 >> Next

This pitfall explored how this misunderstanding can lead the developer into a real bind. By looking at how to solve this particular issue, the developer can gain insight on how each of the beans work behind the scenes and can gain a better appreciation of what is really happening in the container, since it serves as the intermediary in all EJB development.
Item 44: The Unprepared PreparedStatement
JDBC is one of the most popular APIs in the Java platform. Its power and ease of use combined with its easy integration in the Java Web application APIs has caused a proliferation of database-driven Web applications. The most popular of these Web applications is the classic HTML form driving a SQL query to present the data back to the user in HTML. Figure 44.1 is an example of one such Web application. Figure 44.2 shows the response.
3 http:rtclaysvaio/examples/SalaryServlet.html Microsoft Internet Explorer
File Edit View Favorites Tools Help c^end
-J-'Back w -> ? |S) ^Search Favorites #Media ^ J S
Address | http//claysvaio/eKemples/SalafyServle!html
Return nil employees with salaiies greater than
|2000
ISubmrtl Resel |
______^
Don# .oeal intranet
NOTE
Figure 44.1 Salary HTML form.
The Unprepared PreparedStatement 373
3 SalaryServlet - Microsoft Internet Explorer 13
J File Edit View Favorites Tools Help friend
-tJB&ek w ' ^ [_J ^Search .*] Favorites ^Medie J
Address |g) iittp://daysvaio/exainplesySataryServlei J
3
Employee
JONES
BLAKE
CLARK
SCOTT
KING
FORD
___d
Done gLetal intranet
Figure 44.2 HTML form results.
As we look at the code for this example, there are a few things to note. First, it is a very simplified example meant to show all the pieces together in one class. Second, this is an example of a servlet running in the Tomcat servlet container, connecting to an Oracle database. Listing 44.1 shows the code of the class.
01 import javax.servlet.*;
02 import javax.servlet.http.*;
03 import java.io.*;
04 import java.util.*;
05 import java.sql.*;
06
07 public class SalaryServlet extends HttpServlet {
08
09 Connection connection;
11
12 private static final String CONTENT_TYPE = "text/html";
13
14 public void init(ServletConfig config) throws ServletException {
15 super.init(config);
16
17 // Database config information
Listing 44.1 SalaryServlet (continued)
374 Item 44
18 String driver = "oracle.jdbc.driver.OracleDriver";
19 String url = "jdbc:oracle:thin:@joemama:1521:ORACLE";
20 String username = "scott";
21 String password = "tiger";
22
23 // Establish connection to database
24 try {
25 Class.forName(driver);
26 connection =
27 DriverManager.getConnection(url, username, password);
28
29 } catch(ClassNotFoundException cnfe) {
30 System.err.println("Error loading driver: " + cnfe);
31
32 } catch(SQLException sqle) {
33 sqle.printStackTrace();
34
35 }
36 }
37 /**Process the HTTP Post request*/
38 public void doPost(HttpServletRequest request, 2
HttpServletResponse response) throws ServletException, IOException {
39 response.setContentType(CONTENT_TYPE);
40
41 String salary = request.getParameter("salary");
42
43 String queryFormat =
44 "SELECT ename FROM emp WHERE sal > ";
45
46 try {
47
48 Statement statement = connection.createStatement();
49
50 ResultSet results =
51 statement.executeQuery(queryFormat + salary);
52
53 PrintWriter out = response.getWriter();
54 out.println("<html>");
55 out.println("<head><title>SalaryServlet</title></head>");
56 out.println("<body>");
57 out.println("<table>");
58 out.println("<tr>");
59 out.println("<td><b>Employee</b></td></tr>");
60
61 while (results.next()) {
62 out.println("<tr>");
63 out.println("<td>");
64 out.println(results.getString(1));
Listing 44.1 (continued)
The Unprepared PreparedStatement 375
65 out.println("</td>");
66 out.println("</tr>");
67 }
68
69 out.println("</table>");
70 out.println("</body></html>") ;
72 } catch ( SQLException sqle {
74 sqle.printStackTrace();
76 }
77
78 }
79 /**Clean up resources*/
80 public void destroy() {
82 connection.close();
84 }
85 }
86
Listing 44.1 (continued)
Notice that the init() method handles all of the database connection issues. Keep in mind that if this were going to be a production servlet, the connection handling and pooling would be delegated to another class (possibly another servlet). The doPost() method handles the building and execution of a JDBC statement from the connection, as well as the parsing of the resulting result set into HTML. Once again, best practice would cause this handling and presentation to be delegated elsewhere (usually a JSP), rather than building all of these out.println() statements to render the HTML.
This method is the most simplistic, but it clearly lacks efficiency. Essentially, a new String is constructed each time the user makes a request with the parameter appended to that String. What about precompiling the query so that only the parameter must be passed into the query? JDBC provides a method to do this, called the PreparedStatement. Listing 44.2 gives an example of the doPost() method rewritten to use a PreparedStatement.
Previous << 1 .. 129 130 131 132 133 134 < 135 > 136 137 138 139 140 141 .. 166 >> Next