Java Database Programming Bible- P8

50 366 0
Java Database Programming Bible- P8

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 1 3:Using PreparedStatements and CallableStatements -350- <OPTION value=IL>Illinois</OPTION> <OPTION value=IN>Indiana</OPTION> <OPTION value=KS>Kansas</OPTION> <OPTION value=KY>Kentucky</OPTION> <OPTION value=LA>Louisiana</OPTION> <OPTION value=MA>Massachusetts</OPTION> <OPTION value=MB>Manitoba</OPTION> <OPTION value=MD>Maryland</OPTION> <OPTION value=ME>Maine</OPTION> <OPTION value=MI>Michigan</OPTION> <OPTION value=MN>Minnesota</OPTION> <OPTION value=MO>Missouri</OPTION> <OPTION value=MS>Mississippi</OPTION> <OPTION value=MT>Montana</OPTION> <OPTION value=NB>New Brunswick</OPTION> <OPTION value=NC>North Carolina</OPTION> <OPTION value=ND>North Dakota</OPTION> <OPTION value=NE>Nebraska</OPTION> <OPTION value=NF>Newfoundland</OPTION> <OPTION value=NH>New Hampshire</OPTION> <OPTION value=NJ>New Jersey</OPTION> <OPTION value=NM>New Mexico</OPTION> <OPTION value=NS>Nova Scotia</OPTION> <OPTION value=NT>Northwest Territories</OPTION> <OPTION value=NV>Nevada</OPTION> <OPTION value=NY>New York</OPTION> <OPTION value=OH>Ohio</OPTION> <OPTION value=OK>Oklahoma</OPTION> <OPTION value=ON>Ontario</OPTION> <OPTION value=OR>Oregon</OPTION> <OPTION value=PA>Pennsylvania</OPTION> <OPTION value=PE>Prince Edward Island</OPTION> <OPTION value=QC>Quebec</OPTION> <OPTION value=RI>Rhode Island</OPTION> <OPTION value=SC>South Carolina</OPTION> <OPTION value=SD>South Dakota</OPTION> <OPTION value=SK>Saskatchewan</OPTION> <OPTION value=TN>Tennessee</OPTION> <OPTION value=TX>Texas</OPTION> <OPTION value=UT>Utah</OPTION> <OPTION value=VA>Virginia</OPTION> <OPTION value=VT>Vermont</OPTION> <OPTION value=WA>Washington</OPTION> TEAMFLY Team-Fly ® Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -351 - <OPTION value=WI>Wisconsin</OPTION> <OPTION value=WV>West Virginia</OPTION> <OPTION value=WY>Wyoming</OPTION> <OPTION value=YK>Yukon</OPTION> </SELECT> </TD> <TD height=49 vAlign=bottom width=158> Zip/Postal code<BR><INPUT name=Zip size=15> </TD> </TR> </TBODY> </TABLE> </TD> </TR> <TR> <TD align=center> <BR/> <INPUT name=SubmitButton type=SUBMIT value="Click here to proceed"> <BR/> <P/> </TD> </TR> </TABLE> </TD> </TR> </TABLE> </FORM> </BODY> </HTML> After local validation by the JavaScript, the form data is passed to the JSP page ProcessNAForm.jsp, which uses the ProcessNABean to insert the form data into the database. ProcessNAForm.jsp is a simple example of a JSP form handler. It loads the ProcessNABean and sets its properties using the wild card property setter that relies on introspection to set all the properties of the JavaBean from the form data. When the insertData() method is called, ProcessNABean returns a boolean which is used to set the String nextPage to the appropriate handler. Finally, the <jsp:forward> tag is used to forward the user to the appropriate page. Listing 13-6 shows the JSP page. Listing 13-6: ProcessNAForm.jsp <%@ page language="java"%> <jsp:useBean id="ProcessNABean" class="JavaDatabaseBible.ch13.ProcessNABean" scope="session"/> <jsp:setProperty name="ProcessNABean" property="*"/> <% Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -352 - String nextPage = "MemberWelcome.jsp"; if(ProcessNABean.insertData()){ nextPage = "MemberProfile.jsp"; }else{ nextPage = "NewMemberForm.jsp"; } %> <jsp:forward page="<%=nextPage%>"/> Operation of the ProcessNABean The first part of the ProcessNABean is the collection of getter and setter methods required to access the bean's parameters. These must be supplied for the bean introspection that the JSP engine requires to work properly. The real work is done in the insertData() method. The ProcessNABean makes extensive use of a CallableStatement object, cs. First it calls the stored procedure GET_LOGIN_FOR_USER to validate the username against the Login table. If the username is already in use, the boolean flag username_selection_ok is set to false so that the JSP page can notify the user that he or she needs to select a different username. Once the user has selected a valid, unique username, the CallableStatement object is used to call the stored procedure SET_LOGIN_FOR_USER to update the Login table with the new username and password. The stored procedure SET_LOGIN_FOR_USER is defined as follows: CREATE PROCEDURE SET_LOGIN_FOR_USER @USERNAME VARCHAR(20), @PASSWORD VARCHAR(20) AS INSERT INTO LOGIN (USERNAME, PASSWORD) VALUES (@USERNAME, @PASSWORD); The stored procedure GET_LOGIN_FOR_USER is then called again to get the auto generated MemberID assigned to this user. A more elegant way to do this is to use the getGeneratedKeys() method defined in JDBC 3.0 for the Statement object as shown here: if(cs.executeUpdate()!=1)ok = false; Result rs = cs.getGeneratedKeys(); Cross- Reference The use of the JDBC 3.0 extension method Statement.getGeneratedKeys() is discussed in Chapter 4. Finally, the stored procedure INSERT_CONTACT_INFO is called to insert the member data stored in the ProcessNABean. The code for the ProcessNABean is shown in Listing 13-7. Listing 13-7: Calling a stored procedure from a JavaBean package JavaDatabaseBible.ch13; import java.sql.*; import javax.sql.*; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -353 - public class ProcessNABean extends java.lang.Object{ private static String dbUserName = "sa"; private static String dbPassword = "dba"; protected String firstName; protected String lastName; protected char mi; protected String street; protected String city; protected String state; protected String zip; protected String phone; protected String email; protected String username; protected String password; public ProcessNABean(){ } public void setUsername(String username){ this.username = username; } public void setPassword(String password){ this.password = password; } public void setFirstName(String firstName){ this.firstName = firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public void setMi(char mi){ this.mi= mi; } public void setStreet(String street){ this.street = street; } public void setCity(String city){ this.city = city; } public void setState(String state){ this.state = state; } Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -354 - public void setZip(String zip){ this.zip = zip; } public void setPhone(String phone){ this.phone = phone; } public void setEmail(String email){ this.email = email; } public String getUsername(){ return username; } public String getPassword(){ return password; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public char getMi(){ return mi; } public String getStreet(){ return street; } public String getCity(){ return city; } public String getState(){ return state; } public String getZip(){ return zip; } public String getPhone(){ return phone; } public String getEmail(){ return email; } public boolean insertData(){ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -355- boolean username_selection_ok = true; try { Class.forName("com.inet.pool.PoolDriver"); com.inet.tds.TdsDataSource tds = new com.inet.tds.TdsDataSource(); tds.setServerName( "JUPITER" ); tds.setDatabaseName( "MEMBERS" ); tds.setUser( dbUserName ); tds.setPassword( dbPassword ); DataSource ds = tds; Connection con = ds.getConnection(dbUserName,dbPassword); CallableStatement cs = con.prepareCall("{call GET_LOGIN_FOR_USER(?)}"); cs.setString(1,username); ResultSet rs = cs.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int id = -1; while(rs.next()){ id = rs.getInt("MemberID"); } if(id>=0){ System.out.println(id+": "+username+"; "+password); username_selection_ok = false; }else{ cs = con.prepareCall("{call SET_LOGIN_FOR_USER(?,?)}"); cs.setString(1,username); cs.setString(2,password); if(cs.executeUpdate()!=1) username_selection_ok = false; cs = con.prepareCall("{call GET_LOGIN_FOR_USER(?)}"); cs.setString(1,username); rs = cs.executeQuery(); while(rs.next()){ id = rs.getInt("MemberID"); } cs = con.prepareCall("{call Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -356 - INSERT_CONTACT_INFO(?,?,?,?,?,?,?,?,?,?)}"); cs.setInt(1,id); cs.setString(2,firstName); cs.setString(3,String.valueOf(mi)); cs.setString(4,lastName); cs.setString(5,street); cs.setString(6,city); cs.setString(7,state); cs.setString(8,zip); cs.setString(9,"<NULL>"); cs.setString(10,email); if(cs.executeUpdate()!=1) username_selection_ok = false; } }catch(ClassNotFoundException e1){ System.err.println(e1.getMessage()); }catch(SQLException e2){ System.err.println(e2.getMessage()); } return username_selection_ok; } } Error Handling Recall that the ProcessNABean notifies the ProcessNAForm.jsp page that the user needs to select a different username by setting the boolean flag username_selection_ok to false. This lets the ProcessNAForm.jsp know that a problem has arisen, so it then sends the user back to the form so he or she can select a new username and password. As it stands, the form is cleared when redisplayed. This is virtually guaranteed to ensure that the user gets fed up and surfs on. The way to avoid this is to fill in the fields the user has already completed and to present a message telling him or her what to do next. One of the primary uses of JavaBeans in JSP applications is data storage. Since all the form data has already been inserted into the ProcessNABean, completing the form for the user requires only the addition of this line: <jsp:useBean id="ProcessNABean" ./> Also, include these few extra lines of code to set the properties: First Name<BR><INPUT maxLength=30 name=firstName value='<jsp:getProperty name="ProcessNABean" property="firstName"/>' size=26> A partial listing of the modified form is shown in Listing 13-8. Listing 13-8: ProcessNAForm.jsp modified for use as an error page Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -357 - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Member Registration </TITLE> <SCRIPT language=JavaScript1.1 > function validate(form){ if( form.elements["firstName"].value==" "|| form.elements["lastName"].value=="" || form.elements["email"].value=="" || form.elements["city"].value=="" || form.elements["state"].value=="?"|| form.elements["zip"].value=="" ){ alert("Please enter first name, last name, email, city, state and zip."); return false; } return true; } </SCRIPT> <META content="text/html; charset=windows-1252" http-equiv=Content-Type> </HEAD> <BODY bgColor=#ffffff> <BASEFONT face=Arial size=3> <%@ page session="true" %> <jsp:useBean id="ProcessNABean" class="JavaDatabaseBible.ch13.ProcessNABean" scope="session"/> <FORM action=ProcessNAForm.jsp method=POST target=_self onSubmit="return validate(this);"> <TABLE cellPadding=0 BORDER=0> <TR> <TD> <TABLE cellPadding=0 BORDER=1> <TR> <TD valign=center> </P> <SMALL> <CENTER> <FONT color=#ff0000> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -358- Information contained in the shaded portion of this page will be kept confidential </FONT> </CENTER> <SMALL> </TD> </TR> <TR> <TD> <TABLE cellPadding=4 cellSpacing=0 Border=0 BGCOLOR="#AAAAAA" WIDTH="100%"> <TBODY> <TR> <TD vAlign=bottom> <TABLE cellSpacing=0 cellPadding=0 Border=0> <TR> <TD> First Name<BR><INPUT maxLength=30 name=firstName value= '<jsp:getProperty name="ProcessNABean" property="firstName"/>' size=26> </TD> <TD vAlign=bottom align=right> M.I.<BR><INPUT maxLength=1 name=mi value= '<jsp:getProperty name="ProcessNABean" property="mi"/>'size=2> </TD> </TR> </TABLE> </TD> <TD vAlign=bottom> Last Name<BR><INPUT maxLength=30 name=lastName value='<jsp:getProperty name="ProcessNABean" property="lastName"/> 'size=30> </TD> </TR> <TR> <TD vAlign=bottom> Choose a User Name<BR><INPUT maxLength=30 name=username value= Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 1 3:Using PreparedStatements and CallableStatements -359 - '<jsp:getProperty name="ProcessNABean" property="username"/>' size=30> </TD> <TD height=43 colspan=2 vAlign=bottom> Choose a password<BR><INPUT name=password size=20> </TD> </TR> <TR> <TD vAlign=bottom> EMail Address<BR><INPUT maxLength=30 name=email value='<jsp:getProperty name="ProcessNABean" property="email"/>' size=30> </TD> </TR> <TR> <TD height=43 vAlign=bottom> Street Address<BR><INPUT name=street value= '<jsp:getProperty name="ProcessNABean" property="street"/>' size=30> </TD> </TR> </TBODY> </TABLE> </TD> </TR> Note Listing 13-8 is only partial, showing the basic workings of the JSP page. Substitute this into Listing 13-5, and implement the additional lines for the remaining properties to create a complete form. Figure 13-2 shows the use of the original form as a means of providing interactive feedback to the user. This kind of user feedback is important in terms of ensuring that a user will take the trouble to complete a form instead of simply surfing on. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Hashtable as one of the inputs to the PreparedStatement used to save the Blob to the database table The Blob upload servlet is shown in Listing 14-7 Listing 14-7: Uploading images using a Blob upload servlet import java. io.*; import java. util.*; import java. sql.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BlobUploadServlet extends HttpServlet{ private static... content type in the response object Some browsers are more sensitive to this than others Listing 14-8: A servlet that retrieves large objects package JavaDatabaseBible.ch14; import java. io.*; import java. sql.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class LobServlet extends HttpServlet{ private String dbUserName = "sa"; private String dbPassword = "dba"; protected... that loads a JavaBean to query the database The SearchFormBean itself is shown in Listing 15-3 Listing 15-3: JavaBean to handle database query... In practice, a more common way to write a Blob to a database table is to use PreparedStatement.setBinaryStream() to transfer data directly from an InputStream to the RDBMS system An example of this approach is shown in Listing 14-1 Listing 14-1: Inserting a Blob into a table package JavaDatabaseBible.ch14; import java. io.*; import java. sql.*; import javax.sql.*; -364 - Please purchase PDF Split-Merge... large object types Table 14-1: SQL3 Large Object Data Types SQL3 type Java Interface get set Update BLOB java. sql.Blob getBlob setBlob updateBlob CLOB java. sql.Clob getClob setClob updateClob ARRAY java. sql.Array getArray setArray updateArray SQL Structured type java. sql.Struct getObject setObject updateObject REF to Structured Type java. sql.Ref getObject setObject updateObject Note At the time of this... page="SearchFormResultsPage.jsp"/> The SearchFormBean itself is shown in Listing 15-3 Listing 15-3: JavaBean to handle database query from a JSP page package JavaDatabaseBible.ch15; import java. sql.*; import javax.sql.*; public class SearchFormBean extends java. lang.Object{ private static String dbUserName = "sa"; private static String dbPassword = "dba"; protected int price; protected int year; -383 - Please... objects were involved The designers of relational database management systems have responded by providing support for the management and storage of these large objects within the database itself This chapter discusses the use of relational databases to store and retrieve large objects in various ways Examples include the use of servlets to upload images to a database, and to retrieve them for display in... select field The servlet shown in Listing 14-4 echoes the upload back to the browser, so you can look at the upload format Listing 14-4: Blob upload test servlet import java. sql.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BlobTestServlet extends HttpServlet{ public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException,... registerOutParameter() method prior to calling the CallableStatement's getString method to retrieve the output parameter Listing 13-10: Getting an output parameter from a stored procedure package JavaDatabaseBible.ch13; import java. sql.*; import javax.sql.*; public class CheckPassword{ private static String dbUserName = "sa"; private static String dbPassword = "dba"; public static void main(String args[]){ int id = -1;... the efficiency of JDBC-based applications by comparing and contrasting the three variations on the java. sql.Statement object: § java. sql.Statement, which performs in line execution of a SQL command This approach is ideal for one-shot execution of a single command, since it involves minimum overhead § java. sql.PreparedStatement, which offers a means of precompiling SQL commands This approach is best . Listing 13-7: Calling a stored procedure from a JavaBean package JavaDatabaseBible.ch13; import java. sql.*; import javax.sql.*; Please purchase PDF Split-Merge. 14-1: Inserting a Blob into a table package JavaDatabaseBible.ch14; import java. io.*; import java. sql.*; import javax.sql.*; Please purchase PDF Split-Merge

Ngày đăng: 18/10/2013, 00:15

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan