You are on page 1of 18

Creating a Simple Web Application Using a MySQL Database

This document describes how to create a simple web application that connects to a MySQL database server. It also covers some basic ideas and technologies in web development, such as JavaServer Pages (JSP), JavaServer Pages Standard Tag Library (JSTL), the Java Database Connectivity (JDBC) API, and two-tier, client-server architecture. This tutorial is designed for beginners who have a basic understanding of web development and are looking to apply their knowledge using a MySQL database. MySQL is a popular Open Source database management system commonly used in web applications due to its speed, flexibility and reliability. MySQL employs SQL, or Structured Query Language, for accessing and processing data contained in databases. This tutorial continues from the Connecting to a MySQL Database tutorial and assumes that you have already created a MySQL database named M y N ew D a ta b ase , which you have registered a connection for in the NetBeans IDE. The table data used in that tutorial is contained in ifpwafcad.sql and is also required for this tutorial. This SQL file creates two tables, S ubjec t and C oun se l o r , then populates them with sample data. If needed, save this file to your computer, then open it in the NetBeans IDE and run it on the MySQL database named M yN e w D atab ase . Contents Planning the Structure Creating a New Project Preparing the Interface Setting up a Connection Pool Setting up a JNDI Datasource Referencing the Datasource from the Application Adding the Database Driver's JAR File to the Server Adding Dynamic Logic Adding the JSTL Library to the Project's Classpath Adding t a gli b Directives to the JSP Pages Adding JSP and JSTL Code Deploying and Running the Project See Also To follow this tutorial, you need the following software and resources. Software or Resource NetBeans IDE Java Development Kit (JDK) MySQL database server Version Required version 6.x Java version 5 or 6 version 5.x

MySQL Connector/J JDBC Driver version 5.x GlassFish application server or Tomcat servlet container Notes: The NetBeans IDE 6.1 with Glassfish and MySQL Bundle Download provides you with an all-in-one package of software required for this tutorial. The Java download bundle enables you to optionally install the GlassFish application server and the Apache Tomcat servlet container 6.0.x. You must install one of these to work through this tutorial. The MySQL Connector/J JDBC Driver, necessary for communication between Java platforms and the MySQL database protocol, is included in NetBeans IDE 6.x. If you need to compare your project with a working solution, you can download the sample application. V2 UR2 or V3 Prelude version 6.x

Planning the Structure


Simple web applications can be designed using a two-tier architecture, in which the application communicates directly with a data source using the Java Database Connectivity API. A user's requests are sent to a database, and the results are sent directly back to the user. Two-tier architectures can be easily mapped to a client-server configuration, where a user's browser serves as the client, and a remote database reachable over the Internet corresponds to the server. The application you build in this tutorial involves the creation of two JavaServer Pages. In each of these pages, you add basic HTML to implement a simple interface, followed by SQL tags provided by JSTL technology in order to query the database. Consider the following client-server scenario.

The welcome page (i n d e x . j sp ) presents the user with a simple HTML form. When a client requests the in dex. jsp page, the JSP code contained therein is parsed, and data from the Subject database table is gathered, added to the page, and sent to the client. The user makes a selection in the provided HTML form and submits, which causes the client to make a request for r esp on s e . js p . When r e s pon s e .j s p is parsed, data from both the Subject and Counselor tables is gathered and inserted into the page. Finally, the page is returned to the client and the user views data based upon his or her selection.

Creating a New Project


In order to implement the scenario described above, you develop a simple application for a fictitious organization named IFPWAFCAD, or The International Former Professional Wrestlers' Association for Counseling and Development. The application enables a user to choose a counseling subject from a drop-down list (i ndex. jsp ), then retrieves data from the MySQL database and returns the information to the user (res p o ns e.jsp ).

index.jsp

response.jsp

Create a new project in the IDE: 1. Choose File > New Project (Ctrl-Shift-N; -Shift-N on Mac) from the main menu. Under Categories select Java Web (If you are using NetBeans 6.0 or 6.1, select Web); under Projects select Web Application. Click Next. 2. In Project Name, enter IFPWAFCAD. 3. Step through the wizard leaving all other settings at their defaults. Specify the server you want to use by selecting from the Server drop-down menu. Do not select a framework. When you reach the final panel of the wizard, click Finish. The IDE creates a project template for the entire application, and opens an empty JSP page (inde x.jsp ) in the Source Editor. i nd e x . j s p serves as the welcome page for the application. The new project is structured according to Sun Java BluePrints guidelines.

Preparing the Interface


Begin by preparing a simple interface for the two pages. Both ind ex.j sp and re spon se.js p implement an HTML table to display data in a structured fashion. i nde x . js p also requires an HTML form that includes a drop-down list.

index.jsp
Make sure i nd e x . j s p is opened in the Source Editor. If it is not already open, double-click ind ex.js p from IFPWAFCAD > Web Pages in the Projects window. 1. In the Source Editor, change the text between the <t itle > tags to IFPW AFCAD Hom epage . 2. Change the text between the < h 1 > tags (<h 2 > tags if you are using NetBeans 6.0 or 6.1) to We lcome to
I F PW AF C A D , the Int e r nat i o na l F or m e r P rofess iona l Wre stler s' A ssoci ation for Coun selin g a n d D e ve lo p m e n t ! .

Note: For further content, you can either add HTML elements to the page using the IDE's palette, as demonstrated below, or just copy and paste the code provided in step 8 directly into your index .jsp page. 3. Open the IDE's Palette by choosing Window > Palette (Ctrl-Shift-8; -Shift-8 on Mac) from the main menu. Hover your pointer over the Table icon from the HTML category and note that the code snippet for the item displays.

Click the icon, and drag and drop a table into the page in the Source Editor, to a point just after the <h1 > (or < h 2 > tags). In the Insert Table dialog that displays, specify the following values then click OK: Rows: 2 Columns: 1 Border Size: 0 The HTML table code is generated and added to your page. 4. Add the following content to the table heading and the cell of the first table row (new content in bold):
< ta b l e b o r d e r=" 0 " > < t he a d > <tr> <th > I F PW A F CAD o ff e r s e x pert couns elin g in a wid e ra nge o f fie lds. </th> </tr> < / th e a d > < t bo d y > <tr> <td > T o v i e w t h e c o n t ac t deta ils o f an IFPW AFCAD cer tifie d for mer p r of e s sio n a l w r e st l er in your are a, se lect a su bject belo w: </t d > </tr>

5. For the bottom row of the table, drag and drop an HTML form from the Palette into the page, directly between the second pair of <t d > tags. In the Action text box, type in resp onse. jsp , then click OK. 6. Type in the following text between the < f or m > tags of the form you just created:
< st r o n g> S e l e ct a s ub j e ct: < / st r o n g>

7. Drag and drop a drop-down list from the Palette to a point just after the text you just added. In the Insert Dropdown dialog that displays, type in s u b j ec t _ i d for the Name text field, and click OK. Note that the code snippet for the drop-down list is added to the form. The number of options for the drop-down is currently not important. Later in the tutorial you will add JSTL tags that dynamically generate options based on the data gathered from the Subject database table. 8. Add a submit button to the form by dragging a button from the Palette to a point just after the drop-down list you just added. Enter su b m i t for both the Label and Name text fields, then click OK. 9. To format your code, right-click in the Source Editor, and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac). Your code is automatically formatted, and should now look similar to the following:

< bo d y > < h 2> W e l c ome t o < s t ron g > IF P W A FC A D</st rong> , th e Int ernat iona l For mer P r o f ess i o n al W res t l er s ' As s ociat ion f or C ounse ling and Devel opmen t! < / h2 > < t ab l e b ord e r = "0 " > < t h e ad> <tr > < t h> I F PWA F C AD o f fe r s exp ert c ouns eling in a wid e ran ge of fie lds.< /t h > </t r > < / t h ead > < t b o dy> <tr > < t d> T o vi e w t h e co n tact detai ls o f an IFPWA FCAD cert ified for mer p r ofe s s io n a l w r estle r in your area , sel ect a sub ject belo w: < / td > </t r > <tr > < t d> < f orm a ct i o n =" r espon se.js p"> < s t ro n g > Se l ect a subj ect: </str ong> < s e le c t na m e="su bject _id" > < o p t io n ></op tion> < / s el e c t > < i n pu t t yp e ="sub mit" valu e="su bmit" nam e="su bmit" /> < / for m > < / td > </t r > < / t b ody > < / ta b l e > < /b o d y >

To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). When you do this, the JSP page is automatically compiled and deployed to your server. The IDE opens your default browser to display the page from its deployed location.

response.jsp
In order to prepare the interface for r es p o n se . j sp you must first create the file in your application. Note that most of the content that displays in this page is generated dynamically using JSP technology. Therefore, in the following steps you add placeholders which you will later substitute for the JSP code. 1. Right-click the IFPWAFCAD project node in the Projects window and choose New > JSP. The New JSP File dialog opens. 2. In the JSP File Name field, enter re s p o ns e . Note that Web Pages is currently selected for the Location field, meaning that the file will be created in the project's web directory. This is the same location as where the i n de x. j s p welcome page resides. 3. Accept any other default settings and click Finish. A template for the new r espon se.js p page is generated and opens in the Source Editor. A new JSP node also displays under Web Pages in the Projects window.

4. In the Source Editor, change the title to I F P W AFC AD - {pla cehol der} . 5. Remove the <h 1 >He l l o W o r ld ! < / h1 > (or < h1> JSP Page </h1> if you are working in NetBeans 6.0 or 6.1) line between the < b o dy> tags, then copy and paste the following HTML table into the body of the page:
< ta b l e b o r d e r=" 0 " > < t he a d > <tr> <th c o ls p a n=" 2 " >{ p l a ce h older }</th > </tr> < / th e a d > < t bo d y > <tr> <td > < s tr o n g>D e s cr i p t io n : </s trong ></t d> <td > < s pa n sty l e =" f o n t- s ize:s malle r; f ont-s tyle: ital ic;"> {plac ehol der}< /s p a n > < / t d > </tr> <tr> <td > < s tr o n g>C o u ns e l o r: </str ong>< /td> <td > { p la c e hol d e r} < b r> < s pa n sty l e =" f o n t- s ize:s malle r; f ont-s tyle: ital ic;"> m e mb e r si n c e: { p la c ehold er}</ span > </t d > </tr> <tr> <td > < s tr o n g>C o n ta c t De t ails: </st rong ></td > <td > < s tr o n g>e m a il : < /s t rong> < a h r e f=" m a il t o : {p l aceho lder} ">{p laceh older }</a > < b r> < s tro n g >p h o n e: </str ong>{ plac ehold er} </t d > </tr> < / tb o d y > < /t a b l e>

To view this page in a browser, right-click in the Source Editor and choose Run File (Shift-F6). The page is compiled, deployed to your server, and opened in your default browser. Your res pons e.jsp page should display similar to the following.

style.css
Create a simple stylesheet that enhances the interface display. 1. Right-click the IFPWAFCAD project node in the Projects window and choose New > Other. In the New File wizard, make sure Web is selected under Categories, then choose Cascading Style Sheet and click Next. 2. Type s t y le for CSS File Name and click Finish. The IDE creates an empty CSS file and places it in the same project location as i n d ex . jsp and r esp o n se . j s p . Note that a node for s tyle. css now displays within the project in the Projects window, and the file opens in the Source Editor. 3. In the Source Editor, add the following content to the s tyle .css file:
b od y { f o nt - f a m ily : V er d a na, A ri a l , s a ns-se rif; f o nt - s i z e: s m a ll e r ; p a dd i n g : 50 p x ; c o lo r : # 555 ; } h 1, h 2 { t e xt - a l i gn: l e ft ; l e tt e r - s pac i n g : 6 p x; f o nt - s i z e: 1 . 4 em ; c o lo r : # be7 4 2 9 ; f o nt - w e i ght : n or m a l; w i dt h : 4 50p x ; } t ab l e { w i dt h : 5 80p x ; p a dd i n g : 10 p x ; b a ck g r o u nd- c o l or : #c5 e 7 e0 ; } th { } td { } t e xt - a l i gn: l e ft ; b o rd e r - b ott o m : 1 p x so l i d;

p a dd i n g : 10 p x ;

a :l i n k { c o l or : # b e74 2 9 ; f o n t- w e i g ht: n o rm a l ; t e x t- d e c o rat i o n : n o ne; } a :l i n k :h o v e r { c o l or : # b e74 2 9 ; f o n t- w e i g ht: n o rm a l ; t e x t- d e c o rat i o n : u n der l i ne ; }

4. Link the stylesheet to i n dex . j sp and r esp o n se .jsp : In both pages, add the following line between the <he ad> tags:
< li n k re l = " s tyl e s h ee t " ty p e =" t e x t/ c ss" h ref=" styl e.css ">

This document assumes that you understand how the stylesheet functions, and how it affects corresponding HTML elements found in i n d ex . jsp and r esp o n se . j s p . When working with CSS in the IDE, you can take advantage of the CSS Style Builder and CSS Preview. Together, these tools provide extensive support for creating style rules and viewing elements when coupled with style attributes. For example, place your cursor within the h 1 , h 2 rule in sty le.cs s , then open CSS Preview (Window > Other > CSS Preview):

CSS Preview demonstrates how an element renders in a browser. Also note that the preview automatically refreshes as you make changes to a rule, providing a real-time textual representation of style elements from the IDE.

Setting up a Connection Pool


The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool. 1. Setting up a JNDI Datasource 2. Referencing the Datasource from the Application 3. Adding the Database Driver's JAR File to the Server

Setting up a JNDI Datasource


Both GlassFish and Tomcat contain Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. In either case, you need to configure a JNDI Datasource for the server that creates an interface which your application can use for connection pooling. Depending on whether you are using GlassFish or Tomcat, do the following:

GlassFish
The IDE provides enhanced support for GlassFish, enabling you to specify resources using a wizard: 1. In the Projects window, right-click the Server Resources node and choose New > Other. The New File wizard opens. Under Categories, select GlassFish. Under File Types, select JDBC Resource. Click Next. 2. Under General Attributes, choose the Create New JDBC Connection Pool option, then in the JNDI Name text field, type in j d b c /I F PWA F C AD . Click Next. 3. Click Next again to skip Additional Properties, then in Step 4, type in I fpwa fcadP ool for JDBC Connection Pool Name. Make sure the Extract from Existing Connection option is selected, and choose j d bc :m y s q l : //l o cal h o st: 3 3 06 / M y Ne w D ata base from the drop-down list. Click Next.

Note: The wizard detects any database connections that have been set up in the IDE. Therefore, you need to have already created a connection to the M yNe wData base database at this point. You can verify what connections have been created by opening the Services window (Ctrl-5; -5 on Mac) and looking for connection nodes ( under the Databases category. 4. Accept any other default settings within the wizard, then click Finish. By completing the wizard, you declared a new datasource and connection pool for the application. In the Projects window, open the newly created Server Resources > s u n -r e sourc es.xm l file and note that, within the <re sourc es> tags, a jdbc resource and connection pool have been declared containing the values you previously specified. To confirm that a new datasource and connection pool are indeed registered with GlassFish, you can deploy the project to the server, then locate the resources in the IDE's Services window: 1. In the Projects window, right-click the IFPWAFCAD project node and choose Deploy (or Undeploy and Deploy). The server starts up if not already running, and the project is compiled and deployed to it. 2. Open the Services window (Ctrl-5) and expand the Servers > GlassFish > Resources > JDBC > JDBC Resources and Connection Pools nodes. Note that the new datasource and connection pool are now displayed: )

Tomcat
Configure a JNDI Datasource in Tomcat by adding a declaration for your resource to the application's co ntext .x m l file. This is the application's context container, which enables you to specify application meta-data necessary for the server in order to deploy and run the application. There are various locations where you can specify context elements, such as your server's global $C A T A L INA _ HOM E / co n f / co n t ext . x ml file. By adding resource declarations to your application's co nt e x t. xm l file however, you limit the resource to that application, and do not need to configure anything within the

server itself. For more information, see the Apache Tomcat Configuration Reference. 1. From the Projects window, open the application's context container in the Source Editor by double-clicking the Web Pages > META-INF > co n t ext . x ml file. 2. Add the following < R eso u r ce > tags (changes below in bold) as a declaration for the JNDI resource:
< ?x m l ve r s i o n=" 1 . 0 " e n cod i n g= " U T F- 8 "?> < Co n t e xt p a t h=" / I F PW A F CAD " > < R es o u r c e n a m e =" j d bc/ I F PW A F C AD " auth ="Con tain er" t ype=" java x.sql .Data Sour ce" m a x A cti v e = "1 0 0 " m a x Id l e = "3 0 " max Wait= "100 00" u s e r nam e = " ro o t " p a s sw o r d =" n buser " dri verC lassN ame=" com. mysql .jdbc .Dri ver" u r l = "jd b c : my s q l:/ / l oc a l h os t :3306 /MyNe wDat abase "/> < /C o n t ex t >

Notice that the declaration is using roo t and nbu ser as your database's username and password. For a more thorough explanation of JNDI DataSource configuration, including a description of the parameters used in the above resource declaration, refer to the Apache Tomcat 6.0 JNDI Datasource HOW-TO.

Referencing the Datasource from the Application


You need to reference the JNDI resource you just configured from the web application. To do so, you can create an entry in the application's deployment descriptor (w e b .xm l ). Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed to a specific environment. For example, they are normally used to specify application context parameters and behavioral patterns, security settings, as well as mappings for servlets, filters and listeners. Do the following to reference the JNDI Datasource in the application's deployment descriptor. 1. In the Projects window, expand the Web Pages > WEB-INF subfolder and double-click web .xml . A graphical editor for the file displays in the Source Editor. 2. Click the References tab located along the top of the Source Editor. Expand the Resource References heading, then click Add. The Add Resource Reference dialog opens. 3. For Resource Name, enter the resource name that you gave when configuring the JNDI Datasource for the server above (j d b c /I F PWA F C AD ). The Description field is optional, but you can enter a human-readable description of the resource, e.g., Da t aba s e fo r IFP W A FC A D appl icat ion . Note that the default resource type is j a va x. s q l . D ata S our c e . Leave all fields that are provided by default and click OK. The new resource is added under the Resource References heading:

To verify that the resource is now added to the web .xml file, click the XML tab located along the top of the Source Editor. Notice that the following < r e s our c e -r ef > tags are now included:
< re s o u rc e - r e f> < d es c r i p tio n > D at a b ase f or I F PW A FCAD appli cati on</d escri ptio n> < r es - r e f -na m e > jd b c /IF P W AF C A D </ r es-re f-nam e> < r es - t y p e>j a v a x. s q l.D a t aS o u r ce < /res- type> < r es - a u t h>C o n t ai n e r</ r e s- a u t h> < r es - s h a rin g - s co p e >Sh a r ea b l e </ r es-sh aring -sco pe> < /r e s o ur c e - r ef>

Adding the Database Driver's JAR File to the Server


Adding the database driver's JAR file is another step that is vital to enabling the server to communicate with your database. Ordinarily, you would need to locate your database driver's installation directory and copy the mysq lco nn e c to r- j a v a -5 . x -b i n.j a r file from the driver's root directory into the library folder of the server you are using. Fortunately, the IDE's server management is able to detect at deployment whether the JAR file has been added - and if not, it does so automatically. In order to demonstrate this, open the Servers window (Choose Tools > Servers). For both GlassFish and Tomcat, the IDE provides a JDBC driver deployment option. If the option is enabled, it initiates a check to determine whether any drivers are required for the server's deployed applications. In the case of MySQL, if the driver is required and it is missing, the IDE's bundled driver is deployed to the appropriate location on the server. Note: If you are using GlassFish V3, the JDBC driver deployment option is not enabled by default.

Depending on the server you are using, do the following.

GlassFish V3
1. Select GlassFish V3 in the left pane. 2. In the main pane, select the Enable JDBC Driver Deployment option.

3. Before you close the window, make a note of the GlassFish installation directory. This is indicated in the Domains folder text field. 4. Click Close to exit the Servers window. 5. On your computer, navigate to the GlassFish installation directory and drill into the do mains > dom ain1 > l i b subfolder. 6. Deploy your project to the server. In the IDE's Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node. You can view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that the MySQL driver is deployed to a location in the GlassFish server.

Now, if you return to the d o m a in 1 / lib subfolder on your computer, you can see that the my sql-c onnec t o r - j a v a -

5 . x- bi n . j a r file has been automatically added.

When you connect to GlassFish in the IDE, you are actually connecting to an instance of the application server. Each instance runs applications in a unique domain, and so here the JAR file is located in domai n1 , which is the default domain created upon installing GlassFish. Note that the Domain Name text field in the Servers window indicates the name of the domain your server is using.

GlassFish V2
1. Select GlassFish V2 in the left pane. 2. Click on the Options tab in the main pane. Notice that the JDBC Driver(s) Deployment Enabled option is selected by default.

3. Locate the GlassFish installation directory. You can do this by clicking the Connection tab and noting the path listed in the Domains folder text field. 4. Click Close to exit the Servers window. 5. On your computer, navigate to the GlassFish installation directory and drill into the do mains > dom ain1 > l i b subfolder. If you have already deployed your project to the server, you will find that the m ysql- conn ect o r - j a v a 5 . x- bi n . j a r file is added here. If not, deploy your project now (next step). 6. In the Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node. You can view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that the MySQL driver is deployed to a location in the GlassFish server.

Now, if you return to the d o m a in 1 / lib subfolder on your computer, you can see that the my sql-c onnec t o r - j a v a -

5 . x- bi n . j a r file has been automatically added.

When you connect to GlassFish in the IDE, you are actually connecting to an instance of the application server. Each instance runs applications in a unique domain, and so here the JAR file is located in domai n1 , which is the default domain created upon installing GlassFish. You can verify this by viewing the Domain Name text field in the Connection tab.

Tomcat
1. Open the Servers window by choosing Tools > Servers from main menu. 2. Select Tomcat 6.0 in the left panel, then click the Deployment tab in the main pane. Notice that the Enable JDBC driver deployment option is selected by default.

3. Click the Classes tab. This tab displays all of the JAR files contained in the server's li b folder. If you have already deployed your project to the server, you will find that the mysql -conn ecto r-jav a-5.x -bin .jar file is listed here. If not, click Close to exit the Servers window, and deploy your project now (next step). 4. In the Projects window, choose Deploy (or Undeploy and Deploy) from the right-click menu of the project node. You can view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that the MySQL driver is deployed to < ins t all - d ir> / l ib in the Tomcat server.

5. Reopen the Servers window (Tools > Servers) and view the JAR files listed under the Classes tab. You can see that the MySQL driver has been automatically added.

Adding Dynamic Logic


If you return to the i n d e x .js p and re s p on s e . js p placeholders created earlier in the tutorial, you can add JSP and JSTL code to enable pages to generate content dynamically, i.e., based on user input. To do so, you need to perform the following 3 steps: 1. Adding the JSTL Library to the Project's Classpath 2. Adding t a g l i b Directives to the JSP Pages 3. Adding JSP and JSTL Code

Adding the JSTL Library to the Project's Classpath


In order to make better use of the JSP resources at your disposal, you can make use of the JavaServer Pages Standard Tag Library (JSTL) to access and display data taken from the Logic Layer. This library comes bundled with the IDE. You therefore need to make sure the JSTL library is added to the web project's compilation classpath, then add the relevent ta gl i b directives to each of the JSP pages. This allows the server we are using to identify the tags when it reads them from the JSP pages. Depending on whether you are using GlassFish or Tomcat, do the following:

GlassFish V3 and Tomcat


1. In the Projects window, right-click the project's Libraries node and choose Add Library. Select the JSTL 1.1 library and click Add Library. The IDE contains the JSTL 1.1 library by default, and allows you to add it to a project's classpath in this manner.

2. Expand the Libraries node and note that two new JAR files have been added: the JSTL library's s tanda rd . j a r , and the j s t l . j a r . You can further expand the s t an dard.j ar file to view JSTL's four basic areas of functionality.

The JSTL library includes four basic areas of functionality:


cor e : common, structural tasks such as iteration

and conditionals formatting tags


sql : SQL tags

fmt : internationalization and locale-sensitive

xml : manipulation of XML documents

GlassFish V2
Do nothing! GlassFish includes the JSTL library by default. You can verify this by expanding the Libraries > GlassFish node. GlassFish V2 contains the a p p s er v - jst l . ja r file, which defines all standard tags in the JSTL library.

Adding taglib Directives to the JSP Pages


Regardless of what server you are using, you need to add the necessary ta glib directives to JSP pages: 1. Open both i n dex . jsp and r es p o n se . j sp in the Source Editor. Add the following directives to the top of both pages:
< %@ t a g li b u r i=" h t t p: / / jav a . su n . c om / jsp/j stl/c ore" pref ix="c "%> < %@ t a g li b u r i=" h t t p: / / jav a . su n . c om / jsp/j stl/s ql" prefi x="sq l"%>

Adding JSP and JSTL Code


Finally, add the code to each page. Both pages require that you implement an SQL query that utilizes the JSTL <sql:query> tags and the datasource created earlier in the tutorial.

index.jsp
In order to dynamically display the contents of the form in i ndex .jsp , you need to access all na me s from the Subject database table: 1. Add the following SQL query beneath the ta gli b directives you added in the previous step:
< sq l : q ue r y v ar= " s u bj e c ts" d at a S o ur c e="jd bc/IF PWAF CAD"> S E LE C T s ubj e c t _i d , na m e F R O M S u bject < /s q l : qu e r y >

The JSTL < s q l : que r y > tags enable you to use SQL query language directly in a JSP page. A r esult set is generated from the query, and the acquired data can then be inserted into the page using an iterator tag (<c : f o rE a c h > ) from the JSTL co r e library. 2. Replace the empty < o p t io n > tags in the HTML form with the following iterator (changes in bold):
< se l e c t n a m e ="s u b j ec t _ id" > < c :f o r E a ch v a r =" s u bje c t " i t e ms = "${su bject s.ro ws}"> < o p t ion v a lu e = "${ s u bj e c t .s u bject _id}" >${s ubjec t.nam e}</ optio n> < / c: f o r E ach > < /s e l e ct >

The f o r Ea c h tag loops through all i d and n a me values from the generated resul tset , and inserts each pair into the HTML o p ti o n tags. In this manner, the form's drop-down list is populated with data. 3. Save changes (Ctrl+S), then right-click in the Source Editor and choose Run File (Shift-F6). The file is compiled and deployed to the server, and in d e x. j s p renders in the browser. The drop-down list now contains subject names that were retrieved from the database:

response.jsp
For r e s po ns e . j sp , you need to access data from both the S ubjec t and Co unsel or tables that correspond to the i d submitted by the user. This is accomplished using an SQL query and the datasource created earlier in the tutorial: 1. Add the following SQL query beneath the ta gli b directives you added in the previous step:
< sq l : q ue r y v ar= " c o un s S ubj R s " m a x Ro w s="1" data Sour ce="j dbc/I FPWA FCAD" > S E LE C T s .na m e , s . d esc r i pt i o n , c .firs t_nam e, c .nick _name , c . l a st_ n a m e, c .me m b er _ s i nc e , c.t eleph one, c.em ail F R OM S u b jec t a s s , Co u n se l o r a s c W H ER E c . cou n s e lo r _ id = s. c o u ns e lor_i dfk A N D s . s u bje c t _ id = ? < s ql : p a ra m valu e="${ para m.sub ject_ id}" /> < /s q l : qu e r y >

A r e s u lt s e t named c o u n sS u b jRs is generated from the above SQL query, which contains all data associated with the s u b j e c t _i d submitted by the user. Note that data from the Couns elor table is acquired by mapping c o un se l o r _ i dfk from S u b jec t to cou n s el or_ id from Cou nselo r . 2. Add the following declaration beneath the SQL query from the previous step:
< c: s e t v a r = " cou n s S ub j " sc o p e= " r e qu e st" v alue= "${c ounsS ubjRs .row s[0]} "/>

The < c : se t > tag enables you to set the r esu ltset to a scoped variable, so that you can retrieve its contents at a later stage. 3. In the HTML, replace all placeholders with JSP code that allows you to retrieve and display the data held in the c o un sS u b j r e s ult s et (Changes below shown in bold):
< ht m l > < h ea d > < m e t a h t t p -e q u iv= " C on t e n t- T ype" conte nt=" text/ html; cha rset= UTF-8 "/> < l i n k r e l = "s t y les h e et " t yp e ="tex t/css " hr ef="s tyle. css" > < t i t le> $ { c ou n s Sub j . na m e } </ t itle> < / he a d > < b od y > < t a b le> <tr >

< t h c o lsp a n =" 2 " > ${ c ounsS ubj.n ame} </th> </t r > <tr > < t d> < s tro n g >D e s c ri p tion: </st rong ></td > < t d> < s pan s ty l e = "f o nt-si ze:sm alle r; fo nt-st yle: itali c;">$ {cou nsSub j. d e s c r i p t i o n } < / s p a n </t r > <tr > < t d> < s tro n g >C o u n se l or: < /stro ng>< /td> < t d> < s tro n g >$ { c o un s Subj. first _nam e} ${ couns Subj .nick _name } ${ couns Su b j . l a s t _ n a m e } < / s t r < b r>< s p an s t yl e ="fon t-siz e:sm aller ; fon t-st yle:i talic ;"> < e m>m e m be r s in c e: ${ couns Subj .memb er_si nce} </em> </spa n></ td> </t r > <tr > < t d> < s tro n g >C o n t ac t Deta ils: </st rong> </td> < t d> < s tro n g >e m a i l: </str ong> < a hr e f =" m a i lt o :${co unsSu bj.e mail} ">${c ouns Subj. email }</a > < b r>< s t ro n g > ph o ne: < /stro ng>$ {coun sSubj .tel ephon e}</t d> </t r > < / t a ble > < / bo d y > < /h t m l >

Deploying and Running the Project


Whether you are using the GlassFish application server or Tomcat, the process for deploying your project is the same. If you installed GlassFish or Tomcat through the IDE download, your server is already registered in the IDE. If you need to make any changes to server settings, or would like to register a different server with the IDE, choose Tools > Servers from the main menu to open the Server Manager. To deploy the IFPWAFCAD project to the server: From the Projects window, right-click the project node and choose Deploy (If you are using NetBeans 6.0 or 6.1, choose Undeploy and Deploy). The IDE compiles the project, starts the server, then deploys the project to it. You can see any output generated in the Output window. The output should complete with a BU ILD S UCCE SSFUL message. To check that the application has indeed been deployed to the server, open the Services window (Ctrl-5) and expand the Servers node. All servers that are registered in the IDE are listed here. For GlassFish, expand Applications > Web Applications to view the application. For Tomcat, expand Web Applications to view the IPFWAPCAD application. To run the application: In the Projects window, right-click the IFPWAFCAD project node and choose Run. The ind ex.js p page opens in the IDE's default browser. NetBeans 6.5 now provides a Compile on Save feature. Simply saving a file triggers the IDE to recompile and deploy it to the server automatically. That way, compilation and deployment take place entirely in the background. Thus, when you run a project, you can be sure the deployment contains the latest changes. When in d e x . js p displays in the browser, select a subject from the drop-down list and click sub mit . You should now be forwarded to the r esp o n se . j s p page, showing details corresponding to your selection:

Send Us Your Feedback

See Also
This concludes the Creating a Simple Web Application Using a MySQL Database tutorial. This document demonstrated how to create a simple web application that connects to a MySQL database. It also demonstrated how to construct an application using a basic two-tier architecture, and utilized JSTL and JSP technologies as a means of accessing and displaying data dynamically. For related or more advanced tutorials, see the following resources: Connecting to a MySQL Database in NetBeans IDE. Covers the basics of working with a MySQL database in the IDE. NetBeans IDE Tutorial for Web Applications. An in-depth tutorial describing how to build a web application within the context of a typical web development cycle. Introduction to the Spring Framework. An introductory tutorial describing how to create an MVC web application using the Spring Framework in the IDE.

You might also like