developing java web applications.pdf
TRANSCRIPT
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 1/87
NetBeans IDE Tutorial for Web ApplicationsWelcome to the NetBeans IDE 6.5 tutorial for web applications. In this tutorial, you build a fairly
complex web application while being introduced to a number of tools and technologies in NetBeans
IDE, as well as a typical web development cycle, from creation to deployment. Beginning with the
creating of servlets and JSP pages, the advanced sections of this tutorial show you how to use the
JavaServer Pages Standard Tag Library (JSTL) to fetch dynamic data and to internationalize the JSP
pages used in this application. You end the tutorial with an introduction to the IDE's HTTP Monitor,
which helps you analyze a web application while it is deployed.
Note: If you are new to web development in NetBeans IDE, you are recommended to follow
Introduction to Developing Web Applications before continuing.
Expected duration: 50 minutes
Contents
•
Terminology• Obtaining the required source files
• Developing the Application
• Creating a web project from the provided source files
• Creating a front controller using a servlet
• Adding the methods to process requests and to create a cookie
• Creating the JSP page that receives all the requests
• Creating the parameter files used to handle user input
• Using JSTL to handle internationalization
• Wrapping up
• Running and Monitoring the Application
• Enabling the HTTP Monitor• Verifying the Context Path
• Running the application
• Monitoring requests and sessions
• Monitoring cookies
• Monitoring requests for non-existent pages
• Enabling internationalization
• Applying What You Have Learned
• Exploring Further
• Glossary
• Next Steps
To follow this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE 6.5 Java version
Java Development Kit (JDK) version 6 or version 5
JavaServer Faces Components/
Java EE PlatformJava EE 5 or J2EE 1.4
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 2/87
GlassFish application server
or
Tomcat servlet container
V2
version 6.x
Notes:
• To take advantage of NetBeans IDE's Java EE 5 capabilities, use an application server that is
fully compliant with the Java EE 5 specification, such as the GlassFish Application Server V2
UR2. If you are using a different server, consult the Release Notes and FAQs for known
problems and workarounds. For detailed information about the supported servers and Java EE
platform, see the Release Notes.
• Optionally, for troubleshooting purposes, you can download the completed sample and inspect
the sources.
Terminology
Below are explanations of some of the terms used in this tutorial.
•
Composite View. A design pattern that is used to present information in JSP pages. This designpattern creates an aggregate view from component views. Component views might include
dynamic and modular portions of the page. The Composite View design pattern pertains to web
application design when you are creating a view from numerous subviews. Complex web pages
frequently consist of content derived from various resources. The layout of the page is managed
independently of the content of its subviews. For instance, a view might have subviews such as
Navigation, Search, Feature Story, and Headline.
When creating a composite view, you can include static content and dynamic content. Static
content might consist of an HTML file. Dynamic content is a fragment of a JSP page. The
specific content can be determined at either JSP translation time or at runtime.
• Front controllers. Components that are responsible for routing incoming requests and enforcingnavigation in web applications. For more information on the use of the Front Controller design
pattern, see the J2EE Patterns catalog.
• JSP Pages. Files that are used in web applications to present information to end users and to
enable data from end users to flow back to the server. JSP pages must be placed within a web
application in order for the JSP pages to be executable within the IDE.
• Servlets. Java classes that execute within a servlet container, which is typically running within a
web server. Servlets are used to do the following:
• Generate dynamic content.
• Extend the capabilities of web servers and web-enabled application servers.
•
Interact with web clients (typically a browser application such as Netscape or InternetExplorer) using a request-response paradigm.
Obtaining the required source files
To create the Midnight Cookie Company application, you need the midnight.zip file, which
contains the source files on which you build the application. The source files include the WEB-INFfolder, which contains the classes, docs, tlds and lib folders that you will use in this tutorial.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 3/87
1. In your file system, create a folder named midnight. This is where you will unzip the
application's files. From now on, we will refer to this folder as $UNZIPHOME.
2. Click here to download the file.
3. Use an application that unzips files to unzip the midnight.zip file to $UNZIPHOME.
$UNZIPHOME now has a WEB-INF folder, which contains the following files and folders:
File orFolder
Description
web.xml Deployment descriptor for the web application.
classes Contains the resource bundle property files that are used to
internationalize the pages and contains the
com/midnightcookies/taghandlers folder. The
taghandlers folder contains the class files for the
ContentHandler tag handler, the ButtonHandler tag handler, and
the LinksHandler tag handler. The ContentHandler includes the
contents of the specified JSP file. The ButtonHandler prints a
submit button with a localized message. The LinksHandlerdisplays a set of links, including a separator, from the tag
attribute.
docs
Contains the header.jsp file, the index.jsp file, and the
nonesch.jsp file. During the tutorial, you will create the
main.jsp page and place it in this folder. Also contains the
cookies folder, which includes the !ookie!tter.jspfile and the !ookie"ake.jsp file. During the tutorial, you
will create the #ra$.jsp page and place it in this folder. The
abot folder contains the abot.jsp file, which outlines this
web application's architecture.
lib
Contains the standard.jar file and the jstl.jar file.
These two files contain the implementation for the JSTL. The
standard.jar contains the TLDs and the tag handlers. The
jstl.jar file contains other application program interfaces
(APIs) that are needed.
tlds Contains the proprietary midnight.tld.
Developing the Application
Creating a web project from the provided source files
1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select Java Web. Under Projects,
select Web Project with Existing Sources. Click Next.
2. In Location, click Browse to select the web application's document root. The document root is
$UNZIPHOME, which is called midnight, if you followed the instructions above. This is the
folder to which you unzipped the midnight.zip file.
3. In Project Name, notice that midnight has been set. Capitalize the name to "Midnight", just
for display purposes, because project name's initial letter is typically capitalized. Change the
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 4/87
Project Location to any folder on your computer. From now on, we will refer to this folder as
$PROJECTHOME. !lick Next.
4. Select the server to which you want to deploy your application. Only servers that are registered
with the IDE are listed.
5. In Java EE Version, make sure that Java EE 5 is selected. Notice that the Context Path is
/"idnight. Click Next.
6. In Web Pages Folder, select the document root ($UNZIPHOME). Notice that the$PROJECTHOME/"idnight/WEB-INF/lib and the
$PROJECTHOME/"idnight/WEB-INF/classes folders are automatically selected as
your lib and sources folders, respectively, as shown in the following image.
7. Click Finish.
You are prompted to let the IDE delete your class files, because they will automatically be
compiled to your project's bild folder when you build the project.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 5/87
>
Click Delete to let the IDE do this.
The IDE imports your sources, deletes the class files, and creates the Midnight project in the
IDE.
You can view its logical structure in the Projects window and its file structure in the Files
window.
Creating a front controller using a servlet
A front controller is responsible for routing incoming user requests and can enforce navigation in web
applications. A front controller provides a single entry point through which requests for several
resources in a web application pass. A front controller can reduce duplication of code in JSP pages,
especially in cases where several resources require the same processing. For more information on front
controllers, see the J2EE Patterns catalog.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 6/87
1. In the Projects window, expand the Midnight project node and the Source Packages node.
2. Right-click the com.midnightcookies package node and choose New > Servlet.
3. Enter Front!ontroller in the Class Name text box and make sure that the
com.midnightcookies package is selected in the Package drop-down. Click Next.
4. Change the value of the URL Pattern(s) text box to the following:
/docs/%& /
Note that the "&" in the line above is a delimiter between URL mappings. It enables you to
create multiple URL mappings for each servlet.
5. Click Finish.
Front!ontroller.ja'a opens in the Source Editor.
6. In the Projects window. expand the WEB-INF node and double-click the web.xml node. Thecontent of the deployment descriptor file, web.xml, is displayed in the graphical editor. Click
Servlets at the top of the editor. Expand the node for the FrontController servlet's entry. Notice
the servlet's URL Patterns, which you defined in step 4 above:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 7/87
The servlet mapping "/docs/%" prevents the FrontController servlet from forwarding pages to
itself, while the servlet mapping "/" gives the FrontController servlet a servlet mapping to
handle a request such as http(//hostname:portnumber /midnight/.
Click XML at the top of the editor. The content of the deployment descriptor file is shown inXML format. The servlet mappings are as follows:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 8/87
Adding the methods to process requests and to create a cookie
Now you will edit the Front!ontroller.ja'a file to include the logic needed to process the
requests received by the web application. You will modify the process)e*est method and create
a new method called create!ookie, which demonstrates how to create a cookie used in a web
application.
1. Open the Navigator window (Ctrl-7) and select the FrontController.java node in the Projectswindow. You now see the class's methods in the Navigator:
2. Double-click the processRequest method's node in the Navigator. The Source Editor displays the
process)e*est method.
3. Replace the default process)e*est method with the following code:
protected 'oid process)e*est+,ttper'let)e*est re*est&,ttper'let)esponse response
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 9/87
throws er'letException& IException 0
tring id 1 re*est.get)e*est2)I+3 id 1 id.sbstring+re*est.get!ontext4ath+.length+3 geter'let!ontext+.log +5"idnight !ookies Front!ontroller recei'ed a re*est 6or 5 7 id3
// #he page 'ariable holds the path to the page that will be inclded
// in the content area o6 the template page /WEB-INF/docs/main.jsp. // It is passed to the template in a re*est attribte. tring page3
// I6 no re*est is recei'ed or i6 the re*est recei'ed is // 6or the root& ser'e /WEB-INF/docs/index.jsp i6 +id 11 nll 88 id.trim+.e*als+55 88 id.e*als+5/50 page 1 5/WEB-INF/docs/index.jsp53 9
// I6 a re*est recei'ed is 6or a 6ile that does not end in // .jsp or .html& there was an error. Inclde the // error page +nonesch.jsp and set the nonesch attribte with
// the path re*ested. else i6 +:id.endsWith+5.jsp5 ;; :id.endsWith+5.html5 0 page 1 5/WEB-INF/docs/nonesch.jsp53 re*est.set<ttribte+5nonesch5& id3 9 else 0 page 1 5/WEB-INF5.concat+id3
i6 +id.e*als+5/docs/cookies/!ookie"ake.jsp5 0 !ookie cookie 1 create!ookie+re*est3 i6 +cookie 11 nll 0 page 1 5/WEB-INF/docs/cookies/!ookie!tter.jsp53 9
else 0 response.add!ookie+cookie3 re*est.set<ttribte+5cookie5& cookie3 9 9 9
re*est.set<ttribte+5page5& page3 tr$ 0 re*est.get)e*est=ispatcher+5/WEB-INF/docs/main.jsp5.6orward+re*est& response3 9 catch+#hrowable t 0
geter'let!ontext+.log+t.get"essage+3 99
4. Right-click in the Source Editor and choose Fix Imports.
Note: After you enter code (either by typing or copying and pasting) into the Source Editor,
place the cursor in the Source Editor and press Alt-Shift-F to automatically format the code. To
show line numbers, right-click the left margin and choose Show Line Numbers from the
contextual menu.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 10/87
The line with the call to the create!ookie method is underlined and marked as an error,
similar to the following illustration. This is because the method does not exist yet.
5. Click Alt-Enter in the line with the error and notice that the IDE presents a suggestion of how to
solve the error:
6. Select the suggestion. The IDE creates the skeleton create!ookie method at the end of the
file.
7. Fill out the new create!ookie method by copying the following code and pasting it in the
Source Editor:
pri'ate !ookie create!ookie+,ttper'let)e*est re*est 0
tring name 1 +tringre*est.get4arameter+5name53
i6 +name 11 nll 88 name.trim+.e*als+55 0 re*est.set<ttribte+5noname5& 5noname53 re*est.set<ttribte+5error5& 5tre53 retrn nll3 9
tring 'ale 1 +tringre*est.get4arameter+5'ale53 i6 +'ale 11 nll 88 'ale.trim+.e*als+55 0 re*est.set<ttribte+5no'ale5& 5no'ale53 re*est.set<ttribte+5error5& 5tre53 retrn nll3 9
$stem.ot.println+name3 $stem.ot.println+'ale3
!ookie cookie 1 nll3 tr$ 0 cookie 1 new !ookie+name& 'ale3 9 catch+Illegal<rgmentException ex 0 // 4robabl$ an illegal name ex.printtack#race+3 re*est.set<ttribte+5error5& 5tre53 re*est.set<ttribte+5noname5& 5badname53 retrn nll3
9
tring maxage 1 re*est.get4arameter+5maxage53 i6 +maxage :1 nll ;; :maxage.trim+.e*als+55 0 tr$ 0 cookie.set"ax<ge+Integer.parseInt+maxage3 9 catch+NmberFormatException n6e 0 n6e.printtack#race+3 re*est.set<ttribte+5badnmber5& 5badnmber53 re*est.set<ttribte+5error5& 5tre53
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 11/87
retrn nll3 9 9
tring domain 1 re*est.get4arameter+5domain53 i6 +domain :1 nll ;; :domain.trim+.e*als+55 0 cookie.set=omain+domain3 9
tring path 1 re*est.get4arameter+5path53 i6 +path :1 nll ;; :path.trim+.e*als+55 0 cookie.set4ath+path3 9
tring secre 1 re*est.get4arameter+5secre53 i6 +secre :1 nll ;; secre.e*als+5on5 0 cookie.setecre+tre3 9 else 0 cookie.setecre+6alse3 9 retrn cookie3
9
8. The asterisk in the file's tab at the top of the Source Editor appears whenever there are changes
that have not been saved to disk:
Press Ctrl-S to save the document. The asterisk in the file's tab at the top of the Source Editor
disappears.
9. In the Projects window, right-click the FrontController.java node and select Compile File (F9) to
check that there were no errors introduced in the steps you have completed. The Output window
displays messages from the compiler, including any errors. You can double-click the links in the
error messages to locate the source of the error. Resolve all errors listed in the Output window
before continuing with the tutorial.
Creating the JSP page that receives all the requests
The main.jsp page receives all the requests that the FrontController servlet processes. A dynamic
include statement and a LinksHandler are used to create the page.
1. Expand the Midnight project node and the WEB-INF node. Right-click the docs node, choose
New > JSP, and name the JavaServer Pages file main. Click Finish.Now main.jsp opens in the Source Editor.
2. In the Source Editor, replace the contents of the main.jsp file with the following code:
>?@page content#$pe15text/html3charset12#F-A5? >?@page b66er15none5? >?-- #he >midnight(content/ tag which handles the contents section is simplisticall$ implemented to se an inclde. ,ence this page cannot be b66ered --?
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 12/87
>?@taglib pre6ix15midnight5ri15http(//www.midnightcookies.com/midnight5?
>html >head>title#he "idnight !ookie !ompan$>/title>/head >bod$ text15CDD5 link15CccGG5 'link15CDDGG5 alink15CGGGGGG5 >span 6ont-st$le15sans-seri65 >#<BHE border15G5
>tr >table border15G5 >tr>td width15AG5 height15GG5;nbsp3>/td >td width15JGG5 height15GG5
text15CDD5 bgcolor15C6666DD5 'align15center5halign15center5 >jsp(inclde page15/WEB-INF/docs/header.jsp5 6lsh15tre5/ >/td >/tr >tr>td width15DG5 height15GG5
text15CDD5 bgcolor15C6666DD5 'align15top5 >midnight(links separator15>br5/ >/td >td width15JGG5 height15GG5 'align15top5cellpadding15J5 cellspacing15J5 >midnight(content/ >/td >/tr >/table >/tr >tr>td width15JAG5 height15JG5 text15CDD5
bgcolor15C6666DD5 'align15top5 >midnight(links separator1585/ >/td >/tr >/#<BHE >/span >/bod$ >/html
Note: After you enter code (either by typing or copying and pasting) into the Source Editor,
place the cursor in the Source Editor and press Alt-Shift-F to automatically format the code.
3. Press Ctrl-S to save your changes.
Creating the parameter files used to handle user input
The parameter files that you create in this section illustrate the use of tags from tag libraries to handle
internationalization. They also show how input is passed through the Request parameters, specifically
through the JSP expression language (EL) expression K0param.inpt9, which is set in the input
field of the Inpt.jsp page.
1. Right-click the docs node and select New > Other from the contextual menu. Under Categories,
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 13/87
select Other and under File Types, select Folder. Click Next.
2. In the Name and Location panel, type parameters in the Folder Name text field and click
Finish. The new parameters folder appears in the Projects window under the docs node.
3. Right-click the parameters node and choose New > JSP. Type Inpt in the JSP File Name text
field and make sure that WEB-INF/docs/parameters is selected in the Folder text box.
Click Finish. Now Inpt.jsp opens in the Source Editor.
4. In the Source Editor, replace the contents of the Inpt.jsp file with the following code:>?@page content#$pe15text/html3charset12#F-A5?
>?@taglib pre6ix156mt5 ri15http(//ja'a.sn.com/jstl/6mt5 ? >?@taglib pre6ix15c5 ri15http(//ja'a.sn.com/jstl/core5 ? >?@taglib pre6ix15midnight5 ri15/WEB-INF/tlds/midnight.tld5?
>6mt(setBndle basename15com.midnightcookies."idnight5 'ar15bndle5 scope15page5/
>h>6mt(message ke$15pro'ideLinpt5 bndle15K0bndle95/>/h >6orm method154#5 action15tpt.jsp5 >table >tr >td>6mt(message ke$15t$peLinpt5 bndle15K0bndle95/(>/td >?-- #he 'ale o6 the Inpt 6ield will be placed in a re*est parameter named 5inpt5 and it will be passed to tpt.jsp --? >td>inpt t$pe15text5 size15MG5 name15inpt5'ale155>/td >/tr >tr >td>6mt(message ke$15sbmit5 bndle15K0bndle95 'ar15bttonHabel5 scope15page5/ >midnight(btton/ >/td
>td>/td >/tr >/table >/6orm
Press Ctrl-S to save your changes.
5. Create an tpt.jsp file in the Parameters folder using the same method that you used to
create the Inpt.jsp file.
6. In the Source Editor, replace the contents of the tpt.jsp file with the following code:
>?@page content#$pe15text/html3charset12#F-A5? >?@ taglib pre6ix156mt5 ri15http(//ja'a.sn.com/jstl/6mt5 ?
>?@ taglib pre6ix15c5 ri15http(//ja'a.sn.com/jstl/core5 ?
>6mt(setBndle basename15com.midnightcookies."idnight5 'ar15bndle5scope15page5/ >h>6mt(message ke$15displa$Linpt5 bndle15K0bndle95/>/h >6mt(message ke$15datarecei'ed5 bndle15K0bndle95/(
>:--#he 6ollowing line gets the 'ale o6 the re*est parameter named 5inpt5. #his is a demo application. For secrit$ reasons& one shold ne'er echo ser inpt withot parsing 6irst. -- >c(ot 'ale15K0param.inpt95/
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 14/87
7. Press Ctrl-S to save your changes.
Using JSTL to handle internationalization
The #ra$.jsp page that you create in this section illustrates the use of the JSTL, instead of scripting,
to internationalize the page. The !ookie!tter.jsp file, !ookie"aker.jsp file, and resource
bundle property files have been provided with the midnight.zip file. You can take a closer look atthose files and the #ra$.jsp file for examples of how internationalization is handled in this
application.
1. Expand the docs node and expand the cookies node.
2. Create a #ra$.jsp file in the cookies folder using the same method that you used to create
the other JSP files. Make sure that you put it in the cookies folder.
3. In the Source Editor, replace the contents of the #ra$.jsp file with the following code:
>?@page content#$pe15text/html3charset12#F-A5? >?@ taglib pre6ix15c5 ri15http(//ja'a.sn.com/jstl/core5 ? >?@ taglib pre6ix156mt5 ri15http(//ja'a.sn.com/jstl/6mt5 ?
>6mt(setBndle basename15com.midnightcookies."idnight5 'ar15bndle5scope15page5/ >h>6mt(message ke$15cookies5 bndle15K0bndle95/>/h
>table border155 >tr >th halign15center5C>/th >th align15le6t5 >6mt(message ke$15name5 bndle15K0bndle95/ >/th >th align15le6t5 >6mt(message ke$15'ale5 bndle15K0bndle95/ >/th
>tr >?-- We ha'e to se expression to get at an arra$. I6 we se K0cookie9 then we get a map and the entries are not atomaticall$ cast --? >? re*est.set<ttribte+5cookies5& re*est.get!ookies+3 ? >c(set 'ar15i5 'ale15G5/
>c(6orEach 'ar15ck5 items15K0cookies95 >c(set 'ar15i5 'ale15K0i795/ >tr >td>c(ot 'ale15K0i95/>/td >td>c(ot 'ale15K0ck.name95/>/td >td>c(ot 'ale15K0ck.'ale95/>/td
>/tr >/c(6orEach >/table
4. Press Ctrl-S to save your changes.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 15/87
Wrapping up
Once you have completed the development stage as described above, the views in the Projects window
and Files window should look as follows:
Note: The application illustrated above deploys to the Tomcat Web Server. If you have registered and
selected a different target server instead, you will not have a META-INF/context.xml file. For example,
if your server is GlassFish, you will have a WEB-INF/sun-web.xml file as your deployment descriptor.
Running and Monitoring the Application
Enabling the HTTP Monitor
The HTTP Monitor is enabled by default for the Tomcat Web Server. However, for other servers, you
must manually enable the HTTP Monitor. In addition, the HTTP Server must be started for the HTTP
Monitor to work for other servers.
Do the following to prepare to use the HTTP Monitor:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 16/87
1. Choose Tools > Servers from the main window.
2. Select the server.
3. Click Enable HTTP Monitor and then click Close.
4. In the Runtime window, right-click the HTTP Server node and choose Start HTTP Server.
Verifying the Context Path
1. Right-click the Midnight project node and choose Properties.
2. In the Project Properties dialog box, click Run.
3. Make sure that the Context Path is set to /"idnight.
4. Make sure that the Relative URL is set to docs/index.jsp
Running the application
1. In the Projects window, right-click the Midnight project node and choose Run from the
contextual menu.
Note: By default, the project has been created with the Compile on Save feature enabled, so youdo not need to compile your code first in order to run the application in the IDE. For more
information on the Compile on Save feature, see the Compile on Save section of the Creating,
Importing, and Configuring Java Projects guide.
A progress monitor window appears as the application is prepared and deployed to the web
server.
The web browser launches with the URL set to http(//hostname:port /"idnight. The
following example shows the web browser running on a Microsoft Windows platform.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 17/87
2. In the IDE, notice that the HTTP Monitor is displayed.
The following sections illustrate how you can use the HTTP Monitor to monitor requests,
sessions, and cookies.
Monitoring requests and sessions
1. In the HTTP Monitor, select the last entry under the Current Records node.
The last entry represents the request for the Midnight web application.
2. Select the Request tab and you see information similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 18/87
3. Select the Session tab and you see information similar to the following.
4. In your web browser, click the Parameters link to display the Inpt.jsp page. Your web
browser displays information similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 19/87
5. In the Type Input text field, type hello and click Submit data.
Your web browser displays the contents of the tpt.jsp page, similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 20/87
6. In the HTTP Monitor, select the last entry under the Current Records and select the Request tab.
The HTTP Monitor displays information similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 21/87
Monitoring cookies
1. In your web browser, click the Cookies link.
Your web browser displays the !ookie!tter.jsp page.
2. In the Name text field, type cookie, and in the Value text field, type chocolate.
3. Click "Make me a cookie now!".
Your web browser displays information similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 22/87
4. In the HTTP Monitor, select the last entry under the Current Records node.
The Cookies tab in the HTTP Monitor displays information similar to the following.
5. In your web browser, click Cookie tray, and your web browser displays information similar to
the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 23/87
6. In the HTTP Monitor, select the last entry under the Current Records node and select the
Cookies tab.
The HTTP Monitor displays information similar to the following.
7. Select the Request tab and the HTTP Monitor displays information similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 24/87
8. In the HTTP Monitor, right-click the same entry (GET Tray.jsp) under the Current Recordsnode and choose Edit and Replay from the contextual menu. In the Edit and Replay dialog box,
click the Cookies tab and click Add Cookie. Set the name to Ingredient and the value to Sugar.
Click Send HTTP Request. The browser redisplays the page with the new cookie.
Monitoring requests for non-existent pages
1. In your web browser, type a URL for a page that does not exist to see how the nonesch.jsppage is used. For example, you might type
http(//localhost(AGA/"idnight/docs/Bake.jsp for the URL and your web
browser displays something similar to the following.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 25/87
2. In the HTTP Monitor, select the Request tab and you will see information similar to the
following.
Notice that the content of nonesch.jsp page is displayed in place of the non-existent
Bake.jsp page.
Enabling internationalization
1. Modify the language preference used by your web browser to either French or Swedish in order
to see the internationalization feature of this Midnight Cookie Company web application.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 26/87
Note that you might have to add these two languages to the list of languages currently available
to your web browser.
2. Reload or refresh the pages you have viewed in the previous steps.
Notice how the links in the left navigation bar, the links on the bottom of the pages, and the
contents of some of the application's JSP pages have been translated to the language you have
chosen.The web application uses the resource bundle property files to help translate some of the pages
used in this web application. So, the translation is only as extensive as the contents of the
resource bundle property files.
Applying What You Have Learned
Add an Exit link that takes the user to a page that says "Goodbye" in the
appropriate language
1. Right-click the com/midnightcookies/"idnight.properties file and choose Open
from the contextual menu. Add the following keywords and values.
Keyword Default French Swedish
exit Exit Sortie Utgång
closingRemark Goodbye Au revoir Hej då
Use å to display the å character.
2. Add an Exit.jsp content file. Use the message tag from the fmt tag library to display the message
for the closingRemark keyword (Hint: look at Output.jsp). Do not forget to add a taglib directive
for the fmt tag library.
3. Open the com/midnightcookies/taghandlers/LinksHandler.java file in the Source Editor and add
a link to the Exit.jsp file. Use the exit keyword to get the link text from the properties bundle.
Compile the class.
4. Execute the web application.
Exploring Further
Below are some other web application features that you might want to explore.
Examining the Midnight tag library
Expand the tlds/"idnight node to see the list of tags in the library. Look at the the Links tag in
the Source Editor and at its Attributes to see that it takes a separator attribute.
Debugging web applications
Open the docs/main.jsp file in the Source Editor and set a breakpoint by clicking in the margin at
approximately line 32 (the line that invokes midnight:content). Right-click the project node in the
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 27/87
Projects or Files window and choose Debug Project from the contextual menu. The web application
will stop at the breakpoint that you set. Press F7 to step into the code. Whenever a dialog appears
because of missing source, press OK to select the default of stopping at the first line with source.
Continue pressing F7 until you enter the otherDoStartTagOperations() function in the ContentHandler
class. Set a breakpoint at line 50 (request.getRequestDispatcher(page).include(request, response)) and
press Ctrl-F5 (continue). Place the cursor over "page", "request", and "response" to see the values. You
can also see the values in the Local Variables tab. Note that the Call Stack tab shows the relationshipbetween the JSP code and the generated servlet methods. Try setting other breakpoints. Right-click a
variable and choose New Watch from the contextual menu. Click the Watches tab to see the values
change as you execute the various pages in the web application. Choose Debug > Finish Session to quit
the debugging session.
Testing JSP files
To run a public JSP file (one that is not under the WEB-INF folder), you simply right-click the file's
node and choose Execute from the contextual menu. If a page is loaded, clicking the Browser's reload
button will display any modifications that you have made. Private JSP files, like the ones in this
tutorial, are a little harder to execute. One way to test a modified private JSP file without having torestart the web application and navigate to that page is to use the HTTP Monitor's replay action. Modify
the docs/cookies/Tray.jsp file by setting the table's border to 10 and save your changes. In the HTTP
Monitor, right-click a GET Tray.jsp record and choose Replay from the contextual menu. The Tray.jsp
page should appear in the browser with a larger table border.
Creating a Simple Web Application Using a
MySQL DatabaseThis 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 "$New=atabase, which you have registered a connectionfor 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, bject and !onselor, 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 "$New=atabase.
Contents
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 28/87
• 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 taglib 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 Version Required
NetBeans IDE version 6.x Java
Java Development Kit (JDK) version 5 or 6
MySQL database server version 5.x
MySQL Connector/J JDBC Driver version 5.x
GlassFish application serveror
Tomcat servlet container
V2 UR2 or V3 Prelude
version 6.x
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.
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
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 29/87
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 (index.jsp) presents the user with a simple HTML form. When a client requests
the index.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 response.jsp. When
response.jsp 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 (index.jsp), then retrieves data from the MySQL database and returns the
information to the user (response.jsp).
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 30/87
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
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 31/87
(index.jsp) in the Source Editor. index.jsp 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 index.jsp and response.jsp
implement an HTML table to display data in a structured fashion. index.jsp also requires an HTMLform that includes a drop-down list.
index.jsp
Make sure index.jsp is opened in the Source Editor. If it is not already open, double-click
index.jsp from IFPWAFCAD > Web Pages in the Projects window.
1. In the Source Editor, change the text between the >title tags to IF4W<F!<= ,omepage.
2. Change the text between the >h tags (>hM tags if you are using NetBeans 6.0 or 6.1) to
Welcome to IF4W<F!<=& the International Former 4ro6essional
WrestlersO <ssociation 6or !onseling and =e'elopment:.
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 >h (or >hM tags). In the Insert Table dialog that displays, specify the following values
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 32/87
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):
>table border15G5 >thead >tr >thIFPWAFCAD offers expert counseling in a wide range offields.>/th >/tr >/thead >tbod$ >tr >tdTo view the contact details of an IFPWAFCAD certified former professional wrestler in your area select a su!"ect !elow# >/td >/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 >td tags. In the Action text box, type in
response.jsp, then click OK.
6. Type in the following text between the >6orm tags of the form you just created:
>strongelect a sbject(>/strong
7. Drag and drop a drop-down list from the Palette to a point just after the text you just added. In
the Insert Drop-down dialog that displays, type in sbjectLid 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 sbmit 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:
>bod$ >hMWelcome to >strongIF4W<F!<=>/strong& the International Former 4ro6essional WrestlersO <ssociation 6or !onseling and =e'elopment: >/hM
>table border15G5 >thead >tr >thIF4W<F!<= o66ers expert conseling in a wide range o6
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 33/87
6ields.>/th >/tr >/thead >tbod$ >tr >td#o 'iew the contact details o6 an IF4W<F!<= certi6ied6ormer pro6essional wrestler in $or area& select a sbject
below( >/td >/tr >tr >td >6orm action15response.jsp5 >strongelect a sbject(>/strong >select name15sbjectLid5 >option>/option >/select >inpt t$pe15sbmit5 'ale15sbmit5 name15sbmit5 / >/6orm >/td
>/tr >/tbod$ >/table>/bod$
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 response.jsp 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.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 34/87
2. In the JSP File Name field, enter response. 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 index.jsp welcome page resides.
3. Accept any other default settings and click Finish. A template for the new response.jsppage 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 IF4W<F!<= - 0placeholder9.
5. Remove the >h,ello World:>/h (or >hP4 4age>/h if you are working in
NetBeans 6.0 or 6.1) line between the >bod$ tags, then copy and paste the following HTML
table into the body of the page:
>table border15G5 >thead >tr >th colspan15M50placeholder9>/th >/tr >/thead >tbod$ >tr >td>strong=escription( >/strong>/td >td>span st$le156ont-size(smaller3 6ont-st$le(italic350placeholder9>/span>/td >/tr >tr >td>strong!onselor( >/strong>/td >td0placeholder9 >br
>span st$le156ont-size(smaller3 6ont-st$le(italic35 member since( 0placeholder9>/span >/td >/tr >tr >td>strong!ontact =etails( >/strong>/td >td>strongemail( >/strong >a hre615mailto(0placeholder950placeholder9>/a >br>strongphone( >/strong0placeholder9 >/td
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 35/87
>/tr >/tbod$>/table
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
response.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 StyleSheet and click Next.
2. Type st$le for CSS File Name and click Finish. The IDE creates an empty CSS file and
places it in the same project location as index.jsp and response.jsp. Note that a node
for st$le.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 st$le.css file:
bod$ 0 6ont-6amil$( Qerdana& <rial& sans-seri63 6ont-size( smaller3 padding( JGpx3
color( CJJJ39
h& hM 0 text-align( le6t3 letter-spacing( px3 6ont-size( .em3 color( CbeRMD3 6ont-weight( normal3 width( JGpx39
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 36/87
table 0 width( JAGpx3 padding( Gpx3 backgrond-color( CcJeReG39
th 0
text-align( le6t3 border-bottom( px solid39
td 0 padding( Gpx39
a(link 0 color( CbeRMD3 6ont-weight( normal3 text-decoration( none39
a(link(ho'er 0 color( CbeRMD3 6ont-weight( normal3 text-decoration( nderline39
4. Link the stylesheet to index.jsp and response.jsp:
In both pages, add the following line between the >head tags:
>link rel15st$lesheet5 t$pe15text/css5 hre615st$le.css5
This document assumes that you understand how the stylesheet functions, and how it affects
corresponding HTML elements found in index.jsp and response.jsp.
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& hM rule in st$le.css, then open CSS Preview
(Window > Other > CSS Preview):
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 37/87
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 jdbc/IF4W<F!<=. Click Next.
3. Click Next again to skip Additional Properties, then in Step 4, type in I6pwa6cad4ool for
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 38/87
JDBC Connection Pool Name. Make sure the Extract from Existing Connection option is
selected, and choose jdbc(m$s*l(//localhost(G/"$New=atabase 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 "$New=atabase 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 > sn-resorces.xml file and note
that, within the >resorces 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 (orUndeploy 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:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 39/87
Tomcat
Configure a JNDI Datasource in Tomcat by adding a declaration for your resource to the application's
context.xml 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
K!<#<HIN<L,"E/con6/context.xml file. By adding resource declarations to your
application's context.xml 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 > context.xml file.
2. Add the following >)esorce tags (changes below in bold) as a declaration for the JNDI
resource:
>Sxml 'ersion15.G5 encoding152#F-A5S
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 40/87
>!ontext path15/IF4W<F!<=5 $%esource name&'"d!c(IFPWAFCAD' auth&'Container'type&'"avax.s)l.Data*ource' maxActive&'+,,' maxIdle&'-,' maxWait&'+,,,,' username&'root' password&'n!user'driverClassame&'com.mys)l."d!c.Driver' url&'"d!c#mys)l#((localhost#--,/(0yewData!ase'(1>/!ontext
Notice that the declaration is using root and nbser 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 (web.xml).
Deployment descriptors are XML-based text files that contain information describing how anapplication 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 (jdbc/IF4W<F!<=). The Description field is optional, but
you can enter a human-readable description of the resource, e.g., =atabase 6orIF4W<F!<= application. Note that the default resource type is
ja'ax.s*l.=ataorce. Leave all fields that are provided by default and click OK. The
new resource is added under the Resource References heading:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 41/87
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 <resorce-re6> tags are now
included:
>resorce-re6 >description=atabase 6or IF4W<F!<= application>/description >res-re6-namejdbc/IF4W<F!<=>/res-re6-name >res-t$peja'ax.s*l.=ataorce>/res-t$pe >res-ath!ontainer>/res-ath >res-sharing-scopehareable>/res-sharing-scope>/resorce-re6
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 m$s*l-connector-ja'a-J.x-bin.jar 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.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 42/87
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 domains >
domain > lib 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'sOutput 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 domain/lib subfolder on your computer, you can see that the
m$s*l-connector-ja'a-J.x-bin.jar 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 domain, 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.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 43/87
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 domains >
domain > lib subfolder. If you have already deployed your project to the server, you will
find that them$s*l-connector-ja'a-J.x-bin.jar
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 domain/lib subfolder on your computer, you can see that the
m$s*l-connector-ja'a-J.x-bin.jar 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 domain, which is the default domain created upon installing GlassFish. You can
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 44/87
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 lib folder.
If you have already deployed your project to the server, you will find that the m$s*l-connector-ja'a-J.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 <install-dir>/lib in the Tomcat server.
5. Reopen the Servers window (Tools > Servers) and view the JAR files listed under the Classes
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 45/87
tab. You can see that the MySQL driver has been automatically added.
Adding Dynamic Logic
If you return to the index.jsp and response.jsp 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 taglib 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 webproject's compilation classpath, then add the relevent taglib 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,
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 46/87
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
standard.jar, and the jstl.jar. You can further expand the standard.jar file to
view JSTL's four basic areas of functionality.
The JSTL library includes four basic areas of
functionality:
• core : common, structural tasks such as
iteration and conditionals
• fmt : internationalization and locale-
sensitive formatting tags
• sql : SQL tags
• 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 appser'-jstl.jar file, which defines all
standard tags in the JSTL library.
Adding tagli! Directives to the JSP Pages
Regardless of what server you are using, you need to add the necessary taglib directives to JSP
pages:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 47/87
1. Open both index.jsp and response.jsp in the Source Editor. Add the following
directives to the top of both pages:
>?@taglib ri15http(//ja'a.sn.com/jsp/jstl/core5 pre6ix15c5?>?@taglib ri15http(//ja'a.sn.com/jsp/jstl/s*l5 pre6ix15s*l5?
Adding JSP and JSTL CodeFinally, 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 index.jsp, you need to access all names
from the Subject database table:
1. Add the following SQL query beneath the taglib directives you added in the previous step:
>s*l(*er$ 'ar15sbjects5 dataorce15jdbc/IF4W<F!<=5
EHE!# sbjectLid& name F)" bject>/s*l(*er$
The JSTL <sql:query> tags enable you to use SQL query language directly in a JSP page. A
resltset is generated from the query, and the acquired data can then be inserted into the
page using an iterator tag (<c:forEach>) from the JSTL core library.
2. Replace the empty >option tags in the HTML form with the following iterator (changes in
bold):
>select name15sbjectLid5 $c#for2ach var&'su!"ect' items&'34su!"ects.rows5'1 $option value&'34su!"ect.su!"ect6id5'134su!"ect.name5$(option1
$(c#for2ach1>/select
The 6orEach tag loops through all id and name values from the generated resltset, and
inserts each pair into the HTML option 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 index.jsp renders in the browser. The drop-
down list now contains subject names that were retrieved from the database:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 48/87
response.jsp
For response.jsp, you need to access data from both the bject and !onselor tables that
correspond to the id 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 taglib directives you added in the previous step:
>s*l(*er$ 'ar15consbj)s5 max)ows155 dataorce15jdbc/IF4W<F!<=5 EHE!# s.name& s.description& c.6irstLname& c.nickLname& c.lastLname& c.memberLsince& c.telephone& c.email F)" bject as s& !onselor as c W,E)E c.conselorLid 1 s.conselorLid6k <N= s.sbjectLid 1 S >s*l(param 'ale15K0param.sbjectLid95/>/s*l(*er$
A resltset named consbj)s is generated from the above SQL query, which contains
all data associated with the sbjectLid submitted by the user. Note that data from the
!onselor table is acquired by mapping conselorLid6k from bject to
conselorLid from !onselor.
2. Add the following declaration beneath the SQL query from the previous step:
>c(set 'ar15consbj5 scope15re*est5 'ale15K0consbj)s.rowsTGU95/
The <c:set> tag enables you to set the resltset 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 thedata held in the consbj resltset (Changes below shown in bold):
>html >head >meta http-e*i'15!ontent-#$pe5 content15text/html3 charset12#F-A5/ >link rel15st$lesheet5 t$pe15text/css5 hre615st$le.css5 >title34couns*u!".name5>/title >/head
>bod$
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 49/87
>table >tr >th colspan15M534couns*u!".name5>/th >/tr >tr >td>strong=escription( >/strong>/td >td>span st$le156ont-size(smaller3 6ont-st$le(italic3534couns*u!".description5>/span>/td >/tr >tr >td>strong!onselor( >/strong>/td >td>strong34couns*u!".first6name5 34couns*u!".nic76name5 34couns*u!".last6name5>/strong >br>span st$le156ont-size(smaller3 6ont-st$le(italic35 >emmember since( 34couns*u!".mem!er6since5>/em>/span>/td >/tr >tr >td>strong!ontact =etails( >/strong>/td >td>strongemail( >/strong >a hre615mailto(34couns*u!".email5534couns*u!".email5>/
a >br>strongphone( >/strong34couns*u!".telephone5>/td >/tr >/table >/bod$>/html
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 B2IH= 2!!EF2H 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
index.jsp page opens in the IDE's default browser.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 50/87
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 index.jsp displays in the browser, select a subject from the drop-down list and click
sbmit. You should now be forwarded to the response.jsp page, showing detailscorresponding to your selection:
Using Java Persistence in a Web ApplicationThis document is a basic introduction to using the Java Persistence API in a web application and
demonstrates how the development process using the JavaTM Platform, Enterprise Edition 5 ("Java EE
5") technology simplifies the development of Java applications.
In this document you will use the IDE to create a web application that will access a database. In the
web application, you will use the IDE to generate entity classes corresponding to tables in a database.
You will then create a servlet that displays the information in the database. The application uses Java
Persistence to manage the database transaction.
This document uses the NetBeans IDE 6.5 Release, but the steps generally apply to all 6.x versions of
the IDE.
To see how to connect to a database in a Visual Web application, see Using the Java Persistence API
Within a Visual Web JSF Application.
Tutorial Exercises
• Configuring the IDE to Use the Application Server
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 51/87
• Setting Up the Web Application Project
• Coding the Web Application
• Running the Project
To follow this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE 6.5 Java, or 6.0/6.1 Web & Java EE
Java Development Kit (JDK) version 6 or version 5
GlassFish application server V2
Prerequisites
This document assumes you have some basic knowledge of, or programming experience with, the
following technologies:
• Java Programming
• NetBeans IDE
Configuring the IDE to Use the Application Server
For this tutorial you must have an instance of Glassfish V2 or the Sun Java System Application Server
Platform Edition 9 registered with the IDE. In this exercise you will register the application server with
the IDE. If the application server is already registered and visible in the Services window, you can go to
Setting Up the Web Application Project.
1. Choose Tools > Servers from the main menu.
2. Click Add Server. Select your application server (GlassFish or Sun Java System Application
Server) and give a name to the instance. Then click Next.
3. Specify the installation directory of the application server (for example,
!(VnV<ppser'er).4. Leave the Register Local Default Domain radio button selected and select a domain.
5. Optionally, click Next and enter your administrator username and password. If you do not want
to store the username and password in your IDE user directory, you can leave these fields blank.
The IDE will prompt you every time it needs the information.
Note: The default admin password is adminadmin.
6. Click Finish. The IDE registers the server and lists it under the Servers node in the Services
window.
Summary
In this exercise you registered the application server with the IDE.
Setting Up the Web Application Project
In this example developing for the Java EE 5 platform, you do not need a full enterprise application
because you do not need an EJB module or session beans. Instead, you can create a simple web
application and put the entity classes directly in the web application.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 52/87
1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category.
2. Type CustomerBook for the project name and set the project location.
3. Deselect the Use Dedicated Folder option, if selected.
(This option is not available if you are using NetBeans IDE 6.0.)
For this tutorial there is little reason to copy project libraries to a dedicated folder because you
will not need to share libraries with other users or projects.
Click Next.
4. Set the server to GlassFish and set the Java EE Version to Java EE 5. Click Finish.
Summary
In this exercise you created a Java EE 5 web application which will contain the entity classes and
servlet.
Coding the Web Application
Generally some basic setup is necessary before you can start coding the web application. This would
include establishing a connection with the database and creating a connection pool and data source.
Because you are using the jdbc/sample database that comes bundled with the IDE, much of this is
already configured. The connection to the database is already registered with the IDE and the
connection pool and data source are already created. You can view the connection and data source
properties in the Services window.
If you want to use a different database, you need to register a connection and create a data source for the
database.
Once the setup is complete, development for the Java EE 5 platform is much easier than before because
the container does more of the work. Because the container is managing persistence, you do not need toedit any deployment descriptors to configure the CMP mappings or specify the finder methods. In fact,
in this example you do not need any deployment descriptors at all. In the Java EE 5 platform,
persistence is no longer limited to an EJB component. Java EE 5 introduces the Java Persistence API,
which can be used by non-EJB components, such as a web application.
Java EE 5 technology also eliminates the need for a lot of the boilerplate code needed in J2EE 1.4
development. EJB development has been streamlined so that fewer interfaces are needed, lookup is
simpler, and annotations make component definition and resource injection simple and clear.
Managing Persistence
To manage persistence in the application you only need to create a persistence unit, specify which data
source and entity manager to use, and then let the container do the work of managing entities and
persistence. The container discovers the entity beans at runtime.
You create a persistence unit by defining it in persistence.xml. The project does not contain a
persistence.xml yet so you need to create it. The persistence.xml file is created
automatically when you add a persistence unit to the project with the New Persistence Unit wizard. The
wizard will help you define the properties of the persistence unit.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 53/87
You can also create a persistence unit in the New Entity Class wizard. When creating an entity class,
the wizard will prompt you to create a persistence unit if one does not exist.
1. Choose New File (Ctrl-N) to open the New File wizard.
2. From the Persistence category, select Persistence Unit and click Next.
3. Leave the default name for the persistence unit suggested by the wizard.
4. Use the #opHink +de6alt listed in the Persistence Provider drop-down list.
The default provider is the #opHink Essential.jar. #opHink Essential.jarcontains the libraries for Java Persistence. Our entity manager is located in #opHinkEssential.jar.
5. Use the default jdbc/sample data source listed in the Data Source drop-down list.
The default data source jdbc/sample is used to connect to the Java DB database that is
bundled with GlassFish application server.
6. Click Finish.
When you click Finish, persistence.xml is created for your project and opens in the editor. You
can click XML in the toolbar of the editor to see the XML view of persistence.xml. This file
contains all the information the Java EE 5 container needs to manage the entities and persistence of our
application.
Creating the Entity Classes
When developing for the J2EE 1.4 platform, when you created entity beans you placed them in an EJB
module even when the application was a simple web application. Each entity bean required several
interfaces, and you had to configure the deployment descriptors in ejb-jar.xml to define the entity
beans, the interfaces, persistence and finder queries for each entity bean.
In Java EE 5, instead of creating entity beans and putting them in the EJB module, you can use simple
entity classes, and the entity classes can be placed anywhere in a Java EE 5 application. Writing classes
for Java EE 5 applications is also easier than it was for the J2EE 1.4 platform because you can use
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 54/87
annotations to define components and inject resources.
You will now use the Entity Classes from Database wizard to create the entity classes based on the
relational database.
1. Start the Java DB database server.
2. Choose New File (Ctrl-N) to open the New File wizard. Select Entity Classes from Database
from the Persistence category and click Next.3. In the Entity Classes from Database wizard, select the jdbc/sample data source for our
database from the Data Source drop-down list and supply the password if necessary. (The
password should be "app".) When you select the data source, a list of available tables appears in
the Available Tables pane.
4. Select the !2#"E) table from the Available Tables and click Add.
When you click Add, any tables related to the selected table are also added. In this example, the
=I!2N#L!=E table is also added. =I!2N#L!=E table is greyed-out because it is
referenced by !2#"E) table and an entity class for it must be generated in order to generate
the !stomer entity class. When you hover your mouse over a greyed-out table in the Selected
Tables pane, a tooltip appears that displays the name of the table that references the greyed-out
table.
5. Click Next.
The wizard displays the selected table and any related tables. The wizard also displays the entity
classes that will be created based on the selected tables. If you want to modify the name of the
class that will be generated, you can type the name in the Class Name field.
6. Type ejb as the package for the generated classes. Click Finish.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 55/87
When you click Finish, the IDE generates entity classes for the !2#"E) table and the tables related
to !2#"E) table. If you expand the ejb source package in the Projects window you can see that the
IDE created the Java classes !stomer.ja'a and =iscont!ode.ja'a. You can see that the
IDE created only two classes, one for each of the database tables.
If you look at !stomer.ja'a in the Source Editor, you will notice that the @Entit$ annotation is
used to declare the class an entity class. Other annotations provide additional information such as the
database table and the columns that the entity class and its properties are mapped to.
You will also notice that much of the boilerplate code commonly found in entity beans is gone.
Methods such as ejb)emo'e, set"essage, setession!ontext, ejb<cti'ate, and
ejb4assi'ate are no longer needed in your entity class in Java EE 5.
Coding the Servlet
You now need to add a servlet to the web application. Instead of adding resource creation and lookup
code to the servlet, with Java EE 5 you can use resource injection to move that work to the container.
You can use annotations to inject resources directly into the servlet, and the container will manage the
creation and lookup of the requested resource. In this case, you want to use an entity manager asspecified in the persistence unit.
1. Right-click the project node in the Projects window and choose New > Servlet.
2. In the New Servlet wizard, name the servlet !stomer=etails and put the servlet into a
package named web. Click Finish. When you click Finish, !stomer=etails.ja'a opens
in the Source Editor.
3. In the source editor, right-click in !stomer=etails.ja'a and choose Persistence > Use
Entity Manager to inject the PersistenceContext in the class. The IDE adds the following
annotation that specifies the persistence unit used by the servlet. The annotation is added above
the class declaration.
@4ersistence!ontext+name 1 5persistence/HogicalName5& nitName 15!stomerBook425
The IDE also adds the following annotation injecting a resource for managing transaction
boundaries:
@)esorce pri'ate ja'ax.transaction.2ser#ransaction tx3
If you expand the editor fold you can see that the IDE adds the following default persistmethod code to the servlet:
pblic 'oid persist+bject object 0 tr$ 0 !ontext ctx 1 +!ontext newja'ax.naming.Initial!ontext+.lookp+5ja'a(comp/en'53 tx.begin+3 Entit$"anager em 1 +Entit$"anagerctx.lookp+5persistence/HogicalName53 em.persist+object3 tx.commit+3 9 catch+Exception e 0
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 56/87
Hogger.getHogger+get!lass+.getName+.log+He'el.EQE)E&5exceptioncaght5& e3 throw new )ntimeException+e3 9 9
This code looks up the persistence unit defined by @4ersistence!ontext and an instance
of the entity manager.
4. In !stomer=etails.ja'a, modify the generated persist method shown above to refer
to our entity object. When you are finished, the modified code should look like the following
(the code shown in bold indicates the changed lines):
pu!lic Customer find8yID9Integer customerr: 4 Customer customer & null; tr$ 0 !ontext ctx 1 +!ontext newja'ax.naming.Initial!ontext+.lookp+5ja'a(comp/en'53 tx.begin+3 Entit$"anager em 1 +Entit$"anager
ctx.lookp+5persistence/HogicalName53 customer & em.find9Customer.class customerr:; tx.commit+3 9 catch+Exception e 0 Hogger.getHogger+get!lass+.getName+.log+He'el.EQE)E&5exception caght5& e3 throw new )ntimeException+e3 9 return customer; 9
5. Uncomment the code in the process)e*est method and add the following code in bold:
protected 'oid process)e*est+,ttper'let)e*est re*est&,ttper'let)esponse response throws er'letException& IException 0 response.set!ontent#$pe+5text/html3charset12#F-A53 4rintWriter ot 1 response.getWriter+3 ot.println+5>html53 ot.println+5>head53 ot.println+5>titleer'let !stomer=etails>/title53 ot.println+5>/head53 ot.println+5>bod$53 out.println9'$h+1*earch Customer Information$(h+1':; *tring customerr & re)uest.getParameter9'customer6nr':; if99customerr <& null: == <9customerr.e)uals9''::: 4
Customer customer & find8yID9new Integer9customerr::; if9customer <& null:4 out.println9'Customer>s info for nr. ' ? customerr ? '# ' ?customer.getame9::; 5else4 out.println9'Customer not found.':; 5 5 out.println9'$form1':;
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 57/87
out.println9'Customer num!er# $input type&>text>name&>customer6nr> (1':; out.println9'$input type&su!mit value&*elect (1':; out.println9'$(form1':; ot.println+5>/bod$53 ot.println+5>/html53 ot.close+3 9
6. Press Ctrl-Shift-I to generate any missing import statements. (The servlet requires an import
statement for the Customer entity class.)
Running the Project
1. In the Projects window, right-click the CustomerBook project node and choose Properties. In
the Run panel of the Project Properties dialog box, type /!stomer=etails in the Relative
URL field and click OK.
2. Right-click the project node and choose Run Project. The IDE starts the application server,builds the project, and opens the CustomerDetails page in your browser.
3. Enter an ID number (for example, "1") in the Customer number field and click Submit. The
servlet shows you the name of the customer with that ID number.
Summary
In this exercise, you built the CustomerBook application using Java EE 5 technology. You then
deployed the project and tested the web application.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 58/87
Generating a JavaServer Faces CRUD
Application from a DatabaseIn this tutorial, you use the NetBeans IDE to generate and deploy a web application that displays data
from a database. The tutorial demonstrates how to generate a web application with CRUD (Create,Read, Update, Delete) functionality that uses the Java Persistence API (JPA) to manage the database
transaction. In the tutorial you first create entity classes based on tables in a database and then create
JavaServer Faces (JSF) pages from the entity classes using the JSF Pages from Entity Classes wizard.
The JSF Pages from Entity Classes wizard enables you to quickly and easily generate JSF pages for
working with a database based on the entity classes in your project. The wizard also gives you the
option to enable Ajax functionality in the generated JSF pages. The code generated by the wizard has
the following features:
• The code is easy to maintain and customize
• Handles all relationship types, generated and non-generated IDs, and embedded IDs, including
embedded ID fields that correspond to foreign key columns• Embedded ID fields are shown as read-only where appropriate
• Includes required checks to prevent non-nullable column violations and orphan checks to
prevent non-nullable column violations in related entities (by leveraging nllable or
optional annotation elements in the entity classes)
• Includes checks to verify that the current entity is correct in order to prevent errors if a user
deviates from the normal page flow (for example, when working in multiple browser tabs)
• Forgoes per-property code in certain files in case you later need to modify your database schema
• Fields can easily be removed from the generated JSPs to simplify customization
• Graceful handling of situations when a user attempts to operate on an entity that has been
deleted by another user or attempts to create an entity that already exists
• Pages can be styled easily
In addition to generating JSF pages for you, the JSF Pages from Entity Classes wizard incorporates the
functionality of the JPA Controller Classes from Entity Classes wizard. If you want to create JPA
controller classes for entity classes but do not want JSF pages generated for you, you can use the JPA
Controller Classes from Entity Classes wizard rather than the JSF Pages from Entity Classes wizard.
Note. This tutorial uses NetBeans IDE 6.5. If you are using NetBeans IDE 6.1, see Generating a
JavaServer Faces CRUD Application from a Database in NetBeans IDE 6.1.
Contents
• Creating the Database• Viewing the Database Structure
• Creating the Web Application Project
• Generating the Entity Classes from the Database
• Editing the Entity Classes
• Generating JSF Pages From Entity Classes
• Enabling Ajax in the Application
• Generating JPA Controller Classes From Entity Classes
• Adding Data to the Database
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 59/87
• Adding Data With an SQL Script
• Adding Data With the Web Interface
• Exploring Functionality in the Generated Code
• Read-only Primary Key Fields
• Generated Error Checks
To follow this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE 6.5 Java
Java Development Kit (JDK) Version 6 or version 5
GlassFish Application Server V2
Consulting Agency Database download SQL
Note. For the solution project to this tutorial (using the MySQL database), download
ConsultingAgency.zip.
Note. The GlassFish application server is included in the NetBeans download.
Creating the Database
This tutorial uses a consulting agency database called conslt. The database is not included when
you install the IDE so you need to first create the database to follow this tutorial.
The consult database was designed to demonstrate the scope of IDE support for handling a variety of
database structures. The database is thus not intended as an example of recommended database design
or best-practice. Instead, it attempts to incorporate many of the relevant features that are potentially
found in a database design. For example, the consult database contains all possible relationship types,
composite primary keys, and many different data types. See the tables below for a more detailed
overview of the database structure.
Note. If you created a Java DB version of the consult database using an older script, you should run the
derb$LdropLconsltL'.s*l script to drop the tables before creating the database again.
Note. This tutorial uses the JavaDB database server but you can also complete the tutorial using the
MySQL database server. To create the database in MySQL, download and extract the mysql-consult.zip
archive. The archive contains SQL scripts for creating and populating the consult database. For more
information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database
tutorial.
1. Download derby-consult.zip and extract the archive to your local system.
When you extract the archive you will see the SQL scripts for creating and populating thedatabase. The archive also has scripts for dropping tables.
2. In the Services window, expand the Databases node, right-click the JavaDB node and choose
Start Server.
3. Right-click the Java DB node and choose Create Database.
4. Type consult as the Database Name, User Name, and Password in the Create Java DB dialog.
Click OK.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 60/87
A new node appears under the Databases node
(jdbc(derb$(//localhost(JMR/conslt Tconslt on !N2H#U).
5. Right-click the new node and choose Connect.
6. Choose File > Open File from the main menu and navigate to the extracted file
derb$LcreateLconsltL'M.s*l. Click Open.
The file automatically opens in the the SQL editor.7. Make sure that the consult database is selected in the Connection drop-down list in the SQL
editor toolbar and click the Run SQL button.
When you click Run SQL, the following output appears in the Output window.
Note. If at any time you want to clear the database, you can drop the consult schema and tables by
running the derb$LdropLconsltL'M.s*l script included in the archive.
Viewing the Database Structure
To see the if the tables were created correctly, expand the Tables node under the database connection
node. You can expand a table node to see the table columns, indexes and any foreign keys. You can
right-click a column and choose Properties to view additional information about the column.
Note. If you do not see any tables under the Tables node, right-click the Tables node and choose
Refresh.
If you look at the structure of the consult database you can see that the database contains tables that
have a variety of relationships and various field types. When creating entity classes from a database, the
IDE automatically generates the appropriate code for the various field types.
The following table describes the tables found in the consult database.
Database Table Description Design Features
CLIENT A client of the consulting agency
Non-generated, composite primary key
(whose fields do not constitute a foreign
key)
CONSULTANT
An employee of the consulting
agency whom clients can hire on a
contract basis
Includes a resume field of type LONG
VARCHAR
CONSULTANT_STATUS
A consultant's status with the
consulting agency (for example,Active and Inactive are possible
statuses)
Non-generated primary key of type CHAR
RECRUITER
An employee of the consulting
agency responsible for connecting
clients and consultants
PROJECT A project that a client staffs with
consultants of the consulting agency
Non-generated, composite primary key
that includes two fields constituting a
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 61/87
foreign key to the CLIENT table
BILLABLE
A set of hours worked by a consultant
on a project, for which the consulting
agency bills the relevant client
Includes an artifact field of type CLOB
ADDRESS A client's billing address
PROJECT_CONSULTANT
Join table indicating which
consultants are currently assigned to
which projects
Cross-references PROJECT and
CONSULTANT, the former having a
composite primary key
The consult database includes a variety of relationships. When creating entity classes from a database,
the IDE automatically generates the properties of the appropriate Java type based on the SQL type of
the columns. The following table describes the entity relationships for the consult database. (The
inverse relationships are not shown.)
Entity Related Entity Relationship Information Description
CLIENT RECRUITER
nullable one-to-one with
manual editing; nullable one-
to-many if not edited
CLIENT has many RECRUITERs
and RECRUITER has zero or one
CLIENT (if not manually edited)
CLIENT ADDRESS non-nullable one-to-one
CLIENT has one ADDRESS and
ADDRESS has zero or one
CLIENT
CLIENT PROJECT
non-nullable one-to-many; in
a Project entity, the value of
the client field is part of the
Project's primary key
CLIENT has many PROJECTs
and PROJECT has one CLIENT
CONSULTANT PROJECT many-to-many
CONSULTANT has many
PROJECTs and PROJECT has
many CONSULTANTs
CONSULTANT BILLABLE non-nullable one-to-many
CONSULTANT has many
BILLABLEs and BILLABLE has
one CONSULTANT
CONSULTANT_S
TATUSCONSULTANT non-nullable one-to-many
CONSULTANT_STATUS has
many CONSULTANTs and
CONSULTANT has one
CONSULTANT_STATUS
CONSULTANT RECRUITER nullable one-to-many
CONSULTANT has zero or one
RECRUITER and RECRUITER
has many CONSULTANTs
BILLABLE PROJECT non-nullable one-to-many
BILLABLE has one PROJECT
and PROJECT has many
BILLABLEs
Now that the database is created, you can create the web application and use the Entity Classes from
Database wizard to generate entity classes based on the database tables.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 62/87
Creating the Web Application Project
In this exercise you create a web project and add the JavaServer Faces framework to the project. When
you create the project, you will select JavaServer Faces in the Frameworks panel of the New Project
wizard.
1. Choose File > New Project (Ctrl-Shift-N).
2. Select Web Application from the Java Web category. Click Next.
3. Type ConsultingAgency for the project name and set the project location.
4. Deselect the Use Dedicated Folder option, if selected.
For this tutorial there is little reason to copy project libraries to a dedicated folder because you
will not need to share libraries with other users.
Click Next.
5. Set the server to GlassFish and set the Java EE Version to Java EE 5. Click Next.
6. Select the JavaServer Faces checkbox in the Frameworks panel. Click Finish.
Note. When selecting the framework, be sure to select the JavaServer Faces framework, NOT
Visual Web JavaServer Faces.
When you click Finish, the IDE creates the web application project and opens welcomePF.jsp in
the editor. You can close welcomePF.jsp because you will not need to edit this file.
Generating the Entity Classes from the Database
After you create the database and the database connection is registered with the IDE, you can use the
Entity Classes from Database wizard to quickly generate entity classes based on the tables in the
database. The IDE can generate entity classes for each table that you select, and can also generate any
necessary entity classes for related tables.
1. In the Projects window, right-click the ConsultingAgency node, and choose New > EntityClasses from Database.
2. Select New Data Source from the Data Source drop-down list to open the Create Data Source
dialog.
3. Type jdbc/consult as the JNDI Name and select
jdbc(derb$(//localhost(JMR/conslt Tconslt on !N2H#U as the
Database Connection. Click OK to close the dialog box and return to the wizard.
The tables in the conslt database appear in the Available Tables listbox.
4. Click Add All in the wizard. Click Next. 5. Type jpa.entities as the Package. Make sure that the checkbox to generate named queries is
selected.
6. Click Create Persistence Unit to open the Create Persistence Unit dialog box. Click Create in the
dialog box to create the persistence unit and return to the wizard.
Note. You can keep the default values for the persistence unit.
7. Click Next.
8. Keep the default values in the Mapping Options page of the wizard. Click Finish.
You can use the Mapping Options page of the wizard if you want to further customize the
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 63/87
annotations or collection type in the generated entities. For this tutorial the default values are
sufficient.
When using the wizard to create entity classes from a database, the IDE examines the relationships
between the tables. In the Projects window, if you expand the jpa.entities Source Package node
you can see that the IDE generated an entity class for each table except for the
PROJECT_CONSULTANT table. The IDE did not create an entity class for
PROJECT_CONSULTANT because the table is a join table.
The IDE also generated two additional classes for the tables with composite primary keys: CLIENT and
PROJECT. The primary key classes for these tables (!lient4.ja'a and 4roject4.ja'a)
have PK appended to the name.
If you look at the generated code for the entity classes you can see that the wizard added
@XeneratedQale annotations to the auto-generated ID fields and @Basic+optional 156alse5 annotations to some of the fields in the entity classes. Based on the @Basic+optional1 56alse5 annotations, the JSF Pages from Entity Classes wizard can generate code that includes
checks to prevent non-nullable column violations for those fields.
Editing the Entity Classes
If desired, you can now edit the generated entity classes. In this exercise you will modify the
implementations of the totring method in the entity classes. In the Client and Recruiter classes you
will also modify the annotations to change the relationship between clients and recruiters from one-to-
many to one-to-one. Because a nullable one-to-many relationship already exists between recruiters and
consultants, for demonstration purposes in this tutorial you will establish a nullable one-to-one
relationship between clients and recruiters.
Note. This section of the tutorial is optional and you do not need to make any changes to the entity
classes before you generate the JSF pages with the JSF Pages from Entity Classes wizard.
Editing Address."ava
Open the Address entity class and make the following changes.
1. Modify the return statement of the totring method to return the full address:
retrn line 7 5& 5 7 lineM 7 5& 5 7 cit$ 7 5& 5 7 region 7 5& 5 7 contr$ 75& 5 7 postal!ode3
You can use the IDE's code completion to help you add the fields.
2. Fix your imports, if necessary, and save your changes.
Editing 8illa!le."ava
Open the Billable entity class and make the following changes.
1. Modify the return statement of the totring method to return the description, consultant id
and project:
pblic tring totring+ 0
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 64/87
retrn description ? ' ' ? consultantId ? ' ' ? pro"ect3
2. Fix your imports, if necessary, and save your changes.
Editing Client."ava
1. Modify the @ne#o"an$ annotation on the recriter!ollection field to make therelationship one-to-one and change the field from a Collection to )ecriter recriter.
@neTone+mappedB$ 1 5client5pri'ate %ecruiter recruiter3
2. Modify the getters and setters for !ollection>)ecriter recriter!ollectionaccording to the changes in the name of the field. The new getter and setter will look like the
following:
pblic )ecriter get)ecriter+ 0 retrn recriter39
pblic 'oid set)ecriter+)ecriter recriter 0 this.recriter 1 recriter39
It might be simpler to delete the getter and setter for !ollection>)ecriterrecriter!ollection and then generate a new getter and setter for )ecriterrecriter using the Insert Code dialog. To create a new getter and setter, right-click in the
source code and choose Insert Code (Alt-Insert) and then select Getter and Setter. Select
recriter in the Generate Getter and Setter dialog box and click Generate.
3. Modify the return statement of the totring method to return
tring.'ale6+client4.
pblic tring totring+ 0 retrn *tring.valuef9clientPB:39
4. Fix your imports, if necessary, and save your changes.
Editing ClientPB."ava
1. Modify the return statement of the totring method to return the client name and department
number.
pblic tring totring+ 0 retrn clientame ? ' ' ? 'Dept. ' ? clientDepartmentum!er;9
2. Fix your imports, if necessary, and save your changes.
Editing Consultant."ava
1. Modify the return statement of the totring method to return the email.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 65/87
pblic tring totring+ 0 retrn email;9
2. Fix your imports, if necessary, and save your changes.
Editing Consultant*tatus."ava1. Modify the return statement of the totring method to return the status ID and description.
pblic tring totring+ 0 retrn statusId ? ' ' ? description;9
2. Fix your imports, if necessary, and save your changes.
Editing Pro"ect
1. Modify the return statement of the totring method to return the following:
pblic tring totring+ 0 retrn 9pro"ectPB && null '9unnamed pro"ect:' #pro"ectPB.getPro"ectame9:: ? ' ' ? client39
2. Fix your imports, if necessary, and save your changes.
Editing %ecruiter."ava
1. Modify the @"an$#one annotation on the client field to mark the relationship as one-to-
one.
@neTonepri'ate !lient client3
2. Modify the return statement of the totring method to return the email.
pblic tring totring+ 0 retrn email39
3. Fix your imports, if necessary, and save your changes.
Generating JSF Pages From Entity ClassesNow that the entity classes are created, you can create the web interface for displaying and modifying
the data. You will use the JSF Pages from Entity Classes wizard to generate JavaServer Faces pages.
The code generated by the wizard includes checks based on the annotations in the entity classes. The
wizard also gives you the option to enable Ajax functionality in the application by extending the
JavaServer Faces technology with Dynamic Faces technology.
For each entity class the wizard generates the following:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 66/87
• a JPA controller class
• a JSF controller class
• a JSF converter class
• a directory containing four JSP files (=etail.jsp, Edit.jsp, Hist.jsp, New.jsp)
• managed bean elements, converter elements and navigation rules for the entity in 6aces-con6ig.xml
The wizard also generates the following classes used by the controller classes:
• exception classes used by the JPA controllers
• utility classes used by the JSF controllers
To generate the JSF pages:
1. Right-click the project node in the Projects window and choose New > JSF Pages from Entity
Classes to open the New JSF Pages from Entity Classes wizard.
The Available Entity Classes box lists the seven entity classes in the project. The box does not
list the embeddable classes (!lient4.ja'a and 4roject4.ja'a).
2. Click Add All to move all the classes to the Selected Entity Classes box. Click Next. 3. Type jpa.controllers for the JPA Controller Package.
4. Type jsf for the JSF Classes Package.
5. Select Ajax-enable generated pages.
6. Click Finish.
When you click Finish, the IDE creates the JPA controller classes in the jpa.controllers package
and the JSF converter and JSF controller classes in the js6 package. Each JPA controller class handles
the operations for the corresponding entity class, including creating, editing, and destroying instances
of the entity class via the Java Persistence API. Each JSF converter class implements the
ja'ax.6aces.con'ert.!on'erter interface defined by JavaServer Faces and performs the
work of converting instances of the corresponding entity class to tring objects and vice versa. EachJSF controller class is specific to the corresponding generated JSP and includes code that invokes
methods in the appropriate JPA controller class and demonstrates which exceptions to catch.
Note. In general, when modifying your application you will want to modify the controller logic in the
JSF controller classes and use the generated code as an example.
If you expand the Web Pages node, you can see that the IDE generated a folder for each of the entity
classes. Each folder contains the files =etail.jsp, Edit.jsp, Hist.jsp and New.jsp. The
IDE also modified welcomePF.jsp by inserting links to each of the Hist.jsp pages.
If you expand the Source Packages node you can see the controller, converter, exception, and utility
classes that the wizard generated.
If you expand the Configuration Files node and open 6aces-con6ig.xml in the XML editor, you
can see that the IDE inserted the managed-bean and converter elements for each of the controller and
converter classes. The IDE also inserted a navigation-rule element for each JSP, indicating the logical
outcome that causes the application to navigate to that JSP.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 67/87
Enabling Ajax in the Application
The final pane of the JSF Pages from Entity Classes wizard gives you the option to select Ajax-enable
generated pages to enable Ajax functionality in the application through the Dynamic Faces extension
to the JSF framework. The wizard adds the required JSF Extensions libraries to the project and
configures the application's deployment descriptor to enable the Ajax lifecycle. For more about
Dynamic Faces JSF Extensions see the JavaServer Faces Technology Extensions site.
If you select the option the wizard performs the following actions.
• Adds JSF Extensions libraries to the project (js6-extensions-common, js6-extensions-d$namic-6aces, commons-logging, and shale-remoting) that are
required for using Dynamic Faces technology in the project. • Modifies web.xml to configure FacesServlet to use the Ajax lifecycle by adding an entry for
the ja'ax.6aces.HIFE!Y!HELI= initialization parameter and setting the value to
com.sn.6aces.li6ec$cle.4<)#I<H . • Generates the JSP fragment file <jaxcripts.jsp6 in the WEB-INF/jsp6 directory.
<jaxcripts.jsp6 renders script tags for JavaScript files contained in the Dynamic Faceslibraries.
The application contains a JavaScript file js6crd.js in the Web Pages directory. The
js6crd.js file checks if Dynamic Faces is enabled by checking if the script tags for the Dynamic
Faces JavaScript files were rendered. If Dynamic Faces is enabled then the form is configured to send
Ajax requests.
After enabling Ajax in the application with Dynamic Faces extensions, you can modify the application
to add further functionality provided by Dynamic Faces extensions.
Note. If you want to disable Ajax in the application later, you can comment out the contents of
<jaxcripts.jsp6 by adding >?-- to the beginning of the file and --? to the end of the file.
Generating JPA Controller Classes From Entity Classes
In the generated web application the JPA controller methods are accessed by methods in the JSF
controller class. When you use the JSF Pages from Entity Classes wizard the IDE automatically
generates JPA controller classes for each of the selected entities. But the use of JPA controller classes is
not restricted to JSF web applications. You can use JPA controller classes in other applications that use
the Java Persistence API (for example, in desktop applications) to work with entity classes and manage
entity persistence.
The JPA Controller Classes from Entity Classes wizard enables you to easily create JPA controller
classes in projects. To create JPA controller classes, open the New File wizard and choose JPAController Classes from Entity Classes in the Persistence category. In the wizard you specify the entity
classes for which you want the JPA controller classes and then specify where you want the IDE to
create the files. The wizard also automatically creates exception classes used by the JPA controller
classes.
If you update your database schema you can run the Entity Classes from Database and JPA Controllers
from Entity Classes wizards again to regenerate the classes. If desired, after you create the JPA
controller classes, you can run the JSF Pages from Entity Classes wizard and specify the package of the
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 68/87
existing JPA controller classes, in which case the existing JPA controller classes will be leveraged rather
than regenerated.
Adding Data to the Database
Now that you have finished creating the application, you can deploy and run the application. The
Consulting Agency database you created is unpopulated. You need to add data to the database either byadding data through the web interface or by running an SQL script. After you add the data you will see
how the relationships between the tables function.
Adding Data With an SQL Script
If you do not want to add the data through the web forms, you can run the
derb$LinsertLdataLconsltL'M.s*l script included in the derb$-conslt.ziparchive.
1. Open derb$LinsertLdataLconsltL'M.s*l by choosing File > Open File from the
main menu.
The file automatically opens in the the SQL editor.
Note. If you are using the MySQL database server, open the
m$s*lLinsertLdataLconsltL'M.s*l file included in the m$s*l-conslt.ziparchive.
2. Make sure that the consult database is selected in the Connection drop-down list in the SQL
editor toolbar and click the Run SQL button in the toolbar.
You can see the result of the script execution in the Output window.
3. Click Run Main Project in the main toolbar.Your default web browser opens to the local address
http(//localhost(AGAG/!onslting<genc$/ .
Adding Data With the Web Interface
You can add data to the database by launching the application in your browser and then adding data
through the web forms.
1. Click Run Main Project in the main toolbar.
The IDE saves all changed files, rebuilds the application, and deploys the application to the
server. Your default web browser opens to the local addresshttp(//localhost(AGAG/!onslting<genc$/ .
2. Click Show All Address Items and click New Address.
3. Add the following data in the New Address form.
Field Value
Line1 100 Data Street
Line2 Suite 432
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 69/87
City San Francisco
Region California
Country USA
PostalCode 94103
4. Click Create.
5. Click Index to return to the index page.6. Click Show All Client Items and click New Client.
7. Add the following data in the New Client form.
Field Value
ClientDepartmentNumber 2000
ClientName Big Data Corp.
ContactEmail [email protected] accounting @ bigdatacorp.com
ContactPassword accounting
BillingAddress 100 Data Street
8. Click Create and then Index to return to the index page.
9. Click Show All Project Items and click New Project.
10.Add the following data in the New Project form.
Field Value
ProjectName Secret Project
ContactEmail [email protected] project.manager @ bigdatacorp.com
ContactPassword project.manager
11.Click Create and then Index to return to the index page.
12.Click Show All ConsultantStatus Items and then click New ConsultantStatus.
13.Add the following data in the New ConsultantStatus form.
Field ValueStatusId A
Description Active
14.Click Create and then Index to return to the index page.
15.Click Show All Consultant Items and then click New Consultant.
16.Add the following data in the New Consultant form.
Field Value
Email [email protected] janet.smart @ jsfcrudconsultants.com
Password janet.smart
HourlyRate 80
BillableHourlyRate 120
ProjectCollection Secret Project
StatusId A, Active
Note. Make sure you select Secret Project in the list box for ProjectCollection.
17.Click Create and then Index to return to the index page.
18.Click Show All Billable Items and then click New Billable.
19.Add the following data in the New Billable form.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 70/87
Field Value
StartDate 2008-10-13 00:00:00.0
EndDate 2008-10-17 00:00:00.0
Hours 40
HourlyRate 80
BillableHourlyRate 120Description begin gathering requirements
ConsultantId [email protected] janet.smart @ jsfcrudconsultants.com
Project Secret Project
20.Click Create and then click New Billable.
21.Add the following data in the New Billable form.
This time you will type finish gathering requirements in the Description field.
Field Value
StartDate 2008-10-20 00:00:00.0
EndDate 2008-10-24 00:00:00.0
Hours 40
HourlyRate 80
BillableHourlyRate 120
Description finish gathering requirements
ConsultantId [email protected] janet.smart @ jsfcrudconsultants.com
Project Secret Project
22.Click Create and return to the index page.
23.Click Show All Recruiter Items and click New Recruiter.
24.Add the following data in the New Recruiter form.
Field Value
Email [email protected] bob @ jsfcrudconsultants.com
Password bob
ConsultantCollection [email protected] janet.smart @
jsfcrudconsultants.com
Note. Make sure you select [email protected] janet.smart @
jsfcrudconsultants.com in the list box for ConsultantCollection. Leave the Client drop down list
empty.
25.Click Create and then Index to return to the index page.
After adding data to the database you can navigate through the generated pages to see the relationships
between the tables.
Exploring Functionality in the Generated Code
After you populate the database you can see examples of how the code generated by the wizard is based
on the properties of the database fields.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 71/87
Read-only Primary Key Fields
If a field in the database is a primary key, the wizard generates code to prevent the user from editing the
field in the generated forms. The following examples illustrate instances where the primary key field is
read-only.
• If you navigate to the New Client page you can see that the ProjectCollection field is read-only.
If the application permitted an attempt to change the Client associated with an existing Project,the operation would fail because the Client associated with a Project is part of the Project's
primary key. You can verify this in the SQL script by examining the project_pk primary key and
the project_fk_client foreign key.
• If you navigate to the Editing Project Page you can see that the Client field is read-only. Again,
the field is read-only because the Client associated with a Project is part of the Project's primary
key.
Generated Error Checks
The generated code can check if a user action would result in an error. For example, if a table has a
column that cannot be null, the code can check if an action would result in a non-null violation for the
column and instead display an error message. After you populate the database you can see examples of
the generated checks by trying to edit the data in the forms. You will receive an error message if you
attempt to do the following actions.
• Create another Project item, again specifying Secret Project as the ProjectName, and completing
the ContactEmail and Client fields.
An error message appears indicating that the item already exists.
• Create another Address item, but leave all the fields blank.
Error messages appear indicating the required fields.
• Edit the "[email protected] janet.smart @ jsfcrudconsultants.com "
Consultant item by deselecting "finish gathering requirements" in the BillableCollection list.
An error message appears indicating that the Billable item that you deselected must be retained
because its consltantId field cannot be null.
• Destroy the "Secret Project, Big Data Corp., Dept. 2000" Project item.
An error message appears indicating that the Project item cannot be destroyed because the
Project item's associated Billable items have a project field that cannot be null.
• Destroy an item that has already been destroyed by another user.
An error message appears indicating that the item no longer exists, and the Hist.jsp page
subsequently does not display the item.
Note. You can do this if you use two different browsers (e.g., Firefox and Internet Explorer) and
navigate to the same page (e.g., the Listing Billable Items page) in each browser. Destroy one of
the Billable items in one of the browsers and then try to destroy the same item in the other
browser.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 72/87
Integrating an Applet in a Web ApplicationAn applet is a program written in the Java programming language that can be included in an HTML
page, much in the same way an image is included in a page. The application that you build in this
tutorial shows you how to build and deploy applets in the IDE.
Note: Though there are no project templates that are specifically designed for creating applets in theIDE, you can easily develop them in a Java project and package them in a web project, as shown in this
tutorial.
Contents
• Creating or Importing an Applet
• Running an Applet
• Embedding an Applet in a Web Application
To follow this tutorial, you need the following software and resources.
Software or Resource
Version Required
NetBeans IDE
Web and Java EE installation
version 6.1 or version 6.0
Java Development Kit (JDK)
Version 6 or
version 5
Creating or Importing an Applet Source File
In this section, you create your first applet. Possibly, you already have an applet and, in this case, you
can use the instructions below to import it into the IDE.
Create the Java project from scratch or from existing sources
1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select Java.
2. Choose one of the following:
• If you are creating a new applet source file, select Java Class Library under Projects.
Click Next.
• If you want to import an applet source file, select Java Project with Existing Sources.
Click Next. Specify the file's location in the Source Packages Folder text box.
3. Under Project Name, type ,ello<pplet. Change the Project Location to any folder on your
computer.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 73/87
4. Click Finish. If you imported an applet source file, run it.
Create the applet source file
1. Right-click the HelloApplet project node in the Projects window and select New > Other (Ctrl-
N).
2. Under Categories, select Java. Under File Types, select Applet.
Alternatively, if you want to visually design your applet, select Swing GUI Forms > JApplet
Form.
Click Next.
3. Under Class Name, type "$<pplet. Under Package, type org.me.hello.
4. Click Finish.
The IDE creates the applet source file in the specified package. The applet source file opens inthe Source editor.
5. Define your applet class by copying and pasting the following code over the existing default
code:
package org.me.hello3
import ja'a.applet.<pplet3 import ja'a.awt.Xraphics3
pblic class "$<pplet extends <pplet 0 pblic 'oid paint+Xraphics g 0
g.drawtring+5,ello applet:5& JG& MJ3 9 9
Alternatively, if you are designing an Applet Form instead, use the Designing a Swing GUI in
NetBeans IDE document to create something like the following:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 74/87
For detailed information on writing applets, see The JavaTM Tutorial's Applets section.
Running an Applet Source File
The applet that you created can be run from the IDE. This section shows you how to do so.
Build and run the applet source file
1. Right-click the HelloApplet project node in the Projects window and choose Build from the
contextual menu.
2. The ,ello<pplet.jar file is created in the dist folder, which you can see if you switch to
the Files window (Ctrl-2).
3. Right-click the applet class node (i.e., right-click "MyApplet.java" not the "HelloApplet"
project) in the Projects window and choose Run File from the contextual menu.
The "$<pplet.html launcher file, with the applet embedded, is created in the bild folder,
which you can see if you switch to the Files window (Ctrl-2):
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 75/87
The applet is launched in the Applet Viewer:
Applet forms are also displayed in the Applet Viewer:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 76/87
Embedding an Applet in a Web Application
Your applet is complete. Now you need to make it available to the user. To do so, you create a web
application, put the applet JAR on its classpath, and then add an applet tag to the web application'sHTML file.
Create the web project
1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web
Application. Click Next.
2. Under Project Name, type ,elloWeb<pplet. Change the Project Location to any folder on
your computer. Click Next, select your server, and click Finish.
Add the applet JAR file to the web project
When you want to include an applet JAR file in a web project, you can do so by adding the Java project
that contains the JAR file, or by adding the JAR file itself. Although the choice is yours, note that when
you add the Java project to the web project, you enable the IDE to build the applet whenever you build
the web application. Therefore, when you modify the applet in the Java project, the IDE builds a new
version of the applet whenever the web project is built. On the other hand, if the applet JAR file is not
in a NetBeans IDE project, the applet source file is not rebuilt when you build the web project.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 77/87
1. In the Projects window, right-click the HelloWebApplet project node and select Properties from
the contextual menu.
2. Choose one of the following:
• If the applet JAR file is in a Java project, click Packaging, and then click Add Project.
Browse to and select the folder that contains the Java project. Note that IDE projects are
marked by the NetBeans IDE project icon.
• If the applet JAR file is not in a IDE project, click Packaging, and then click AddJAR/Folder. Browse to and select the folder that contains the JAR file.
The JAR file containing the applet source file is listed in a table at the bottom of the Project
Properties dialog box.
3. Optionally, you can type a location for the applet in the table's Path in WAR column. By default,
the applet JAR file will be copied to the web application's document root, which is the bild/web folder (the highest level of the web application's file structure). Click OK.
When you build the project, the applet's JAR file is packaged in the project's WAR file in the
dist folder. It is also added to the bild/web folder. For details, see the illustration below.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 78/87
Create and run the JSP file or HTML file
1. Choose one of the following:
• If you want to embed the applet in a JSP file, double-click the default index.jsp file
in the Projects window. This file is created by the IDE when you create a web project. It
opens in the Source Editor.
• If you want to embed the applet in an HTML file, right-click the HelloWebApplet
project node, and choose New > Other from the contextual menu. Under Categories,
select Web. Under File Types, select HTML. Click Next. Give your HTML file a name
and click Finish.
2. Embed the applet in the file by adding the following applet tag anywhere between the file's
>bod$>/bod$ tags:
>applet code15org.me.hello."$<pplet5 archi'e15,ello<pplet.jar5/
• org.me.hello."$<pplet is the full classname to your applet
•
,ello<pplet.jar is the JAR file that contains the applet3. Right-click the JSP node or HTML node in the Projects window and choose Run File from the
contextual menu.
The server deploys the JSP file or HTML file in the IDE's default browser.
You should see something similar to the illustration below:
For applet forms, you should see something similar to the following:
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 79/87
Securing a Web Application in NetBeans IDE
6.5Contributed by Dan Kolar, Maintained by James Branam
This document takes you through the basics of adding security to a web application that is deployed to
either the Tomcat server or the Sun Java System Application Server.
This document shows you how to configure security authentication using a basic login window and also
using a login form in a web page. This document takes you through the steps for creating users on the
Tomcat server and Sun Java System Application Server (GlassFish). After creating the users, you then
create the security roles by setting the security properties in the deployment descriptor. This document
also shows how you can use JDBC authentication to secure your application when deploying to the Sun
Java System Application Server (GlassFish).
Expected duration: 40 minutes
Contents
• Installing and Configuring the Working Environment
• Creating the Web Application
• Creating the Secure Directories
• Creating the JSP Index Page
• Creating a Login Form (optional)
• Creating Users and Roles on the Target Server
• Defining Roles on Tomcat Web Server
• Defining Roles on Sun Java System Application Server
• Configuring the Login Method
• Basic Login
• Form Login
• Configuring Security Deployment Descriptors
• Deploying and Running the Application
To follow this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE 6.5 Java version
Java Developer Kit (JDK) Version 6 or version 5
Java EE Platform Java EE 5 or J2EE 1.4
Travel Database Not Required
Application Server Tomcat or GlassFish V2
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 80/87
Notations Used in the Tutorial
<NETBEANS_HOME> - NetBeans IDE installation directory
<APPSERVER_HOME> - Sun Java System Application Server or GlassFish installation directory
<TOMCAT_HOME> - Tomcat installation directory<PROJECT_HOME> - directory containing your project
Installing and Configuring the Working Environment
Install and start NetBeans IDE 6.5. You can do this tutorial using the bundled Tomcat server or
GlassFish V2.
If you are using the Sun Java System Application Server (GlassFish), make sure the server is installedand a server instance is registered with the IDE. You can use the Server Manager to register the server
instance. (Choose Tools > Servers > Add Server. Select "GlassFish V2" and click Next. Click Browse
and locate the installation directory of the application server. Click Finish.)
Creating the Web Application
In this excercise you first create the web application project and the directory structure. You then create
some simple html files in each of the secure directories. The web application uses a basic login
authentication for accessing the secure directories. If you want to use a login form for authentication,
you can add a jsp page with the form.
Creating the Secure Directories
1. Choose File > New Project (Ctrl-Shift-N), select Java Web Application from the Web category,
and click Next.
2. Name the project Web<pplicationecrit$. Accept the default settings.
3. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the
location for the libraries folder. See Sharing Project Libraries for more information on this
option.
4. Click Next.
5. Select the server to which you want to deploy your application. Only servers that are registeredwith the IDE are listed. Click Next.
6. You do not need to add a framework, so click Finish.
7. In the Projects window of the IDE, right-click Web Pages and choose New > Other.
8. In the New File wizard, select Other as Category and Folder as File Type. Click Next.
9. In the New Folder wizard, name the folder secureAdmin and click Finish.
The secureAdmin folder appears in the Projects window in the Web Pages folder.
10.Repeat steps 5, 6, and 7 to create another folder named secureUser.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 81/87
11.Create a new html file in the secureUser folder by right-clicking the folder secureUser in the
Projects window and choosing New > HTML.
12.Name the new file pageU and click Finish.
When you click Finish, the file page2.html opens in the Source Editor.
13.In the Source Editor, replace the existing code in page2.html with the following code.
>html >head >title2ser secre area>/title >/head >bod$ >h2ser ecre <rea>/h >/bod$ >/html
14.Right-click the secureAdmin folder and create a new html file named pageA.
15.In the Source Editor, replace the existing code in page<.html with the following code.
>html
>head >title<dmin secre area>/title >/head >bod$ >h<dmin secre area>/h >/bod$ >/html
Creating the JSP Index Page
You now create the JSP index page containing links to the secure areas. When the user clicks on the
link they are prompted for the username and password. If you use a basic login, they are prompted bythe default browser login window. If you use a login form page, the user enters the username and
password in a form.
1. Open index.jsp in the Source Editor and add the following links to page<.html and
page2.html:
>p)e*est a secre <dmin page >a hre615secre<dmin/page<.html5here:>/a>/p>p)e*est a secre 2ser page >a hre615secre2ser/page2.html5 here:>/a>/p
2. Save your changes.
Creating a Login Form (optional)
If you want to use a login form instead of the basic login, you can create a jsp page containing the
form. You then specify the login and error pages when configuring the login method.
1. In the Projects window, right-click the folder Web Pages and choose New > JSP.
2. Name the file login, leave the other fields at their default value and click Finish.
3. In the Source Editor, add the following code to the top of login.jsp.
>?@taglib ri15http(//ja'a.sn.com/jstl/core5 pre6ix15c5 ?
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 82/87
4. In the Source Editor, insert the following code between the >bod$ tags of login.jsp.
>6orm action15jLsecrit$Lcheck5 method154#5 2sername(>inpt t$pe15text5 name15jLsername5>br 4assword(>inpt t$pe15password5 name15jLpassword5 >inpt t$pe15sbmit5 'ale15Hogin5 >/6orm
5. Create a new html file named loginError.html in the Web Pages folder. This is a simple
error page.
6. In the Source Editor, replace the existing code in loginError.html with the following
code.
>html >head >titleHogin #est( Error logging in>/title >/head >bod$ >hError Hogging In>/h >br/
>/bod$ >/html
Creating Users and Roles on the Target Server
To be able to use user/password authentication (basic login or form-based login) security in web
applications, the users and their appropriate roles have to be defined for the target server. To log in to a
server, the user account has to exist on that server.
How you define the users and roles varies according to the target server you specified. In this tutorial
the users admin and tomcat are used to test the security setup. You need to confirm that these users
exist on the respective servers, and that the appropriate roles are assigned to the users.
Defining Roles on the Sun Java System Application Server (GlassFish)
The Sun Java System Application Server (GlassFish) has one pre-defined user named admin, which is
used for accessing the Admin Console. For this scenario you first need to use the Admin Console of the
Sun Java System Application Server to create two new users named ser and admin. The user named
ser will have limited access to the application, admin will have administration privileges. You then
need to map these users to roles by modifying sn-web.xml. sn-web.xml is located in the
Configuration Files directory of your project.
1. Open the Admin Console by right-clicking Servers > GlassFish V2 in the Services window ofthe IDE. The login page for the Sun Java System Application Server opens in your browser
window. You need to log in using the admin username and password to access the Admin
Console.
Note: The Application Server must be running before you can access the Admin Console. To
start the server, right-click the GlassFish V2 node and choose Start.
2. In the Admin Console, navigate to Configuration > Security > Realms.
3. Select the 6ile realm, and in the Edit Realm screen click Manage Users.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 83/87
4. Click New to add a new user. Type ser as the user ID and ser as the password. Click OK.
5. Follow the previous steps to create a user named admin in the 6ile realm.
Defining Roles on the Tomcat Web Server
The Tomcat server bundled with the IDE already has some pre-defined users and roles.
The basic users and roles for the Tomcat server are defined in tomcat-sers.xml. You can findtomcat-sers.xml in your <USER_DIR>Vapache-tomcat-J.J.RLbaseVcon6directory. Your tomcat-sers.xml file should like similar to this:
>tomcat-sers >role rolename15tomcat5/ >role rolename15role5/ >role rolename15manager5/ >role rolename15admin5/ >ser sername15ide5 password15(generated passwrd!5 roles15manager&admin5/ >ser sername15tomcat5 password15tomcat5 roles15tomcat5/ >ser sername15role5 password15tomcat5 roles15role5/ >ser sername15both5 password15tomcat5 roles15tomcat&role5/
>/tomcat-sers
Note: The password for the user ide is generated when Tomcat is installed. You can change the
password for the user ide, or copy the password in tomcat-sers.xml.
Configuring the Login Method
When configuring the login method for your application, you can use the login window provided by
your browser for basic login authentication. Alternatively, you can create a web page with a login form.
Both types of login configuration are based on user/password authentication.
You configure the login method for the application by configuring web.xml. The web.xml file can
be found in the Configuration Files directory of the Projects window.
Basic Login
When you use the basic login configuration, the login window is provided by the browser. A valid
username and password is needed to access the secure content.
The following steps show how to configure a basic login for the Sun Java System Application Server.
1. In the Projects window, double-click web.xml located in the Configuration Files directory to
open the file in the Visual Editor.
2. Click Security in the toolbar to open the file in Security view.
3. Expand the Login Configuration node and set the Login Configuration to Basic.
Note: If you want to use a form , select Form sintead of basic and specify the login and login
error pages.
4. Enter 6ile as the Realm Name. This corresponds to the realm name where you created the
users on the Sun Java System Application Server.
5. Expand the Security Roles node and click Add to add a role name.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 84/87
6. Add the following Security Roles:
• <dmin. Users added to this role will have access to the secre<dmin directory of the
server.
• 2ser. Users added to this role will have access to the secre2ser directory of the
server.
7. Create and configure a security constraint named <dmin!onstraint by doing the following:
• Click Add Security Constraint to create a new security constraint.• Enter <dmin!onstraint for the Display Name of the new security constraint.
• Click Add to add a Web Resource Collection.
• In the Add Web Resource dialog box, set the Resource Name to <dmin and the URL
Pattern to /secre<dmin/% and click OK.
Note: When you use an asterisk (*), you are giving the user access to all files in that
folder.
• Select Enable Authentication Constraint and click Edit to edit the Role Name field.
• In the Edit Role Names dialog box, select Admin and User in the left pane, click Add
and then click OK.
After completing the above steps, the result should resemble the following figure:
8. Create and configure a security constraint named 2ser!onstraint by doing the following:
• Click Add Security Constraint to create a new security constraint.
• Enter 2ser!onstraint for the Display Name of the new security constraint.
• Click Add to add a Web Resource Collection.
• In the Add Web Resource dialog box, set the Resource Name to 2ser and the URL
Pattern to /secre2ser/% and click OK.
• Select Enable Authentication Constraint and click Edit to edit the Role Name field.
Note: You can also set the timeout for the session in web.xml. To set the timeout, click the
General tab of the Visual Editor and specify how long you want the session to last. The defaultis 30 minutes.
Form Login
Using a form for login enables you to customize the content of the login and error pages. The
steps for configuring authentication using a form are the same as for the basic login
configuration, except that you specify the login and error pages you created.
The following steps show how to configure a login form for the Sun Java System Application
Server.
• In the Projects window, double-click web.xml located in the Web 4ages/WEB-INFdirectory to open the file in the Visual Editor.
• Click Security in the toolbar to open the file in Security view and expand the Login
Configuration node.
• Set the Login Configuration to Form.
• Set the Form Login Page by clicking Browse and locating login.jsp.
• Set the Form Error Page by clicking Browse and locating loginError.html.
• Click Add Role and add the following Security Roles.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 85/87
• <dmin, for administrators
• 2ser for users
• Click Add Security Constraint, name it <dmin!onstraint, and do the following:
• Add a Web Resource Collection and set the name to <dmin and the path to
/secre<dmin/%
• Select Enable Authentication Constraint and click Edit.
• In the Edit Role Names dialog box, select Admin in the left pane and click Add.• Click Add Security Constraint, name it 2ser!onstraint, and do the following:
• Add a Web Resource Collection and set the name to 2ser and the path to
/secre2ser/%
• Select Enable Authentication Constraint and click Edit.
• In the Edit Role Names dialog box, select Admin and Tomcat in the left pane and
click Add.
Note: You can also set the timeout for the session in web.xml. To set the timeout, click the
General tab of the Visual Editor and specify how long you want the session to last. The default
is 30 minutes.
Configuring Security Deployment Descriptors
If you are deploying your application to the Sun Java System Application Server (GlassFish), you need
to configure the security deployment descriptors in sn-web.xml to map the security roles defined
in web.xml. Note that the values you entered in web.xml are displayed in sn-web.xml. sn-web.xml pulls these values from web.xml for you.
1. Double-click sn-web.xml located in the Configuration Files directory in the Projects
window.
2. Select the Security tab to reveal the security roles.
3. Select the Admin security role node to open the Security Role Mapping pane.4. Click Add Principal and enter admin for the principal name. Click OK.
5. Select the User security role node to open the Security Role Mapping pane.
6. Click Add Principal and enter ser for the principal name. Click OK
7. Save your changes to sn-web.xml.
You can also view and edit sn-web.xml in the XML editor by clicking Edit As XML in the top
right corner of the Sun Web Application visual editor. If you open sn-web.xml in the XML editor,
you can see that sn-web.xml has the following security role mapping information:
>secrit$-role-mapping >role-name<dmin>/role-name
>principal-nameadmin>/principal-name>/secrit$-role-mapping>secrit$-role-mapping >role-name2ser>/role-name >principal-nameser>/principal-name>/secrit$-role-mapping
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 86/87
Deploying and Running the Application
In the Projects window, right-click the project node and choose Run.
Note: By default, the project has been created with the Compile on Save feature enabled, so you do not
need to compile your code first in order to run the application in the IDE. For more information on the
Compile on Save feature, see the Compile on Save section of the Creating, Importing, and Configuring
Java Projects guide.
After building and deploying the application to the server, the start page opens in your web browser.
Choose the secure area which you want to access by clicking either admin or user.
After supplying the user and password, there are three possible results:
• Password for this user is correct and user has privileges for secured content -> secure content
page is displayed
• Password for this user is incorrect -> Error page is displayed
•
Password for this user is correct, but user does not have right to access the secured content ->browser displays Error 403 Access to the requested resource has been denied
Summary
In this tutorial, you created a secure web application. You edited security settings using the web.xml
and sun-web.xml Descriptor editors, creating web pages with secure logins and multiple identities.
7/23/2019 Developing Java Web Applications.pdf
http://slidepdf.com/reader/full/developing-java-web-applicationspdf 87/87