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 .. 96 97 98 99 100 101 < 102 > 103 104 105 106 107 108 .. 166 >> Next

Listing 31.2 (continued)
278 Item 31
068 * @param userid the userid of the accessing user
069 */
070 private void putInUserData(PrintWriter out,
071 String userid)
072 throws IOException
073 {
074 BufferedReader br = null;
075 String fn = userid + ".html";
076 String htmlfile =
077 getServletContext().getRealPath(fn);
078
079 System.out.println("debug: Trying to open "
080 + htmlfile);
081
082 File htmlSnippetFile = new File(htmlfile);
083 try
084 {
085 String line;
086
087 //Check to see if it exists first
088 if (!htmlSnippetFile.exists())
089 {
090 out.println("File " + fn + "not found!");
091 return;
092 }
093
094 br = new BufferedReader(new FileReader(htmlfile));
095
096 /*
097 * Now, let's read it..
098 * Since finding the bad behavior in this pitfall
099 * revolves around timing, we will only read 2
100 * characters at a time so that the bad behavior
101 * can be more easily seen.
102 */
103
104 char[] buffer = new char[2];
105 int count = 0;
106 do
107 {
108 out.write(buffer, 0, count);
109 out.flush();
110 count = br.read(buffer, 0, buffer.length);
111 }
112 while (count != -1);
113 }
114 catch (Exception e)
115 {
116 out.println(
Listing 31.2 (continued)
Design Flaws with Creating Database Connections within Servlets 279
117 "Error in reading file!!"
118 );
119 e.printStackTrace(System.err);
120 }
121 finally
122 {
123 if (br != null)
124 br.close();
125 }
126
127 }
128 }
129
130
Listing 31.2 (continued)
Now that we have eliminated instance variables in Listing 31.2, we have fixed our problems with thread safety! Be hesitant in using instance variables in servlets. If there is a better way, do it.
Item 32: Design Flaws with Creating Database Connections within Servlets
Connecting to a database is a convenient way for generating Web content. That being said, there can be many performance issues with creating database connections in servlets. It is imperative that a Web-enabled application be able to scale to the demand of its users. For that reason, preparation for a large amount of users is a necessity.
We will present a sample scenario where we are developing a Java Servlet-based system for a local shop, "Lavender Fields Farm." The decision makers on the project have decided that we will need to use a database for the online purchases and transactions. At the same time, we will need to use that database to keep track of inventory. This example will focus on the development of that "inventory servlet."
Listing 32.1 shows a servlet that queries the database to show inventory. In lines 52 to 75, in the servlet's doPost() method, we establish a connection to the database, and we create an HTML table showing the name of each item available, the description, and the amount that the shop has in stock. Figure 32.1 shows a screen capture of the result. In testing, everything with this example works wonderfully. When many users begin to use the system, the database becomes a bottleneck. Finally, after intense usage of the Web application, the database begins refusing new connections. What happened?
280 Item 32
01 package org.javapitfalls.item32;
02 import java.io.*;
03 import java.sql.*;
04 import java.text.*;
05 import java.util.*;
06 import javax.servlet.*;
07 import javax.servlet.http.*;
08 public class BadQueryServlet extends HttpServlet
09 {
10 /**
11 * simply forwards all to doPost()
12 */
13 public void doGet(HttpServletRequest request,
14 HttpServletResponse response)
15 throws IOException, ServletException
16 {
17 doPost(request,response);
18 }
19
20 /**
21 * The main form!
22 */
23 public void doPost(HttpServletRequest request,
24 HttpServletResponse response)
25 throws IOException, ServletException
26 {
27 Printwriter out = response.getWriter();
28 out.println("<TITLE>Internal Inventory Check</TITLE>");
29 out.println("<BODY BGCOLOR='white'>");
30 out.println("<H1>Lavender Fields Farm Internal Inventory</H1>");
31
32 //show the date.
33 SimpleDateFormat sdf =
34 new SimpleDateFormat ("EEE, MMM d, yyyy h:mm a");
35 java.util.Date newdate = new
36 java.util.Date(Calendar.getInstance().getTime().getTime());
37 String datestring = sdf.format(newdate);
38
39 out.println("<H3>Inventory as of: " + datestring + "</H3>");
40
41 out.println("<TABLE BORDER=1>");
42 out.println("<TR><TD BGCOLOR='yellow'><B><CENTER>Name</CENTER>"+
43 "</B></TD><TD BGCOLOR='yellow'><B><CENTER>" +
44 "Description</CENTER></B></TD><TD BGCOLOR='yellow'>" +
45 "<B><CENTER>Inventory Amount</CENTER></B></TD></TR>");
46
47 //Load the inventory from the database.
48
49 try
50 {
Listing 32.1 Specifying connection in a servlet
Design Flaws with Creating Database Connections within Servlets 281
51
52 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
53 String connect = "jdbc:odbc:Lavender";
54
55 Connection con = DriverManager.getConnection(connect);
56
57 Statement stmt = con.createStatement();
Previous << 1 .. 96 97 98 99 100 101 < 102 > 103 104 105 106 107 108 .. 166 >> Next