1. Trang chủ
  2. » Công Nghệ Thông Tin

The JSP Files (Part 5) - No Forwarding Address

29 400 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề The JSP Files (Part 5): No Forwarding Address
Tác giả Vikram Vaswani, Harish Kamath
Thể loại Article
Năm xuất bản 2000-2002
Định dạng
Số trang 29
Dung lượng 44,08 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

In this article, we're going to demonstrate how to use JSP to connect to a database, extract data from it, anduse that data to build a dynamic Web page.. Since all database interaction i

Trang 1

The JSP Files (part 5): No Forwarding Address

By Vikram Vaswani and Harish Kamath

This article copyright Melonfire 2000−2002 All rights reserved.

Trang 2

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

Trang 3

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 buildcomplex, 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, anduse that data to build a dynamic Web page We'll be building a simple Web application in order to help makethe 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 themySQL database server, available at http://www.mysql.com/ mySQL is a fast, reliable, open−source databasemanagement 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 tocreate and edit database tables

Since all database interaction in Java takes place using a technology known as JDBC, or Java DatabaseConnectivity, 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 inthe 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 thetechniques described over the next few pages to talk to other databases too You'll probably need to consultyour 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'sextremely 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

Trang 4

As always, one of the first things you have to think about when designing a data−driven application is thedesign of the database (duh!) For this application, we've decided to use a single table called "abook", whichcontains 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 thisarticle

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),

Trang 5

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,

'My spidey−sense is tingling!');

INSERT INTO abook (id, uid, fname, lname, tel, fax, email,

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 youshould see:

The JSP Files (part 5): No Forwarding Address

Trang 6

| 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

Trang 7

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

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

// query statement

Trang 8

Statement SQLStatement = Conn.createStatement();

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

Trang 9

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 JSPdocument 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 theresults 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 allqueries 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 withthe 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 youreceive 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 bycombining the server name, the username and password, and the name of the database to use into a singleURL−like string

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

Trang 10

// 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 Allcommunication between JSP and the database server takes place through this connection In this case, thespecific 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 forexecution

// 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 iteratethrough the result set The example above uses the next() method, which simply moves forward through thelist of records returned by the query A "while" loop is used to iterate through the result set in combinationwith the next() method

// get and display each record

The JSP Files (part 5): No Forwarding Address

Trang 11

8 Finally, each result set returned after a query occupies some amount of memory − and if your system islikely to experience heavy load, it's a good idea to use the various close() methods to free up memory.

// close connection

SQLResult.close();

SQLStatement.close();

Conn.close();

As you can see, connecting to a database through JSP is a little more complicated than the equivalent

procedure in PHP There's not much you can do about this but grin and bear it

The JSP Files (part 5): No Forwarding Address

Trang 12

What's Your Name?

Now that you know how to connect to a database, let's begin developing the bare bones of the address bookapplication This first script asks for a user name and then connects to the database to display entries owned

// check submit state

String submit = request.getParameter("submit");

// form not yet submitted

// display initial page

if(submit == null)

{

%>

<form action="view.jsp" method="GET">

Enter your name: <input type="text" name="name" size="10">

<input type="submit" name="submit" value="Go">

String uid = request.getParameter("name");

Trang 13

// define database parameters

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

String FName = SQLResult.getString("fname");

String LName = SQLResult.getString("lname");

String Tel = SQLResult.getString("tel");

String Fax = SQLResult.getString("fax");

The JSP Files (part 5): No Forwarding Address

Trang 14

String Email = SQLResult.getString("email");

out.println("<tr><td>" + FName + "</td><td>" + LName +

If you don't like the word "null" being displayed in columns which have no data, you can add a few "if" loops

to replace it with an empty space

The JSP Files (part 5): No Forwarding Address

Trang 15

<h2>Add Address Book Entry</h2>

<table border=0 cellspacing=5 cellpadding=5>

<form action="add_res.jsp" method="POST">

<tr>

<td><b>Username</b></td>

<td>

<select name="uid">

<!−− generate list of available usernames from database −−>

<%@ page language="java" import="java.sql.*" %>

// create connection string

connString = "jdbc:mysql://" + host + "/" + db + "?user=" +

user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(connString);

Trang 16

ResultSet SQLResult = SQLStatement.executeQuery(Query);

// get and display each record

Trang 17

Once the form has been filled up and submitted, control passes to "add_res.jsp", which takes care of actuallyperforming the INSERT operation Take a look.

Trang 18

<%@ page language="java" import="java.sql.*" %>

<%

// add_res.jsp

// form data

String uid = request.getParameter("uid");

String fname = request.getParameter("fname");

String lname = request.getParameter("lname");

String address = request.getParameter("address");

String tel = request.getParameter("tel");

String fax = request.getParameter("fax");

String email = request.getParameter("email");

String company = request.getParameter("company");

String comment = request.getParameter("comment");

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

// get result code

int SQLStatus = SQLStatement.executeUpdate(Query);

if(SQLStatus != 0)

The JSP Files (part 5): No Forwarding Address

Trang 19

It should be noted at this point that if your INSERT statement contains special characters which need to beescaped (say, commas or single quotes), you'd do better to use the PreparedStatement class, which

automatically takes care of escaping special characters and offers some performance benefits as well Adiscussion of the PreparedStatement class is beyond the scope of this tutorial, but there's plenty of

documentation out there should you ever require it

The JSP Files (part 5): No Forwarding Address

Trang 20

No Forwarding Address

Next up, updating records In order to demonstrate this, the first order of business is to modify the

next−to−last example so that each entry displayed has an edit option next to it Here's the modified code:

// check submit state

String submit = request.getParameter("submit");

// form not yet submitted

// display initial page

if(submit == null)

{

%>

<form action="view.jsp" method="GET">

Enter your name: <input type="text" name="name" size="10">

<input type="submit" name="submit" value="Go">

String uid = request.getParameter("name");

// define database parameters

String host="localhost";

String user="us867";

String pass="jsf84d";

Trang 21

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

String FName = SQLResult.getString("fname");

String LName = SQLResult.getString("lname");

String Tel = SQLResult.getString("tel");

String Fax = SQLResult.getString("fax");

String Email = SQLResult.getString("email");

The JSP Files (part 5): No Forwarding Address

Trang 22

// get the record number HERE

String ID = SQLResult.getString("id");

// add an edit link to each record with the ID

out.println("<tr><td>" + FName + "</td><td>" + LName +

Clicking this link will 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"

<h2>Update Address Book Entry</h2>

<%@ page language="java" import="java.sql.*" %>

Trang 23

// create connection string

conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user +

"+

pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

ResultSet SQLResult = SQLStatement.executeQuery(Query);

// get and display record

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

TỪ KHÓA LIÊN QUAN