The JSP Files (Part 5) - No Forwarding Address

29 400 0
The JSP Files (Part 5) - No Forwarding Address

Đ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

The JSP Files (part 5): No Forwarding Address By Vikram Vaswani and Harish Kamath This article copyright Melonfire 2000−2002. All rights reserved. Table of Contents Toolbox .1 Dumped! .2 The Scenic Route .5 One Step At A Time 7 What's Your Name? .10 New Friends .13 No Forwarding Address .18 Cleaning Up .26 The JSP Files (part 5): No Forwarding Address i Toolbox JSP offers a number of advantages over other server−side scripting languages − as you've already seen, performance is just one of them. And this performance edge becomes particularly important when you combine it with another important benefit − the ability to seamlessly connect to a variety of database servers. By offering seamless database connectivity (okay, it's not as transparent as the database connectivity available in PHP, but it's still pretty good!) in combination with faster response times, JSP allows developers to build complex, scalable, data−driven Web applications while simultaneously enjoying short development cycles. OK, 'nuff said. Let's cut to the chase. In this article, we're going to demonstrate how to use JSP to connect to a database, extract data from it, and use that data to build a dynamic Web page. We'll be building a simple Web application in order to help make the process clearer; this should also help you quantify how much easier (or harder) JSP is to use, as compared to other server−side scripting languages you may be familiar with. If you're planning on trying out the examples below (recommended), you'll need to download and install the mySQL database server, available at http://www.mysql.com/. mySQL is a fast, reliable, open−source database management system, which offers a fair amount of power at a price that should move you to tears − it's free! We'll be assuming that you've installed and configured mySQL, and have the appropriate permissions to create and edit database tables. Since all database interaction in Java takes place using a technology known as JDBC, or Java Database Connectivity, you'll also need a JDBC module that allows you to connect to the mySQL database server. We'll be assuming that you've downloaded the mm.mySQL JDBC module from http://www.worldserver.com/mm.mysql/ , and configured it to talk to your mySQL database, as described in the article "Slapping Together A JSP Development Environment" at http://www.devshed.com/Server_Side/Jserv/JSPDev/ If you're using a database other than mySQL, fear not − JSP supports all major databases, and you can use the techniques described over the next few pages to talk to other databases too. You'll probably need to consult your database vendor's manual or Web site for information on how to obtain the necessary software. Finally, some knowledge of SQL would come in handy. In case you don't know SQL, don't worry − it's extremely simple, and a few minutes with the "Speaking SQL" tutorial at http://www.devshed.com/Server_Side/MySQL/Speak/ will have you executing queries like an expert. With all that out of the way, let's actually get our hands dirty. Toolbox 1 Dumped! If you're familiar with SQL, you know that there are four basic types of operations possible with a database: SELECT a record; INSERT a record; UPDATE a record; DELETE a record. In order to demonstrate these operations, we're going to build a little application that requires each of the functions listed above − an address book which allows multiple users to store and view contact information online. As always, one of the first things you have to think about when designing a data−driven application is the design of the database (duh!). For this application, we've decided to use a single table called "abook", which contains fields for different types of contact information − address, phone, fax, email address, and the like. Every user in the system has a unique login id, and each record in the database is "owned" by a specific user. We've put together a "dump file", which lets you create the database tables and initial set of records quickly − we suggest that you import this data into your mySQL database server, as we'll be using it throughout this article. To import the data, download the dump file and use this command at your mySQL prompt: $ mysql −u username −p database < dumpfile Or you could insert the contents manually − here is what you 'll need: # # Table structure for table 'abook' # DROP TABLE IF EXISTS abook; CREATE TABLE abook ( id int(11) unsigned NOT NULL auto_increment, uid varchar(255) NOT NULL, fname varchar(255) NOT NULL, lname varchar(255) NOT NULL, tel varchar(255), fax varchar(255), Dumped! 2 email varchar(255), addr text, company varchar(255), comment text, PRIMARY KEY (id) ); # # Dumping data for table 'abook' # INSERT INTO abook (id, uid, fname, lname, tel, fax, email, addr, company, comment) VALUES ( '1', 'john', 'Bugs', 'Bunny', '7376222', '', 'bugs@somedomain.com', 'The Rabbit Hole, Dark Woods, Somewhere On Planet Earth', '', 'Big−ears in da house!'); INSERT INTO abook (id, uid, fname, lname, tel, fax, email, addr, company, comment) VALUES ( '2', 'john', 'Elmer', 'Fudd', '', '7628739', 'fuddman@somedomain.com', '', '', ''); INSERT INTO abook (id, uid, fname, lname, tel, fax, email, addr, company, comment) VALUES ( '3', 'joe', 'Peter', 'Parker', '162627 x34', '', 'webcrawler@somedomain.com', 'Your Friendly Neighbourhood Newspaper', '', 'My spidey−sense is tingling!'); INSERT INTO abook (id, uid, fname, lname, tel, fax, email, addr, company, comment) VALUES ( '4', 'bill', 'Clark', 'Kent', '1−800−SUPERMAN', '', 'superdude@somedomain.com', '', '', 'Is it a bird? Is it a plane?'); This will create a table named "abook" with columns for different types of contact information; these records are owned by three mythical users, "bill", "john" and "joe". Now check whether or not the data has been successfully imported with a SELECT query (the SELECT SQL statement is used to retrieve information from a database). Enter this at your mySQL command prompt: mysql> select uid, fname, lname from abook; which, in English, means "display the columns uid, fname and lname from the address book". Here's what you should see: The JSP Files (part 5): No Forwarding Address Dumped! 3 +−−−−−−+−−−−−−−+−−−−−−−−+ | uid | fname | lname | +−−−−−−+−−−−−−−+−−−−−−−−+ | john | Bugs | Bunny | | john | Elmer | Fudd | | joe | Peter | Parker | | bill | Clark | Kent | +−−−−−−+−−−−−−−+−−−−−−−−+ 4 rows in set (0.00 sec) The JSP Files (part 5): No Forwarding Address Dumped! 4 The Scenic Route All working? Good. Now, let's use JSP to do exactly the same thing − fire a SELECT query at the database, and display the results in an HTML page. <html> <head> <basefont face="Arial"> </head> <body> <%@ page language="java" import="java.sql.*" %> <%! // define variables String UId; String FName; String LName; // define database parameters String host="localhost"; String user="us867"; String pass="jsf84d"; String db="db876"; String conn; %> <table border="2" cellspacing="2" cellpadding="5"> <tr> <td><b>Owner</b></td> <td><b>First name</b></td> <td><b>Last name</b></td> </tr> <% Class.forName("org.gjt.mm.mysql.Driver"); // create connection string conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "+ pass; // pass database parameters to JDBC driver Connection Conn = DriverManager.getConnection(conn); // query statement The Scenic Route 5 Statement SQLStatement = Conn.createStatement(); // generate query String Query = "SELECT uid, fname, lname FROM abook"; // get result ResultSet SQLResult = SQLStatement.executeQuery(Query); while(SQLResult.next()) { UId = SQLResult.getString("uid"); FName = SQLResult.getString("fname"); LName = SQLResult.getString("lname"); out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName + "</td></tr>"); } // close connection SQLResult.close(); SQLStatement.close(); Conn.close(); %> </table> </body> </html> And you'll see something like this: Owner First name Last name john Bugs Bunny john Elmer Fudd joe Peter Parker bill Clark Kent The JSP Files (part 5): No Forwarding Address The Scenic Route 6 One Step At A Time Using JSP to extract data from a database involves several steps. Let's dissect each one. 1. First, we need to make sure that all the modules required for a JDBC connection are available to the JSP document. This is accomplished by means of the <%@ page . %> directive, used to define attributes that affect the JSP document. <%@ page language="java" import="java.sql.*" %> The "import" attribute is used to import all the packages and classes required for the script to execute − here, all the packages in the "java.sql.*" tree. 2. Next, it's necessary to declare all the variables required for this scriptlet; we've kept aside some for the results of the SQL query, and also created variables to hold database−specific information, such as the name of the database server, the username and password required to gain access, and the database to use for all queries. This information is used to build a connection string, at a later stage. 3. The next step is to load the JDBC driver required to access a mySQL database − this is accomplished with the statement Class.forName("org.gjt.mm.mysql.Driver"); The name of the driver to be used for a specific database can always be obtained from the documentation you receive with the driver. 4. Now that the drivers have been loaded, it's time to open a connection to the database server. This is accomplished by means of the Connection object and its getConnection() method. The getConnection() method requires a connection string as argument; this connection string is created by combining the server name, the username and password, and the name of the database to use into a single URL−like string. // create connection string conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "+ One Step At A Time 7 pass; // pass database parameters to JDBC driver Connection Conn = DriverManager.getConnection(conn); The getConnect() method then returns a connection identifier, which is used for subsequent SQL queries. All communication between JSP and the database server takes place through this connection. In this case, the specific instance of the Connection object is called "Conn". 5. Once a connection to the database is available, the Statement object is used to prepare a SQL statement for execution. // query statement Statement SQLStatement = Conn.createStatement(); 6. At this point, a query is created // generate query String Query = "SELECT uid, fname, lname FROM abook"; and the ResultSet object is used to store the results of the query. // get result ResultSet SQLResult = SQLStatement.executeQuery(Query); 7. Once the query has been executed and the results returned, a number of methods can be used to iterate through the result set. The example above uses the next() method, which simply moves forward through the list of records returned by the query. A "while" loop is used to iterate through the result set in combination with the next() method. // get and display each record while(SQLResult.next()) { UId = SQLResult.getString("uid"); FName = SQLResult.getString("fname"); LName = SQLResult.getString("lname"); out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName + "</td></tr>"); The JSP Files (part 5): No Forwarding Address One Step At A Time 8 [...].. .The JSP Files (part 5): No Forwarding Address } Incidentally, the ResultSet object also comes with a handy prev() method, which allows you to display the preceding record The getString() method is used to access specific columns in the record currently being examined; these values are stored as strings in the JSP document In addition to the getString() method, you can also use the getInt(),... activate the script "edit .jsp" and pass the record number to it via the URL GET method Let's now take a look at "edit .jsp" Update Address Book Entry As you can see, once "edit .jsp" receives the record number, it connects to the database, extracts the. .. Email = SQLResult.getString("email"); No Forwarding Address 19 The JSP Files (part 5): No Forwarding Address // get the record number HERE String ID = SQLResult.getString("id"); // add an edit link to each record with the ID out.println("" + FName + "" + LName + "" + Tel + "" + Fax + "" + Email + "edit this entry");... SQLResult.getString("email"); address = SQLResult.getString("addr"); company = SQLResult.getString("company"); comment = SQLResult.getString("comment"); // close connection SQLResult.close(); SQLStatement.close(); Conn.close(); No Forwarding Address 21 The JSP Files (part 5): No Forwarding Address %> 's Little Black Book First name Last name Tel Fax Email address .jsp" should be called with the number of the record to be deleted So, just as you have the link "edit this entry" you will now have the additional link "delete this entry" Let's take a look at "delete .jsp" ... number, it connects to the database, extracts the record, and then generates a simple form with the values already filled in (note our usage of the shortcut construct to display variable values) The user is then free to modify the information displayed in the form; once done, the form is submitted to "edit_res .jsp" , which takes care of the UPDATE operation ... face="Arial"> New Friends 15 The JSP Files (part 5): No Forwarding Address . (0.00 sec) The JSP Files (part 5): No Forwarding Address Dumped! 4 The Scenic Route All working? Good. Now, let's use JSP to do exactly the same thing. "display the columns uid, fname and lname from the address book". Here's what you should see: The JSP Files (part 5): No Forwarding Address Dumped!

Ngày đăng: 27/10/2013, 07:15

Từ khóa liên quan

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

Tài liệu liên quan