You are on page 1of 42
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 Next OOO 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 above 4 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): 7. Forthe botom row of the table insert an HTML form. To doo, place your cursor between the second pai of tags, then double excimer tem Eh lon nthe Palete. nthe inser Form dialog, ype in response. jap nthe Acbon textfield than cick ox. ‘Action: ‘response jsp Method: = @ cer O post Encoding: © appication/x-wwvw-form-urlencoded O multipart/form-data Name: Cenc) GOD £8 Typein he following content between te tgs (new content shown in Bok ‘eesponse.isp"> ject a subject : 8 Press Enos add an emply tne ater th contnt youjusl added and thon double-dick Drop-down Listin the Paete to open the Insert Dropdown aatog box 10. Type subject_td forthe Name textfeld inthe lnsrt Drop-down dlog and cick OK. Not thatthe code snippet forthe dropdown sts ade to he form. ‘Tre number afoptons fr te top-down is curently notimpertant.Laterin he torial you wil add IST. tags that eysamically ‘generate options basod onthe data gathered om the Subject database table 11, Ad a submit biton iten (Gt a point just ater te drown is you jusadded. You can eter use the Pete odo hs, oF| Invoke the editor's code completion as isatedin he previous sep. nthe inser Buiton dialog, enter submit for both the Label and Name text els, then cok OK, 12, Toformatyour cade, rightlekn the eltor and choose Formal (Alt Shit-; Ci-SIN on Mac) Your code is automaticaly formatted, and should now ook simlarto fe following 7FFWAFCAD/strong>, the International Former Professional Wrestlers’ Association for Counseling and Oevelepment!
ctdbte view the contact details of an IFPUAFCAD certified former professional wrestler in your ares, select @ subject below: cea>cetrongrensil: {placeholder} corocatrong>phone: (placeholder)
cetrong>select a ubject: {placsholdor} cee “crebcerrongebescription: (placeholeer} e/spand fer crabcerrong>Counselor: {placenolder} ore menber since: (placeholdey} cite -ete>cetrongecontact Details:
To vew his page ina browser, ght-clck nthe editor and choose Run File (Shit; Fn-Shit.F6 on Mac). The page compiles, ‘deployed othe GlassFish server, and opens in your defi browser. e00e IFPWAFCAD - iplacehotder), oO GL COCa) Gir cone 8) A {placeholder} Counselor: jrmber snc: (placeholder email (laccholier) ‘Contact Detalls: phone: (placeholder) Creating a stylesheet (reste a simple sylesheet hat enhances he dlaplay of he web nace. This ual assumes that you understand how sive rulesfuncon, and how they afectcorespording HTML elements found n index. jap and response..j9p. 4. Open he New ile wizard by pressing he New ile (buon in he IDES main olbar. Select the Wed category, hen select Catcading Sle Sheet nd sick Next 2, Type style for CSS File Name an ick Finish, The IDE reales an empy CSS fe ard paces itn the sae project een as {index ep and response. jap. Nole that node for sty Le .cxs now aisplays wiin the proectin the Projects window, and the file apensin the exit. 4 Inthe ear, adie folowing content the styLe.css fle body ( font-size: smaller; padding: Sopxs color: 45557 aL text-align: left: Letter-spacing: 6px? font-size: L.4ems color: #he?429; font-weight: normal; width: 450px7 table 4 wicth: S0px: padding: 0px: background-color: #eSe7ed; cht textratign: left: norder-bottom: 1px solids cat padding: 0px: astink ¢ color: #be?429; font-weight: normal: text-decoration: nene: a:linksover { color: #07475; font-weight: normaly text-decoration: underlines 4. Linktne siylesheetto index. jap and response. sp. Ibo pages, ada the following ne Between the Choad tags To quick¥y navigate been tes thaLare open in he eilor, press Cit-Tab, hen selectthe fle you are wanting Preparing Communication between the Application and Database ‘The most effcient way oimplament communication between the server anc database iso setup 2 database connection pool Creating a naw ceanaection foreach cient request can be very me-consuming, especialy for appications thal continuovdly receive a large number atrequest Te remedy ti, numerous connactions are crested and maintained ina connection pool Any incoming raquestshatraqure access oe application's data layer use an alteady-created connecton tom the pool. Likewise, when a equestis completed, te connections not closes dow, but etumed to he pol ‘Aer preparing the data source and connection pool or he server, you ten need to instucthe application fo use the data source. Tris is 'ypiealy done by ereatng an enty n he spplcaton's web. xn deployment descriptor. Final, you need io ensure tha he database érver (MSL Connector JDBC Divers accessible othe server. Important: From this pont onward, you need you ensure that you have a MySQL. database instance named MytewDatabase setup that contains sample date provided in pata sql. This SQL fle creates vo fables, Subject and Counse or, then populates them wit sample data. you have nol already done his, or you need help wth his ask see Connecting fo a MySQL Database belre proceeding tunher Als, your database needs be passwont-protected fo crea @ datasource and work with he GiassFish sever in this tutorial you are using te default MySQL. zoo account with an empty password, you can setthe password fom a commande prompt. his tutor uses nbuser as an exemple password To set your password 9 nibuser, naga te your MySQL insalaton's bin directory in be cammanatine prompt and enter he following: shell> ayogl a root ycql> UPOASE myogl.user SET Password = PASSHORD(*nbuser’) nysql> FuUS# PRIVILEGES; Formor informaton se the oficial MySQL Reference Manual: Securing the nial MySQL. Accounts, 1. Soting up a JOBC datasource and connection pool 2. Relerencing the data source fom the appicaton 3. Adding the database divers JAR lof the server ‘Setting up a JDBC data source and connection pool The GlassFish Server Open Souroe Eon contains Database Connecton Pooling (DACP) ibrar met provide connection peaing ‘uncSonalty ina way thatisansparent‘o you as a developer. To take advantage ofthis, you need to configure a JOBC (Java Database CConnectivy) data souree for the server wrieh your applieaton can use fr connection packing For mor infomation on JOBC tsenology, See The Java Tura: JDBC Basis ‘You could contgure he data source rect wihin the GlassFish saver Admin Console or, a8 descnbed below, you can deca resources tatyour application needsin a gLassfiah-reacusces.xm2 fle. hen the applicaon's deployed, te server readin the resource deciarabons, and creates te necessary resources, ‘The following stops domonsvate how lo declare a connection poo, and a daa source hateleson the connection pool. The NetBeans DBC Resource wizard alows youto perform both actions. 4. Open te New File wizard by pressing the New File (| buon in the IDEs main toolbar Select the GlaseFieh sere eatgory. then Select JOG Resource anacck Nex. 2, Instep 2, General Aiutes, choose the Create New JDBC Connection Pool option, ten inte JNDI Name txt ld pe in dbenFPWAFCAD. supe SES 1. choose ‘roid configuration fermion forthe ORC Resource 2 caneraiAarioutes- Ei thaas a ntng JOB Comecton Poko cate anew OAC Conmacton ol 5 Paces Fel wi na we es 4 ChtoveDanbase cmeed 5. ABU Conexion Pot Properties. _O Use Existing JOBC Connection Poo! 6. Naveen et Spud opens RoE eet PTE © create new 08 Connection oot (INDI Name* [dc /IFPWAFCAD Object type: Laser ® Ce SA Gee) GD Const ‘The JDBC data source relies on JNDI, he Java Naming and Directory Interface. The JNDIAPI provides unitrm way fr applicalions ond and accoss data sources. Fer mor information, see Tne JNO! Tutorial, 3. Optonally, adda descrinon forthe data source. For example, Ypein: Accesses the database that provides dats for the TEPWAFCAD application, 4. Click Nox hen dick Nextagain to shp slap 3, Adtonal Propers. 5. InStep 4, ype in fpwateadPoo! fr JDBC Connection Poo! Name, Maxe sure the Exact fom Elstng Connection oplon i selected and choose jabe:kyaql://Lecalhast:3306/MyNewDatabase fom the dropdown ist Click Nex. 1. Choose Frovie configuation nlormaton forthe JOKC Connection Poot 2 General avitutes - fier ehoose an existing dtabare connection to estat information, of enter the [otc Resource Configuration information. 5. Properties Fie ith an" mark ae requires aa connec rnection Poot Name* [ipwafendP@el 5. Add Connection aot ORC Cone 6. Add Connection Poot ‘Optional Properties O New Configuration using Database ) XA Global Transaction 7 ep) ( taps, a data source and connecton poolhave been declared conlaining the values you previously spocifed ‘To confirm hata new dala source and connection pool are indeed rep stored with te GlasFieh sever, you can deploy tre projectto ‘he server, hen locale the resources in the IDEs Serves window: 1. Inthe Projets window, ng. he IFPAIAFCAD projeet node and choose Deploy. The sewer stars up i notalready running, and the pojectis compiled and ployed sit 2, Open the Services window (CW; 35 on Mac) and expand he Servers > Glassfish > Resources» JDBC » JDBC Resources and Connection Paste nodes. Note that the new data source and connection poalare now displayed: y (a Servers ¥ ©pGlassFish v3 Domain > Go Applications y & Resources ¥ @ yoec y (i JDBC Resources |S jdbc/sample & jdbc/_TimerPoot S jdbc/_detaue Ss mm fat Comacten rot ame earl 5 Demy 6 sanpteroa 6 >» Connectors > Jnbta Sessions Referencing the data source from the application "You need to reference the JDBC resource you just configured fom te web applicaton. Todo so, you can create an entry in he application’ ‘ob. deployment desert. Deployment aescxptors are XML-based text fet that conta information describing how an application isto be deployed oa specie enuronment For example, Dey ae normaly used a speci application contest parameters ena behavioral pales, secunlysettngs, 96 ell as mappings for servis, ers and Istners. Note. you specfod Java EE 6 or Java EE7 as tre Java version when you created the project you need to creat the deployment esctpior le by choosing Web > Standard Deployment Descipor inthe New Fle wizar Perform the following sts to reference th datasource inthe applications deplayment descriptor, 1. Inthe Projects window, expand the Gontguraton Files folder ard couble-clex wes. xm lo open the fle inthe eto. 2, Cliktne References ab located along the top ofthe adr. 8. Expand the Resource References heading and clk Add to open the Add Resource Relerence dialog 4. For Resource Name, enter te resource name hat you gave when configuring the data source forthe server above (Gabe/1FeMAF CAD) 65. Type javax.aq2.ConnectionPoolDataSource nthe Resource Type eld. Click OK ‘The Desariion fils s optional, butyou can enter @humanceadable deserpson of heresoutes, eg, Database for TRPHAFCAD application. 0.8. elt Mesures REP Resource Name: [jdbe/IFPWAFCAD Resource Type: _|javax.sal.ConnectionPoolDataSource |~ ‘Authentication: (Container) Sharing Scope: {shareable 3) Description: [iY Caneel) (SOE) “The new resource is now listed under he Resource References heading 6, Toverf thal he resource is now added tothe wal 22 lo, click he Source tab located along the top ofthe edior. Notes thatthe following 4 dbo/TFPRAFCAD¢/ree-ref-name> croa-type>javax.aql ConnectionPoolbatasource Container “erea-sharing-scope>shareablec/res-sharing-scope> ‘Adding the database driver's JAR fle to the server ‘Aadling the database tives JAR fleis another sep Malis vial enabling the server o communicate wih your database. Ordinarily, you would need t locate your database avers insallaton directory and copy he nysql~connector~java~S.+.§-bin. jar tle fom the ‘tver’s rotrector ino te library ober ofthe server you ae using. Fortunately, the DE's server managersntis able io detect at eployment whether the JAR ile has been added ardifno it does so automaticaly Irederto demonsiae this open the Servers manager (Choose Tools > Servers). The DE provides a OBC driver deployment option. Khe ‘pton is enabled, tinitates a check o determine whether any crives ae required forte server's deployed application. Inthe case of ‘MyBO. the drivers requted and itis missing, the IDE’ bundled ever is deployes fo the appropriate location onthe server 41. Choose Tools > Servers open the Servers manager. lect the GlassFish serverin helo pane. 2. Inthe main pane, selectthe Enable JDBC Driver Deployment option. Sees [OB eres ——*S SarerName infish Sever 0 Sa Seer TV hsstish Sever € ==) eee nese nate Comet Suppor (S Presewe Sessions Actos Reaeloyment Enable TP Mentor (star epsteed Deby Sever |S tate s0¥ Der Desoyment ae) Before you close the Servers manager, make a note of he path indicated in he Domains folder tx Feld When you connect the (GlassFish serverin the IDE, you are actualy connecting to an stance of he applation server. Each instance rune eppleatons in @ Unique domain. and tie Damain Name fel indicates the name of tie domain your servers using. As shown inthe mage above, he Aver JAR fle #ouk be located win domaint. whieh is he dels domi created upon ising the Glassfish sever, Clic lose to ent te Servers manager. ‘on your compiler, navigate tothe GlassFish sewer installation dvectry and ailinio he domaine > donainl > Lib subflder ‘Because you should have al-eady deployed the FPWWAFCAD projectto he server, you should see te xyaqi—connector~ Ja 5.1. Goin. Ja fle you do not eee the driver JAR Sl, perform the following step. Deploy your projecto the server. nthe IDEs Projcts window, choose Deploy fom he ngitlek menu ofthe project nade. You can vow progress in the DE's Output window (C4 3-4 on Mae) The outputindateshalhe MySQL drveris deployed ls alocation the GlassFiah server, "Now fyouretum othe doma ini Lb subfoler on your computer. you can see halthe nyaql-connector~Java-$.1.6- bin. Jar le has been automaticaly ade Adding Dynamic Logic Roturring othe index. jsp and response. sp placeholders that you created earerin the tral, you can now implement te JSTL code thatenabies pages to generate content dnemiealy, \e, based on user input To do so, perfor the flowing hee asks, 1 Add the JSTL brary tothe projects classpath 2. Implement STL code ‘Adding the JSTL library to the project's classpath ‘You can apply the JavaServer Pages Standard Tag Library (JSTL) to access and spay data taker fom the database. The GlassFish sewer Includes me JST brary by detult. You can vey tis by expanding the GlassFish Server node under Lirares node i the Projects window, and searching for tha javax.sexviet. jep. jat). jar lay. (Older versions ofthe GlassFish server use he } spl. 332 Hora) Because the GlassFish server braves ave by detaul adaed io your projects classpath, you do nothave to perform any steps or is task STL provides he following four base areas of uncial. + core: common, stuctral tasks suchas terators and condonas fr handing fow conto + mt: Interationalzation and localizaton message formating + sql simple database access + m1: handling oP content This tutorial focuses on usage ofthe core and aq tag lraries. Implementing JSTL code "Now yeu can implement tne code hal dynamically etioves and eisplays dala foreach page. Goth pages require tha you implement an SOL. ‘query thatutlizes the datasource erased earlrin the hora. ‘Te IDE provides several dataase-specil JSTL snippets which you can select fom he Palelle(CL¥-SRS; Shit on Mach ¥ Daabase SHens index jsp Inordoro dynamical display the contents ofthe form n andex. jsp, younsed to access all nanes tom he Subject database table 1. Hover yourmouse overthe 8 Report item inthe Pale. ‘The DB Reportitem uses te tag ocreae an SAL query ben tuses he tag loop tough he quer/s res Lset and output the retieved data, 2. Place your cursorabove he decaraton ne 7), then double-click tho D3 Reporttam inthe Pat. the ialog hata splays, ener te following deta: «Variable Name: sub jacts, + Scope: page + Data Source: jebe/z#PWascAD 1 Query Statement: SELECT subject_1d, name FROM Subject VariableName: (subjects Scope (page _— Data Source: _jdbc/IFPWAFCAD Query Statement: 3. Click OK. The fellowing contontis onerated inthe index.sp fle. New contont shown in bold) Document: index author abuser < SELECT subject_id, naze FROM Subject. en 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 Ketzong>Select a subject: 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 eM e/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-on response 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} th colspan="2"5$ (counselordataiis.name) eit ctdvcatrong>description: capan style~"fontosize:amalier; font= style:izalics"9§ (counselorpetails. description) ese counsolor: $ {eounselosDetaile first name} S{eounselordetaile.nick ane) $(counselorDetails.last_nane} Kenmmenber since: §{eounselorDetatle.member_sinee} Contact Detaila: href="nailto:8 {coungelozDetaiis email} ">$ {counselorDetasie eal} phone: $ (eounselorbetails. telephone) Running the Completed Application Youve now completed the application. Try running itagan to see how itdsplays na browser. Note that because of NetBeans! Compe on Save feature, you do not need to worry about compiling or redeploying the applicator. When you tun a project you canbe sure the deployment conf your tates changes. Ck ne Run Project (D>) auton he main tober. The index. jep page opensin he IDE efatbrowser Vien index. Sap displaysin the browser, selecta subject fom the deop-down is and click suhmie. You should now be forwarded othe ‘response. jsp page, showing details coresponding to your selection, Past-Life Regression 1 Past-Life Regression is a journey ofthe soul, backward and Description: forward through time, like a yo-Yo. Andre "The Giant’ Counselor: member since: 2001-01-12 Contact ‘email: bobo@ifpwafcad.com Detai phone: 606 443-4567 ‘This concludes the Creating a Simple Web Applicaton Using @ MySQL Data simple web application hat connec o a MySGL. database, algo demanstated how fo construct an application using abasic Wwo-terarhtecur, and utizes numerous tecnaologies cluding JSP, JSTL, JDBC, and JNOlas @ means of accessing and esplaying data cynamicaly tutorial. This document emanates now tere Troubleshooting Mostotihe problems tra occur wih the trial applicaton ae due to communication dffcultes between the GlassFish Server Open Source Editon and the MySQL database sewer. your application does not display corey or fyou ate receiving a server ero, te following ‘examinations may be usetuL + Doatabae resources exist? + Do the connection poo and datasource exist onthe server? + ethe MySQL Connector ver accessible othe GlassFish server? «+ lsthe database password-protected? + Ave he connection p00 properies correct set? Do database resources exist? Use the IDE's Servics window (CHS; 2-5 on Maco ensure thalthe MySQL serveris running, and thatMytew2acabasc is accessible and contains appropriate table daa + To connectio the MySQL database server, rghtalce he MySOL Server node and choose Connect + Ifa conection nde (EE or sywewoatabase does notisplay in te Services window, you can create a connection by right- ‘llcking te MySQL ever nade (@®) and choosing Conneet Using, Entarte quired deals othe dialog hat display, Data Input Mode: @ Field Entry © Direct URL Entry Host: Damme eeeeeeeeeeeeeeeeeeeeeeeeeeeeeem re 3505 oe Tabac rm Display Name (Optional): Remember password © Gee help for information on security risks) ‘Additional Props: 1 Show JOBC URL jdbe:mysql://localhost:3306/MyNewDatabase ‘The els provide the New Database Connecon dialog ior the URL sting entered inte Snow JOBG URL option ‘Teretore,tyouknow he URL (eg. jabe:mysal ://Lecalnon::3306/éykewbstabase) you can paste into te Show JDBC URL fe, andthe remaining dialog felds bocome automatically populated + To ensure thatthe Subject and Counse Lor tables exist and hal hey contain sample data, expand he MyWewDatabase consection node (EB) and ocale he Mynewdat.sonse catalog node (EB). Expend the caalog node to view exsng ables. You can vew able data by 'ghtolckng able node and choosing View Dai, vB MyNewDatabase y Cl Tables Counselor i counselor_id 1 first. name 1 nick name 1 lastname 1D telephone 1 email IGE member_since > Ct indexes Recreate Table. Properties Do the connection pool and data source exist on the server? ‘ter deploying the application othe GlassFish sever, Ne glassf:ch-rosources x contained in the project should insvucthe server to ceate a JDBC resource and connection pool You can determine whethartrese ext fom the Servers node inthe Sarvca window. + Expand the Servers >the GlassFish Server > Resources node, Expand JOBC Resources lo iow the abe/ TFEWAECAD dala source hatwas ested fom g.asafi'sh-resources .»ml. Expand the Connection Pools node lo vew tie "fpwafeadPook conredion pool that was crealed fom glassLish-resources xz. (This is demonstrated above) Is the MySQL Connector/J driver accessible to the GlassFish server? ‘Make sure thal be MySOL. Connector diver has been deployed tothe GlassFish server. (This lscussedin Adding the databese deers LAR fle tothe server) + Locate he Glassish server installation older on your computer and ail down ino the GlassPssh donains/domaint/1ib subfoleer. Hore you shuld nd the ayaql-connector~Java-5.1.€-bin. jar Mle Is the database password-protected? ‘The database reeds o be passwort-proteced to wnable the GlassFish server data Source to work properly this tutorial. you are using the Getaut MySQL root account wih an empty password you can sel the password fom @commandtine prompt + To setyour password to nbuser. navigate fe your MySG nsallaon's nin aretory in he commandine prompt an enter folowing yaql> CPOATE ayaqluses SE7 Password = PASSMORD('nbuses') “> WHERE User = ‘root mysql> PLUSH PRIVILEGES; Formoce information, see he off MySQL Reference Manual Secung the hia! MySQL Accounts ‘Are the connection pool properties correctly set? Ensure hal he cannection pool is working coral fr he server. 1. Open the Services window (CHL #5 on Mac) and expard the Servers node, 2, Rightalick ne Glass svar node and choose View Admin Console, 5. Emer the username ana password you ate prompted. You can Vew the usemame and password inthe Servers manager 4 Inthe rae on the et ide ofthe console, expand the Resouross > JDBC > JDBC Connetion Pools > rrpxaZcad?oe! nada Dota or the 1£pwazcadoo1 connection pool display in the main window. 5. Cliektne Ping buton fhe connection pols set up eorecty, youwil see "Ping Succeeded’ met Edit Connection Pool [Save | | Cancet | Modify an existing JDBC connection pool. A JDBC connection poo! is a group of reusable connections for a particular database. Lond efauis Fh | Pea General Settings "Indicates required field NDI Name: fpwafcadPoo! 6. Ive ping fal, lick he Adnonal Properies in and ensure tetihe Isted propery values are coecly set ‘Send Us Your Feedback See Also Formor information about Java web developmant ses the flowing resources + NotBeans Artcts and Tutorials + #sJava Database Connectivity (JDBC) ‘+ # JavaServer Pages Standard Tag Library (JSTL) “+ = Java Naming and Di tory Interface {UND}

You might also like