Creating a Simple Web Application Using a MySQL Database
wnten by Toy Bungero
This document deserves howto eats a simple web application mat connects to @ MySQL database server. leo coves some basle teas ana
technologies in web development, such as JavaServer Pages (JSP, JavaServer Pages Slardard Tag Lirary (STL), the Java Database
Conneciwiy (JDBC) AP, and wo-ter, clenkserverarhtecture, This tla is designed for beginners who have a basicundersianding of web
evelopment ana are looking to apply ther knowledge using a MySQL database,
'MyS04 ls poputer open source database menagement system commonly used in web applications due toils speed, Nexbiy and relay
MySQL employs SOL. or Stuctured Query Language or accessing and processing dats conained in databases.
‘This tutorial isa continuation fom te Connecting to @ MySQL Database torial and assumes that you have already created a MySAL database.
named ¥ytiewDztabase, which you have registered a connection forin te NetBeans IDE. The lable data used in hattulval i contained in
watead sal andi als required for Wis taal. Ts SOL He ceales Mo lables, Subject and Counse Lor, ben populales them with sample
data needed, save this flo your computer, ten open tin the NetBeans IDE and run ton the MySQL database names yew2aLabase.
To olow his tutorial, you need the folowing software and resources.
Sofware or Resource Version Required
NetBeans IDE 72,73,74,8.0,dava ££ bundle
Java Development Kt (10%) version 7or@MySal databace server 5x
MySQL Conedtodd JDBC Drier version 5
GlassFish Server Open Source Eaton 3xor4x
Notes:
+The Java download bundle of he NetBeans IDE enables yout instal he GlassFish server. You require the GlassFish serve to work
through sis tutorial
+The mySal Connector JDBC Driver, necessary for communication between Java platforms and he MySQL database protocol.
Included inthe NetBeans IE.
+ Hyou need to compare your project witha working solution, you can download the sample application.
Planning the Structure
‘Simple web applications can be designed using a wor architecture, which a cent communicates drecty wit a server. In this torial,
Java web application communicates arety wit a MySQL database using he Java Database Connect APL Essentially, ts te MySOL
Connector JO8C Driver that enaoles communication Between he Java code understoog by the application server (he ClaseFih server. na
any contentin SAL the language understood bythe database server (MySQL).
‘Te applcaton you buildin this tutorial involves tho creation of wo JSP pages. each ofthese pages you use HTML ard CSS ts implrmenta
‘imple intetace, and apply STI teennology lo pertrm the loge that crecty queries the dalabase and ings the reviewed data ito the to
ages, The two dalabate fables, Subject ang Counselor, are contained in he MySQL. database, MyNewDattabase, which you create by
completing te Connecting fo @ MySGL Database loa, Consider the following bo-Her scenario,‘The welcome page (ides. js) presents the user with a simple HTML form, When a browser requests index. 2p, the JSTL code within the
page iiates a query ontyNtewoacabase, Rretieves dala om the Subject database table, and insets tino toe page beore itis sentto
the browser. When the user submis his or her selection inthe welcome page's HTML for, the submitinitats 2 request forthe sponse page
(cesponse. jsp). Again he JSTL code within te page inate a query on ytveuDatabase. This ne, itretieves data fom both the
Subject and Counse loz tables and inset ino tthe page, allowing the user lo ew data based upon his of her selection when the page
ie retumed tothe brow,
In orertoimplementine scenar described above, you develop a simple application for tous organization named IFPWAFCAD, The
Internatonal Former Professional Wrestlers" Association for Counseling an Development.
Index.jsp.Welcome to IFPWAFCAD,
the International Former
Professional Wrestlers'
Association for Counseling
and Development!Creating a New Project
Begin by creating anew Java web projectin the DE:
1 Choose Fila > New Project (CH-ShiEN;2-ShiEN on Mac) rom the main menu. Select the Java Web category hr
‘Application. Click NextOOO New Project
steps Choose Project
1. Choose Project Categories: Projects:
2 Gina ‘Web Applicaton
or Web Applicaton wih Exstng Sources
Gite [33 We Free-Foem Application
Gi Maven
Bi Groow
i NetBeans Modules
> Gi Samples
Description
Creates an empty Web application in a standard IDE project. A
k Standard project uses an IDE-generated build seript to build, run,
and debug your projec.
“The New Project wizard allows you ts reat an empty web application in a standard IDE project The standard projactuses an DE
‘generated Art build sexpt lo compile, deploy, and tn te application,
2. n Projet Name, enter FPWAFCAD. Also, speci the locaton fr the praecl on your computer (By default he IDE places projectsin a
MetBeansP eo jects flder located in yourhome directory.) Click Next.
'3, ne Server and Setings panel, sped the GlassFish Server as server which willbe used to run the application,
Note. The GlassFish server deplays in te Server top-down Fld ifyou insales the Java version of tie NetBeans IDE, Because
the GlassFish sereris included in the download itis automatically regstered with the IDE. you wantio use a diferent server or
‘his project, clk he Ad button located next to the Server drop-down Fel and rogistra diferent server wih the IDE, However,
‘working wih servers ober han the GlassFish server beyond the scope ofthis aor
4. Inthe Java EE Version fold, select Java EES,steps. Server and Settings
Choose Project ‘Add to Enterprise Application: | :
Name and Location Sea
1
2
3. Server and Settings
4. Frameworks Server GlassFish Server 4
(Ada.
Java EE Version: (java fe 5 a
Context Path: [/IFPWAFCAD
7
(Help
Cancel}
Java EE 6 and Java EE 7 web projecs do not eaure the use ofthe web. xm deployment dese*pta, andthe NetBeans pojecttemplate
{do0s notinchide te web zn! loin Java EE 6 and Java EE 7 projects, However. i's tutorial demonstalas now to declare a dala
source in the deployment descriptor, and itdoes notrely onan ealures specicio Java EE 8 or Java EE7, so you can set the project
version Java EES,
‘Note. You cola equal set he proect version to Java EE 6 a Java EE 7 and then cate a wols. xml deployment deserpor
(rom the New Fle wizard, solactthe Web eatogory, hen Standard Deployment Deseiptor)
5, Click Fish. The DE coates a projecttemplate fo the entire application and opens an empl JSP page (incex.7 sp)in he edierThe
index. jp tle serves. as te weleome page forthe appleation,
Preparing the Web Interface
Begin by preparing the welcome (inex. jp) and response (response. jsp) pages. The weleome page implements an HTML form
Used to capture user data. Got pages implement an HTML table oGisplay cata na stuctured fashion. In Bis section, you also create a
‘ylesheet thal enhances the appearance ofboth pages,
+ Soting up the welcome page+ creating be response page
+ Creating a stleshest
Setting up the welcome page
Conf hat index. 3 sp is open inthe er the fe
IFPWAFCAD projecin me Prolets wndow,
isnotakeady open, doubleick Incex..)sp under the Web Pages node inthe
4. Inthe eater, cnange the tex betwoen fhe tage lo: FEWRECAD Homepage
2, Change te text between the tags to:Wocomo to TFPWAPCAD, the International Former Professional
Weestlers’ Association for Counseling and Development |
8, Open the IDE’ Pale by choosing Window » Pale (CH-Shif-s;#-Shits on Mae) rom the main men. Hover your pointer over he
Tebleicon tom tne HTML category and noe that ne cau code snippet ‘or te item displays
ete oo
es
‘You can configure the Paete oyourlking -rightlickin the Paleo and choose Show Bg leans and Hide em Names ‘ohave
Iaaplay asin te Image above4 Place your cursor ata poinjust ater he tags. (This is where you wantts implement te new HTL able.) Then, in the Pale,
65. Inthe Insert Table dlilog that caplays,specty the following values then lick OX:
+ Rows:2
+ Cotes: +
+ Border Size:0
‘The HTIML table coda is gorerated and acdedto your page.
8. Ade the aiowing content the table heading and he cal ofthe frst abe row (new content shown n Bol):
Note hat he IDE automatically added tag sb directives needed forthe JSTL tags used in he generated content (cau: quary>
and cc: forkach>),A ag! ib drecive dedates that Me JSP page uses custom (, JSTL) lags, names he ag brary at etnes
them, and species ther tag prefix
Run be project see how tdaplays ina browser. Right.iek the project node in he Projects window and choose Run.
\When you choose Run, the IDE deploys te projectio ie GlaseFish saver, the index page i compiled into @ save, andthe
‘welcome page opens in your default browser. The code generaod fom the DB Reportitem reales te flowing table in the welcome
age[subject_id name
1 Financial Consultancy
2 Existential Psychotherapy
3 ‘Temper Management
4 Past-Life Regression
5 Marriage Guidance
6 Crisis Management
7 Dream Analysis
8 Hypnosis
9 Reiki
{As you can see, he DB Repotitem enables you to quickly test your database connection and enables you o ew table data tom
te database In your browser. This canbe particularly use when prottyping.
‘The following steps demonstrate howto integrate the generated code ins the HTML drop-down lst you created eal ine tural
5, Examine tho column dain he gonorated code. Two tags are
ISP container ie, he GlassFish server te perform a loop onal abe ows, and for each row. oops tough al columns, kts
‘manner, data forthe entire table ie aeplaye.
so one is nests inside the oer, Tie causes the
6, Inlegrate he fags ino the HTML form as follows, The value ofeach tom becomes the auh}jact_ia, and te ouput
text becomes he nase, as recordin the database. (Changes are displayed in bold
Ineihercase,the tgs. nhs manner, te forms arop-down lt is populated wi data
Delete the table that was ge
rated fom the DB Repor itsm. (Deleon shown below as srke-throughetext)
cttagiib profixete™ uri=raetp://Java-sun.com/ jsp/jeti/eore"’>
Document: dndex
created on : Dec 22, 2003, 7:33:43 eMe/sqhiqvery>
“heeps/ fie. w3oFg/PR/neald/teoge ded">
5, Save your changes (Ct
8. Retesh the welcome page ofthe project in your browser
"Noe hat he drop-down stn the browser now contains subjectnames that were evieved ftom the database.
"You donot need to redeploy your project ve is enabled or you project by default This means tha
ven you madly and save a fe, the Fe auomatcally compiled and deployed and you de nolnees trecamsile the entre
Prec. You can enable an disable compile-on-save for your project inthe Compiling category ofthe Properties window ofthe
Project.
ause comple-onresponse jsp
The response page provides deal forthe counselor whe covtesponds to tre subject chosen in he welcome page. The query you create
rust selectthe counselor record whose counseloz_La matches the couniselce_Ldf i fom ine eelacied subjectrecors
1. Place your eursor above he Variable Name: [counselorQuery
Scope (page _—
Data Source: [jdbc /IFPWAFCAD
Query Statement:
‘SELECT ~ FROM Subject, Counselor
\WHERE Counselor.counselor id = Subject.counselor_idfk
|AND Subject.subject_id = ?
SELECT * PROM Subject, Counselor
WEERE Counselor.counselor_id = Subject.counselor_idfk
AND Subject. aubjact_id = ?
[Nofehat ine IDE automatically sed he £ag] ib arectve needed forthe tag, Alo, note tatyou used an
- tag drecly win the query. Because his query eles on the susect_ ic value tat was submites fom
‘index. jp, you can exractte value using an EL (Expression Language) sttementin ie form of #|paran.subject_sd},and
ten pase tte the tag sohalitcan be uses in place ofthe SQL. question mark (2) durng tune,
Use a tg to seta variable that coresponds othe fretrecord (Le, row) ofthe remul tet elumed fom the query. New
content shown in bold)
ceqi:query varo"counselozguery" datasource
SELECT * FROM subject, Counselor
jdbe/TEPWAFCAD">
AND Subject.subject_id = ?
[though he resultsa* retuned fom the query shoul only contain a single record, hiss a necessary step Because he page
needs to access values fom he record using EL (Expression Language) statsmerts. Recall hatin index. jp, you ware ableto
access vahios forthe resultset simply Dy using a lag, However, the lag operates by soting @
vaable fore rows contained in the query, ths enabling you to extract values ty including te row variable in EL. statements
‘Ada the taghib
In bots)
ve fr he JSTL coe Hbrary tothe top athe Fle, eo atthe tag is understood, (New content shown
wnttp://Java.sun.con/3sp/ st1/sqi"@>6. Inthe HTL markup, replace all placeholders with EL statements cade thatsiepay the dala held inthe counseloxDacails
‘variable, (Changes Below shown In Boa:
oem
$ (counselosDetaiie name}