blob: 1fac921350b866210a94cad9d4e1777c8809170b [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="author" content="troy.giunipero@sun.com">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="description" content="This tutorial unit demonstrates how to create project files in the IDE, and introduces you to some of the facilities available for HTML and CSS development.">
<meta name="keywords" content="NetBeans, IDE, integrated development environment,
Java, Java EE, open source, web technology, e-commerce">
<link rel="stylesheet" type="text/css" href="../../../../netbeans.css">
<link rel="stylesheet" type="text/css" href="../../../../print.css" media="print">
<link rel="stylesheet" type="text/css" href="../../../../lytebox.css" media="screen">
<script type="text/javascript" src="../../../../images_www/js/lytebox-compressed.js"></script>
<title>The NetBeans E-commerce Tutorial - Preparing the Page Views and Controller Servlet</title>
</head>
<body>
<!-- Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. -->
<h1>The NetBeans E-commerce Tutorial - Preparing the Page Views and Controller Servlet</h1>
<div style="margin-left:-3px">
<div class="feedback-box margin-around float-left" style="margin-right:15px">
<h4>Tutorial Contents</h4>
<ol>
<li><a href="intro.html">Introduction</a></li>
<li><a href="design.html">Designing the Application</a></li>
<li><a href="setup-dev-environ.html">Setting up the Development Environment</a></li>
<li><a href="data-model.html">Designing the Data Model</a></li>
<li><strong>Preparing the Page Views and Controller Servlet</strong>
<ul style="margin: 5px 0 0 -2em">
<li><a href="#createProjectFiles">Creating Project Files</a></li>
<li><a href="#implementHTML">Implementing HTML and CSS content</a></li>
<li><a href="#view">Placing JSP Pages in WEB-INF</a></li>
<li><a href="#jspf">Creating a Header and Footer</a></li>
<li><a href="#dd">Adding a Directive to the Deployment Descriptor</a></li>
<li><a href="#controller">Creating the Controller Servlet</a></li>
<li><a href="#implement">Implementing the Controller Servlet</a></li>
<li><a href="#seeAlso">See Also</a></li>
</ul></li>
<li><a href="connect-db.html">Connecting the Application to the Database</a></li>
<li><a href="entity-session.html">Adding Entity Classes and Session Beans</a></li>
<li><a href="manage-sessions.html">Managing Sessions</a></li>
<li><a href="transaction.html">Integrating Transactional Business Logic</a></li>
<li><a href="language.html">Adding Language Support</a></li>
<li><a href="security.html">Securing the Application</a></li>
<li><a href="test-profile.html">Testing and Profiling</a></li>
<li><a href="conclusion.html">Conclusion</a></li>
</ol>
</div>
</div>
<p><img src="../../../../images_www/articles/68/netbeans-stamp-68-69.png" class="stamp"
alt="Content on this page applies to NetBeans IDE, versions 6.8 and 6.9"
title="Content on this page applies to NetBeans IDE, versions 6.8 and 6.9"></p>
<p>This tutorial unit demonstrates how to create project files in the IDE, and
introduces you to some of the facilities available for HTML and CSS development.
After creating necessary project files, you begin organizing the front-end of
the application. That is, you'll place JSP files in their proper locations
within the project structure, create a header and footer which will be applied
to all views, and set up the controller servlet to handle incoming requests.</p>
<p>In this unit, you also create a web deployment descriptor (<code>web.xml</code> file)
for the application. You can use the deployment descriptor to specify configuration
information which is read by the server during deployment. Although the
<a href="http://jcp.org/en/jsr/detail?id=315" target="_blank">Servlet 3.0 Specification</a>,
included in Java EE 6, enables you to use class annotations in place of XML, you may
still require the deployment descriptor to configure certain elements of your application.
Specifically, in this unit you add directives for the header and footer and specify
which files they will be applied to.</p>
<p>One of the goals of this tutorial unit is to create JSP pages that correspond to the
views specified in the application design. Referring back to the <a href="design.html#mockups">page
mockups</a> and <a href="design.html#business">process flow diagram</a>, you begin
implementing page layouts according to the mockups by creating <em>placeholders</em>
for all visual and functional components. This unit provides a guide for implementing
the layout of the welcome page. You can apply the outlined steps to create the other
pages on your own, or <a href="https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252Fecommerce%252FAffableBean_snapshot1.zip">download
project snapshot 1</a>, which provides completed layouts for all pages.</p>
<p>You can view a live demo of the application that you build in this tutorial:
<a href="http://services.netbeans.org/AffableBean/" target="_blank">NetBeans E-commerce
Tutorial Demo Application</a>.</p>
<br style="clear:left">
<br>
<table>
<tbody>
<tr>
<th class="tblheader" scope="col">Software or Resource</th>
<th class="tblheader" scope="col">Version Required</th>
</tr>
<tr>
<td class="tbltd1"><a href="https://netbeans.org/downloads/index.html" target="_blank">NetBeans IDE</a></td>
<td class="tbltd1">Java bundle, 6.8 or 6.9</td>
</tr>
<tr>
<td class="tbltd1"><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">Java Development Kit (JDK)</a></td>
<td class="tbltd1">version 6</td>
</tr>
<tr>
<td class="tbltd1"><a href="#glassFish">GlassFish server</a></td>
<td class="tbltd1">v3 or Open Source Edition 3.0.1</td>
</tr>
</tbody>
</table>
<p><strong class="notes">Notes:</strong></p>
<ul>
<li>The NetBeans IDE requires the Java Development Kit (JDK) to run properly.
If you do not have any of the resources listed above, the JDK should be
the first item that you download and install.</li>
<li>The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are
required for the application you build in this tutorial.</li>
<li id="glassFish">The NetBeans IDE Java Bundle also includes the GlassFish server,
which you require for this tutorial. You could
<a href="http://glassfish.dev.java.net/public/downloadsindex.html" target="_blank">download
the GlassFish server independently</a>, but the version provided with the
NetBeans download has the added benefit of being automatically registered with
the IDE.</li>
</ul>
<br>
<h2 id="createProjectFiles">Creating Project Files</h2>
<p>To create new files for your project, access the IDE's File wizard. You can click
the New File (
<img src="../../../../images_www/articles/73/javaee/ecommerce/common/new-file-btn.png"
alt="New File button"> ) button, press Ctrl-N (&#8984;-N on Mac), or in the
Projects window, right-click the folder node that will contain the new file,
and choose New &gt; [file-type]. In the following sub-sections, create JSP
pages and a stylesheet for the project.</p>
<ul>
<li><a href="#jsp">Creating JSP Pages</a></li>
<li><a href="#css">Creating a Stylesheet</a></li>
</ul>
<div class="indent">
<h3 id="jsp">Creating JSP Pages</h3>
<p>Begin working in the project by creating JSP pages that correspond to the views
displayed in the <a href="design.html#business">process flow diagram</a>.</p>
<p>The <code>index.jsp</code> page that was generated by the IDE will become the
project's welcome page. Create JSP pages for the four remaining views and, for
now, place them in the project's webroot with <code>index.jsp</code>.</p>
<ol>
<li>Click the New File (
<img src="../../../../images_www/articles/73/javaee/ecommerce/common/new-file-btn.png"
alt="New File button"> ) button to open the File wizard.</li>
<li>Select the Web category, then select JSP and click Next.</li>
<li>Name the file '<code>category</code>'. Note that the Location field
is set to <code>Web Pages</code>, indicating that the file will be created
in the project's webroot. This corresponds to the project's <code>web</code>
folder, which you can later verify in the IDE's Files window.</li>
<li>Click Finish. The IDE generates the new JSP page and opens it in the editor.</li>
<li>Repeat steps 1 - 4 above to create the remaining <code>cart.jsp</code>,
<code>checkout.jsp</code>, <code>confirmation.jsp</code> pages.
<br><br>
When you finish, your Projects window will look as follows:
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/projects-win-views.png"
class="margin-around b-all" alt="Projects window displaying 'view' folder and JSP pages"
title="Views are contained in the 'WEB-INF/view/' folder">
</li>
</ol>
<h3 id="css">Creating a Stylesheet</h3>
<p>Create a CSS file to contain all styles specific to the application.</p>
<ol>
<li>In the Projects window, right-click the Web Pages node and choose New &gt; Folder.</li>
<li>In the New Folder wizard, name the folder '<code>css</code>' and click Finish.</li>
<li>Right-click the new <code>css</code> folder and choose New &gt; Cascading
Style Sheet. (If the Cascading Style Sheet item is not listed, choose Other.
In the File wizard, select the Web category, then select Cascading Style Sheet
and choose Next.)</li>
<li>Name the stylesheet <code>affablebean</code>, then click Finish.
<br><br>
When you finish, you'll see the <code>affablebean.css</code> file displayed
in your Projects window.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/projects-win-css.png"
class="margin-around b-all" alt="Projects window displaying 'affablebean.css' stylesheet"
title="Projects window displays new 'css' folder and stylesheet"></li>
</ol>
</div>
<br>
<h2 id="implementHTML">Implementing HTML and CSS content</h2>
<p>The purpose of this section is to design the page views so that they begin to
mirror the provided <a href="design.html#mockups">page mockups</a>. As such,
they'll serve as a scaffolding which you can use to insert dynamic content during
later stages of project development. To do so, you'll utilize the IDE's HTML
and CSS editors, along with several CSS support windows.</p>
<p class="notes"><strong>Browser compatibility note:</strong> This tutorial uses
Firefox 3 and <em>does not</em> guarantee that page view markup is compatible
with other modern browsers. Naturally, when working with front-end web technologies
(HTML, CSS, JavaScript) you would need take measures to ensure that your web
pages render properly in the browsers and browser versions that you expect visitors
to your site will be using (typically Internet Explorer, Firefox, Safari, Chrome,
and Opera). When working in the IDE, you can set the browser you want your application
to open in. Choose Tools &gt; Options (NetBeans &gt; Preferences on Mac), and under
the General tab in the Options window, select the browser you want to use from
the Web Browser drop-down. The IDE detects browsers installed to their default
locations. If a browser installed on your computer is not displayed, click the
Edit button and register the browser manually.</p>
<p>Preparing the display of your web pages is usually an iterative process which
you would fine-tune with regular feedback from the customer. The following steps
are designed to introduce you to the facilities provided by the IDE, and
demonstrate how to get started using the <a href="design.html#index">welcome
page mockup</a> as an example.</p>
<ol>
<li>In the Projects window, double-click <code>index.jsp</code> to open it in the
editor.</li>
<li>Begin by creating <code>&lt;div&gt;</code> tags for the main areas of the page.
You can create five tags altogether: four for main areas (header, footer,
left column, and right column), and the fifth to contain the others. Remove
any content within the <code>&lt;body&gt;</code> tags and replace with the
following. (New code is shown in <strong>bold</strong>.)
<pre class="examplecode">
&lt;body&gt;
<strong>&lt;div id=&quot;main&quot;&gt;
&lt;div id=&quot;header&quot;&gt;
header
&lt;/div&gt;
&lt;div id=&quot;indexLeftColumn&quot;&gt;
left column
&lt;/div&gt;
&lt;div id=&quot;indexRightColumn&quot;&gt;
right column
&lt;/div&gt;
&lt;div id=&quot;footer&quot;&gt;
footer
&lt;/div&gt;
&lt;/div&gt;</strong>
&lt;/body&gt;</pre></li>
<li>Add a reference to the stylesheet in the page's head, and change the title text.
<pre class="examplecode">
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
<strong>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/affablebean.css&quot;&gt;</strong>
&lt;title&gt;<strong>The Affable Bean</strong>&lt;/title&gt;
&lt;/head&gt;</pre></li>
<li>Open the <code>affablebean.css</code> stylesheet in the editor. Begin creating
style rules for the <code>&lt;div&gt;</code> IDs you just created.
<ul style="margin: 5px 0 0 -.7em">
<li>Use the <code>width</code> and <code>height</code> properties to create
space for each area.</li>
<li>Use the <code>background</code> property to discern the areas when you
view the page.</li>
<li>In order to horizontally center the four areas in the page, you can include
<code>margin: 20px auto</code> to the <code>body</code> rule. (<code>20px</code>
applies to the top and bottom; <code>auto</code> creates equal spacing to
the left and right.) Then include <code>float: left</code> to the left and
right columns.</li>
<li>The footer requires <code>clear: left</code> so that its top border displays
after the bottom borders of any left-floating areas above it (i.e., the left
and right columns).</li>
</ul>
<pre class="examplecode">
body {
font-family: Arial, Helvetica, sans-serif;
width: 850px;
text-align: center;
margin: 20px auto;
}
#main { background: #eee }
#header {
height: 250px;
background: #aaa;
}
#footer {
height: 60px;
clear: left;
background: #aaa;
}
#indexLeftColumn {
height: 400px;
width: 350px;
float: left;
background: #ccc;
}
#indexRightColumn {
height: 400px;
width: 500px;
float: left;
background: #eee;
}</pre></li>
<li>Click the Run Project (
<img src="../../../../images_www/articles/73/javaee/ecommerce/common/run-project-btn.png"
alt="Run Project button"> ) button in the IDE's main toolbar. Project files that contain
changes are automatically saved, any Java code in the project compiles, the project is
packaged and deployed to GlassFish, and your browser opens to display the current state
of the welcome page.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/index-page.png"
class="margin-around b-all" alt="Welcome page displayed in browser" style="width:688px"
title="Run the project to view the current state of pages"></li>
<li>Now, begin creating placeholders for page components within each of the four visible areas.
Start with the header. Reviewing the <a href="design.html#index">welcome page mockup</a>, the
header should contain the following components:
<ul style="margin: 5px 0 0 -.7em">
<li>logo</li>
<li>logo text</li>
<li>shopping cart widget</li>
<li>language toggle</li>
</ul>
Make the following changes to the <code>index.jsp</code> file. (New code shown
in <strong>bold</strong>.)
<pre class="examplecode">
&lt;div id=&quot;header&quot;&gt;
<strong>&lt;div id=&quot;widgetBar&quot;&gt;
&lt;div class=&quot;headerWidget&quot;&gt;
[ language toggle ]
&lt;/div&gt;
&lt;div class=&quot;headerWidget&quot;&gt;
[ shopping cart widget ]
&lt;/div&gt;
&lt;/div&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;img src=&quot;#&quot; id=&quot;logo&quot; alt=&quot;Affable Bean logo&quot;&gt;
&lt;/a&gt;
&lt;img src=&quot;#&quot; id=&quot;logoText&quot; alt=&quot;the affable bean&quot;&gt;</strong>
&lt;/div&gt;</pre>
In the above code, you use a <code>&lt;div id=&quot;widgetBar&quot;&gt;</code>
element to contain the the language toggle and shopping cart widget.
<br><br>
<div class="feedback-box float-left" style="width: 683px;">
<h3>NetBeans HTML Editor Support</h3>
<p>When you work in the editor, take advantage of the IDE's HTML support.
Aside from typical syntax highlighting that lets you differentiate
between tags, attributes, attribute values, and text, there are plenty
of other features.</p>
<p>When typing tags and attributes in the editor, you can invoke code-completion
and documentation support by pressing Ctrl-Space. The IDE presents a list
of suggestions which you can choose from, as well as a documentation window
that defines the selected item and provides code examples.</p>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/documentation-popup.png"
class="margin-around b-all" title="Press Ctrl-Space to view code completion and documentation windows"
alt="Code completion and documentation windows displayed in editor"/>
<p>The IDE detects errors in your code and provides you with warnings, error
messages, and in some cases, suggestions. Warning messages are displayed
in yellow, while errors are shown in red. You can hover your pointer over
a designated area to view the message in a tooltip.</p>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/html-hint.png"
class="margin-around b-all" title="Hover your pointer to view a tooltip warning"
alt="HTML warning displayed in editor"/>
<p>You can also take advantage of numerous keyboard shortcuts. Choose Help &gt;
Keyboard Shortcuts Card from the main menu.</p>
</div>
<br style="clear: both;"/></li>
<li>In the stylesheet, create rules for the new IDs and classes. Add the following rules
beneath the <code>header</code> rule. (New code shown in <strong>bold</strong>.)
<pre class="examplecode">
#header {
height: 250px;
background: #aaa;
}
<strong>#logo {
height: 155px;
width: 155px;
float: left;
margin-left: 30px;
margin-top: -20px;
}
#logoText {
float: left;
margin: 20px 0 0 70px;
/* font styles apply to text within alt tags */
font-family: 'American Typewriter', Courier, monospace;
font-size: 50px;
color: #333;
}
#widgetBar {
height: 50px;
width: 850px;
float: right;
background: #ccc;
}
.headerWidget {
width: 194px;
margin: 20px 2px;
font-size: small;
float: right;
line-height: 25px;
background: #aaa;
}</strong></pre>
For the <code>logo</code> rule, you apply <code>margin-left</code> and
<code>margin-top</code> properties to position the component on the page.
<br><br>
If there are properties in the above code that you are unfamiliar with,
position your cursor on the given property and press Ctrl-Space to invoke
a pop-up window that provides documentation support.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/css-doc-support.png"
class="margin-around b-all" alt="Documentation window for CSS support"
title="Press Ctrl-Space on a CSS property to invoke documentation support">
<br>
<p class="tips">To see how a property is affecting your page, you can comment
it out, then refresh the page in the browser. To comment out code, position
your cursor on a line, or highlight a block of code, then press Ctrl-/
(&#8984;-/ on Mac).</p></li>
<li>Save (Ctrl-S; &#8984;-S on Mac) the <code>index.jsp</code> and <code>affablebean.css</code>
files, then switch to your browser and refresh the page to view its current state.
<br><br>
<p class="notes"><strong>Note:</strong> The IDE's 'Deploy on Save' facility is automatically
activated for Java web projects. This means that every time you save a file, the file is
automatically compiled (i.e., if it is a Java class or JSP page) and the project is newly
packaged and deployed to your server. Therefore, when you make HTML or CSS changes, you
don't need to explicitly rerun the project to view the updated version in a browser. Simply
save your file(s), then switch to the browser and refresh the page.</p>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/index-page2.png"
class="margin-around b-all" alt="Welcome page displayed in browser" style="width:688px"
title="Placeholders for header are visible when running project">
<br>
By following the previous steps, you are probably able to see a pattern emerging.
For each area on the page, you perform three steps.
<ol style="list-style:lower-alpha; margin-top:5px">
<li>Create the structure in HTML.</li>
<li>Create a set of styles to define the appearance.</li>
<li>View the page to examine the results of your changes.</li>
</ol>
Following these three steps, let's implement the components in the remaining areas.</li>
<li>Create placeholders for components in the right column. According to the
<a href="design.html#index">welcome page mockup</a>, the right column contains
four evenly-spaced boxes.
<br><br>
Create the structure for the four boxes. Insert the following code between
the <code>&lt;div id=&quot;indexRightColumn&quot;&gt;</code> tags. (New code shown
in <strong>bold</strong>.)
<pre class="examplecode">
&lt;div id=&quot;indexRightColumn&quot;&gt;
<strong>&lt;div class=&quot;categoryBox&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;span class=&quot;categoryLabelText&quot;&gt;dairy&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;categoryBox&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;span class=&quot;categoryLabelText&quot;&gt;meats&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;categoryBox&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;span class=&quot;categoryLabelText&quot;&gt;bakery&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;categoryBox&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;span class=&quot;categoryLabelText&quot;&gt;fruit & veg&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;</strong>
&lt;/div&gt;</pre></li>
<li>Add style rules to <code>affablebean.css</code> for the new <code>categoryBox</code>
and <code>categoryLabelText</code> classes. (New code shown in <strong>bold</strong>.)
<pre class="examplecode">
#indexRightColumn {
height: 400px;
width: 500px;
float: left;
background: #eee;
}
<strong>.categoryBox {
height: 176px;
width: 212px;
margin: 21px 14px 6px;
float: inherit;
background: #ccc;
}
.categoryLabelText {
line-height: 150%;
font-size: x-large;
}</strong></pre>
<div class="feedback-box float-left" style="width: 683px;">
<h3>NetBeans CSS Support</h3>
<p>When working in stylesheets, there are two windows that can be
particularly helpful. The CSS Preview enables you to view style
rules as they are rendered in a browser. To open the CSS Preview,
choose Window &gt; Other &gt; CSS Preview from the main menu.
When you place your cursor within a style rule in the editor,
the CSS Preview automatically refreshes to display sample text
according to the properties defined in the rule.</p>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/css-preview.png"
class="margin-around b-all" alt="CSS Preview"
title="Use the CSS Preview to view rendered style rules">
<p>The CSS Style Builder is useful if you do not like to code style
rules by hand. To open the CSS Style Builder, choose Window &gt;
Other &gt; CSS Style Builder from the main menu. Using this interface,
you can construct rules by choosing properties and values from a
graphical interface.</p>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/style-builder.png"
class="margin-around b-all" alt="CSS Style Builder"
title="Use the CSS Style Builder to construct style rules">
<p>Like the CSS Preview, the Style Builder is synchronized with the editor.
When you make a selection in the Style Builder, the style rule is
automatically updated in the editor. Likewise, when you type changes
into the editor, the selections in the Style Builder are instantly
updated.</p>
</div>
<br style="clear: both;"/></li>
<li>Save (Ctrl-S; &#8984;-S on Mac) the <code>index.jsp</code> and <code>affablebean.css</code>
files, then switch to your browser and refresh the page to view its current state.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/index-page3.png"
class="margin-around b-all" alt="Welcome page displayed in browser" style="width:688px"
title="Placeholders for header and right-column are visible when running project">
<li>The left column and footer only require placeholders for static text, so let's
implement both simultaneously.
<br><br>
Insert the following code between the <code>&lt;div id=&quot;indexLefttColumn&quot;&gt;</code>
and <code>&lt;div id=&quot;footer&quot;&gt;</code> tags. (New code shown in <strong>bold</strong>.)
<pre class="examplecode">
&lt;div id=&quot;indexLeftColumn&quot;&gt;
<strong>&lt;div id=&quot;welcomeText&quot;&gt;
&lt;p&gt;[ welcome text ]&lt;/p&gt;
&lt;/div&gt;</strong>
&lt;/div&gt;
...
&lt;div id=&quot;footer&quot;&gt;
<strong>&lt;hr&gt;
&lt;p id=&quot;footerText&quot;&gt;[ footer text ]&lt;/p&gt;</strong>
&lt;/div&gt;</pre></li>
<li>Make changes to the <code>affablebean.css</code> stylesheet. It's not necessary
to account for all new IDs and classes - you can fine-tune the appearance at a
later point when you receive text and images from the customer.
<br><br>
The horizontal rule (<code>&lt;hr&gt;</code>) tag runs the full length of its
containing element (<code>&lt;div id=&quot;footer&quot;</code>). Therefore,
to shorten it in accordance with the mockup image, you can adjust the width of
<code>&lt;div id=&quot;footer&quot;&gt;</code>. (New code shown in <strong>bold</strong>.)
<pre class="examplecode">
#footer {
height: 60px;
<strong>width: 350px;</strong>
clear: left;
background: #aaa;
}
<strong>hr {
border: 0;
background-color: #333;
height: 1px;
margin: 0 25px;
width: 300px;
}</strong></pre></li>
<li>Save (Ctrl-S; &#8984;-S on Mac) the <code>index.jsp</code> and <code>affablebean.css</code>
files, then switch to your browser and refresh the page to view its current state.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/index-page4.png"
class="margin-around b-all" alt="Welcome page displayed in browser" style="width:688px"
title="Placeholders for left column and footer are visible" id="welcome-page">
<br>
The welcome page is complete. You've created all necessary placeholders for
components that will exist on the page.
</li>
</ol>
<p>You've now completed the initial design of the application's welcome page. All
placeholders for page components exist. Later in the tutorial, when you begin
to apply dynamic logic to the page views, you can simply plug JSTL and EL
expressions into these placeholders.</p>
<p>The task remains for you to implement the initial design for the other pages
based on the <a href="design.html#mockups">mockups</a>. To accomplish this,
follow the pattern outlined above, namely:</p>
<ol style="margin: 5px 0 0 -.7em">
<li>Create <code>&lt;div&gt;</code> tags for the main page areas.</li>
<li>Iterate through each area and perform three steps:
<ol style="margin: 5px 0 0 -1.4em; list-style-type: lower-alpha">
<li>Create the structure in HTML.</li>
<li>Create a set of styles to define the appearance.</li>
<li>View the page to examine the results of your changes.</li>
</ol></li>
</ol>
<p>Be sure to take advantage of the HTML and CSS support that the IDE provides for you.
Some <a href="#tipsTricks">tips and tricks</a> are outlined below. If you just want
to grab the code for the remaining pages and proceed with the tutorial, you can
<a href="https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252Fecommerce%252FAffableBean_snapshot1.zip">download
snapshot 1 of the <code>AffableBean</code> project</a>. Images of initial mockup
implementations for the remaining pages are included here.</p>
<div class="indent">
<h4 id="categoryPage">category page</h4>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/category-page.png"
class="margin-around b-all" alt="Category page displayed in browser" style="width:708px"
title="Placeholders implemented for category page">
<br><br>
<h4 id="cartPage">cart page</h4>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/cart-page.png"
class="margin-around b-all" alt="Cart page displayed in browser" style="width:708px"
title="Placeholders implemented for cart page">
<br><br>
<h4 id="checkoutPage">checkout page</h4>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/checkout-page.png"
class="margin-around b-all" alt="Checkout page displayed in browser" style="width:708px"
title="Placeholders implemented for checkout page">
<br><br>
<h4>confirmation page</h4>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/confirmation-page.png"
class="margin-around b-all" alt="Confirmation page displayed in browser" style="width:708px"
title="Placeholders implemented for checkout page">
<br><br>
<p class="notes"><strong>Note:</strong> The background colors for each page area only
serve to help you position elements while developing the application. Eventually,
you'll want to remove them from the stylesheet and apply a background color more
suitable for the application. You can do this by adjusting the background rule for
the <code>main</code> class:</p>
<div class="indent">
<pre class="examplecode">#main { background: #f7f7e9 }</pre>
</div>
<h3 id="tipsTricks">Tips and Tricks</h3>
<p>The IDE's editor provides many facilities that help you to work more efficiently.
If you familiarize yourself with keyboard shortcuts and buttons in the editor
toolbar, you can increase your productivity. The following list of tips applies
to the editor for HTML and CSS files. To view more keyboard shortcuts, open the
IDE's Keyboard Shortcuts Card by choosing Help &gt; Keyboard Shortcuts Card from
the main menu.</p>
<ul style="margin: 5px 0 0 -.7em">
<li><strong>Code completion:</strong> When you type in tags and attributes, suggestions
for code completion automatically appear in a pop-up box. Pressing Enter completes
the suggested tag.</li>
<li><strong>Format your code:</strong> Right-click in the editor and choose Format.</li>
<li><strong>Toggle line numbers:</strong> Right-click in the left margin and choose
Show Line Numbers.</li>
<li><strong>Find occurrences:</strong> Highlight a block of text, and press Ctrl-F
(&#8984;-F on Mac). All matches become highlighted in the editor. To toggle
highlighting, press the Toggle Highlight Search (
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/toggle-highlight.png"
alt="Toggle Highlight Search button" class="b-all"> ) button (Ctrl-Shift-H)
in the editor's toolbar.</li>
<li><strong>Create a bookmark:</strong> Press the Toggle Bookmark (
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/toggle-bookmark.png"
alt="Toggle Bookmark button" class="b-all"> ) button (Ctrl-Shift-M) to
create a bookmark in the editor's left margin. Wherever you are in the file,
you can then jump to the bookmark by pressing the Previous/Next Bookmark
buttons in the editors's toolbar.</li>
<li><strong>Copy a code snippet up or down:</strong> Highlight a code snippet,
then press Ctrl-Shift-Up/Down.</li>
<li><strong>Highlight opening and closing tags:</strong> Place your cursor on either
the opening or closing tag, and both are highlighted in yellow.</li>
</ul>
</div>
<br>
<h2 id="view">Placing JSP Pages in WEB-INF</h2>
<p>Looking back at the <a href="design.html#mockups">page mockups</a> that were created,
you can see that the <a href="design.html#index">welcome page</a> should look the same
whenever it is requested, for whomever requests it. That is, the content that displays
on the welcome page is not determined by a user's <em>session</em>. (Sessions are
discussed in Unit 8, <a href="manage-sessions.html">Managing Sessions</a>.) Notice
however that all other pages do need some form of user-specific information to display
properly. For example, the <a href="design.html#category">category page</a> requires
that the user select a category in order to display, and the <a href="design.html#cart">cart
page</a> needs to know all items currently held in a shopper's cart. These pages will
not render properly if the server isn't able to associate user-specific information with
an incoming request. Therefore, we do not want these pages to be accessed directly from
a browser's address bar. The project's <code>WEB-INF</code> folder can be used for this
purpose: any resources contained in the <code>WEB-INF</code> folder are not directly
accessible from a browser.</p>
<p>Create a new folder named <code>view</code>, and place it in the <code>WEB-INF</code>
folder. Then move all JSP pages other than the welcome page into this new folder.</p>
<ol>
<li>In the Projects window, right-click the WEB-INF node and choose New &gt; Folder.</li>
<li>In the New Folder wizard, name the folder <code>view</code> and click Finish.
Notice that a new folder node appears in the Projects window.</li>
<li>Move the <code>category.jsp</code>, <code>cart.jsp</code>, <code>checkout.jsp</code>,
and <code>confirmation.jsp</code> pages into the <code>view</code> folder.
<br><br>
You can do this by clicking on <code>cart.jsp</code> to select it, then Shift-clicking
on <code>confirmation.jsp</code>. This selects the four files. Then, with the four
files selected, click and drag them into the <code>WEB-INF/view</code> folder.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/view-folder.png"
class="margin-around b-all" alt="Projects window displaying JSP pages being dragged into 'view' folder"
title="Click and drag the JSP pages into the 'WEB-INF/view/' folder"></li>
</ol>
<p>To demonstrate that these pages are no longer accessible from a browser, click the
Run Project (
<img src="../../../../images_www/articles/73/javaee/ecommerce/common/run-project-btn.png"
alt="Run Project button"> ) button to run the project. When the application displays in
your browser, enter the full path to any of these files in the address bar. For example,
type in:</p>
<div class="indent">
<pre class="examplecode" style="width:700px">http://localhost:8080/AffableBean/WEB-INF/view/category.jsp</pre>
</div>
<p>You receive an HTTP Status 404 message, indicating that the resource is not available.</p>
<br>
<h2 id="jspf">Creating a Header and Footer</h2>
<p>Looking at the <a href="design.html#mockups">page mockups</a>, it is easy to see
that all of the five views share identical content; at the top, they contain the
company logo, a language toggle, and other widgets associated with shopping cart
functionality. At the bottom, they contain some text with Privacy Policy and
Contact links. Rather than including this code in each page source file, we can
factor it out into two JSP fragments: a header and a footer. We'll then include
the fragment files into page views whenever they need to be rendered.</p>
<p>For these fragments, let's create a new folder named <code>jspf</code>, and place
it within <code>WEB-INF</code>.</p>
<ol>
<li>In the Projects window, right-click the WEB-INF node and choose New &gt; Folder.</li>
<li>In the New Folder wizard, name the folder <code>jspf</code> and click Finish.
<br><br>
<p class="tips">Menu items provided by the IDE are often context-sensitive.
For example, because you right-clicked the WEB-INF node, when the New Folder
wizard displayed, <code>web/WEB-INF</code> was automatically entered in the
Parent Folder field. Likewise, when you right-click a node in the Projects
window and choose New, the list of file types is partially determined by
your previous selections.</p>
</li>
<li>Create two JSP segments: <code>header.jspf</code> and <code>footer.jspf</code>.
To do so, right-click the newly created <code>jspf</code> folder and choose New
&gt; JSP. In the New JSP wizard, enter the file name, and under Options, select
the Create as a JSP Segment option, then click Finish.
<br><br>
When you finish, you'll see <code>header.jspf</code> and <code>footer.jspf</code>
displayed in your Projects window:
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/projects-win-jspf.png"
class="margin-around b-all" alt="Projects window displaying JSP fragments"
title="Header and footer JSP fragments are displayed in the project">
<br><br>
Now, you can copy the header code from any of the JSP pages and paste it into the
<code>header.jspf</code> file. Likewise, you can copy the footer code from any of
the JSP pages and paste it into the <code>footer.jspf</code> file. When you finish
this task, you can remove the header and footer code from all of the JSP pages.</li>
<li>Copy the header code from any of the JSP pages and paste it into the
<code>header.jspf</code> file. The header should include the page doctype
and the opening <code>&lt;html&gt;</code>, <code>&lt;head&gt;</code>, and
<code>&lt;body&gt;</code> tags through to the closing tag for the
<code>&lt;div id=&quot;header&quot&gt;</code> element. Be sure to include
placeholders for the shopping cart widget, language toggle, and 'proceed to
checkout' button used along the top of page views. After you paste code into
<code>header.jspf</code>, the file will look as follows.
<pre class="examplecode">
&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/affablebean.css&quot;&gt;
&lt;title&gt;The Affable Bean&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;main&quot;&gt;
&lt;div id=&quot;header&quot;&gt;
&lt;div id=&quot;widgetBar&quot;&gt;
&lt;div class=&quot;headerWidget&quot;&gt;
[ language toggle ]
&lt;/div&gt;
&lt;div class=&quot;headerWidget&quot;&gt;
[ checkout button ]
&lt;/div&gt;
&lt;div class=&quot;headerWidget&quot;&gt;
[ shopping cart widget ]
&lt;/div&gt;
&lt;/div&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;img src=&quot;#&quot; id=&quot;logo&quot; alt=&quot;Affable Bean logo&quot;&gt;
&lt;/a&gt;
&lt;img src=&quot;#&quot; id=&quot;logoText&quot; alt=&quot;the affable bean&quot;&gt;
&lt;/div&gt;</pre></li>
<li>Copy the footer code from any of the JSP pages and paste it into the <code>footer.jspf</code>
file. The footer code should include the <code>&lt;div id=&quot;footer&quot;&gt;</code>
element, through to the closing <code>&lt;html&gt;</code> tag. After you paste code into
<code>footer.jspf</code>, the file will look as follows.
<pre class="examplecode">
&lt;div id=&quot;footer&quot;&gt;
&lt;hr&gt;
&lt;p id=&quot;footerText&quot;&gt;[ footer text ]&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></li>
<li>Remove the header and footer code from all five JSP pages (<code>index.jsp</code>,
<code>category.jsp</code>, <code>cart.jsp</code>, <code>checkout.jsp</code>,
and <code>confirmation.jsp</code>).</li>
</ol>
<br>
<h2 id="dd">Adding a Directive to the Deployment Descriptor</h2>
<p>So far, you've placed views in their proper location and have factored out
common header and footer code into the <code>header.jspf</code> and
<code>footer.jspf</code> files. The application still needs to know which
pages the header and footer files will be applied to. You could add
<code>&lt;jsp:include&gt;</code> tags to each of the page views. Doing so
however would just reintroduce the code repetition which we've just made
efforts to eliminate. An alternative solution would be to create a <code>web.xml</code>
deployment descriptor, and add a JSP Property Group directive to specify
which page views the header and footer fragments should apply to.</p>
<ol>
<li>Press Ctrl-N (&#8984;-N on Mac) to open the New File wizard. Select the Web
category, then under File Types, select Standard Deployment Descriptor (web.xml).</li>
<li>Click Next. Note that the file is named <code>web.xml</code>, and that the
wizard will place it in the project's <code>WEB-INF</code> directory upon completion.</li>
<li>Click Finish. The <code>web.xml</code> file is created and added to the project.
The IDE's graphical interface for the deployment descriptor opens in the editor.
<br><br>
The interface is categorized by the areas that can be configured in a web application.
These areas are displayed as tabs in the editor toolbar, and include topics such
as Servlets, Filters, References, and Security. The XML tab displays the entire
source code for the file. Any changes you make in the graphical interface will
cause immediate updates to the deployment descriptor's source code, which you
can verify by switching to the XML tab. This is demonstrated in the following steps.</li>
<li>Click the Pages tab, then click the Add JSP Property Group button. The
Add JSP Property Group dialog opens.</li>
<li>Type in '<code>header and footer settings</code>' for the Description field.
Leave Display Name blank. Both the Display Name and Description fields are
optional.</li>
<li>For URL Patterns, specify the paths to the five views. Type in
'<code>/index.jsp</code>' and '<code>/WEB-INF/view/*</code>'. Separate the
two paths with a comma. (The '<code>*</code>' is a wildcard that represents
all files within the given folder.)
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/add-jsp-prop-group-dialog.png"
class="margin-around b-all" alt="Add JSP Property Group dialog"
title="Use the Add JSP Property Group dialog to specify &lt;jsp-config&gt; tags in the deployment descriptor"></li>
<li>Click OK. An entry is added to the JSP Properties Groups category in the Pages tab.</li>
<li>Switch back to the XML tab. Notice that the following code has been added to
the deployment descriptor.
<pre class="examplecode">
&lt;jsp-config&gt;
&lt;jsp-property-group&gt;
&lt;description&gt;header and footer settings&lt;/description&gt;
&lt;url-pattern&gt;/index.jsp&lt;/url-pattern&gt;
&lt;url-pattern&gt;/WEB-INF/view/*&lt;/url-pattern&gt;
&lt;/jsp-property-group&gt;
&lt;/jsp-config&gt;</pre>
<p class="notes"><strong>Note:</strong> You may need to add carriage returns
to the code so that it displays on multiple lines. You can right-click in
the editor and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac) to have the
code properly indented.</p></li>
<li>Switch to the Pages tab again, and in the Include Preludes and Include Codas
fields, enter the paths to the <code>header.jspf</code> and <code>footer.jspf</code>
files, respectively. You can click the Browse button and navigate to the files
in the provided dialog.
<br>
<a href="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/jsp-prop-groups.png"
title="Enter paths to the header and footer in the JSP Property Group" rel="lytebox">
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/jsp-prop-groups-small.png"
class="margin-around b-all" alt="JSP Property Group shown under Pages tab of web.xml" title="Click to enlarge"></a></li>
<li>Switch back to the XML tab. Note that the following code has been added.
(Changes in <strong>bold</strong>.)
<pre class="examplecode">
&lt;jsp-config&gt;
&lt;jsp-property-group&gt;
&lt;description&gt;header and footer settings&lt;/description&gt;
&lt;url-pattern&gt;/index.jsp&lt;/url-pattern&gt;
&lt;url-pattern&gt;/WEB-INF/view/*&lt;/url-pattern&gt;
<strong>&lt;include-prelude&gt;/WEB-INF/jspf/header.jspf&lt;/include-prelude&gt;
&lt;include-coda&gt;/WEB-INF/jspf/footer.jspf&lt;/include-coda&gt;</strong>
&lt;/jsp-property-group&gt;
&lt;/jsp-config&gt;</pre>
The above directive specifies that for all files found within the
given <code>url-pattern</code>s, the <code>header.jspf</code> file
will be prepended, and the <code>footer.jspf</code> file appended.
<br><br>
<p class="tips">To view the definitions of the above tags, as well as
all tags available to you in the web deployment descriptor, consult the
<a href="http://jcp.org/en/jsr/detail?id=315" target="_blank">Servlet
Specification</a>.</p></li>
<li>Run the application again (press F6; fn-F6 on Mac). You've already removed
the header and footer code from the <code>index.jsp</code> file, so you can
determine whether it is automatically being added when the file is requested.
<br><br>
You will see that the <a href="#welcome-page">welcome page displays as it
did previously</a>, with header and footer content included.</li>
</ol>
<br>
<h2 id="controller">Creating the Controller Servlet</h2>
<p>The controller servlet handles incoming requests by initiating any actions
needed to generate the model for the request, then forwarding the request
to the appropriate view. For a visual representation, refer back to the
<a href="design.html#mvcDiagram">MVC diagram for the AffableBean project</a>.</p>
<p>The IDE provides a Servlet wizard that enables you to define the servlet component
in a web application either by including the <code>@WebServlet</code> annotation
in the generated class, or by adding the necessary directives to the deployment
descriptor. In the following steps, you create the <code>ControllerServlet</code>
and define it in the application context using the
<a href="http://java.sun.com/javaee/6/docs/api/javax/servlet/annotation/WebServlet.html" target="_blank"><code>@WebServlet</code></a>
annotation.</p>
<ol>
<li>In the Projects window, right-click the <code>AffableBean</code> project
node and choose New &gt; Servlet.</li>
<li>In the wizard, type <code>ControllerServlet</code> in the Class Name field.</li>
<li>In the Package field, type <code>controller</code>. (The new package is
automatically created when you complete the wizard.)
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/servlet-wizard.png"
class="margin-around b-all" alt="Servlet wizard"
title="Use the Servlet wizard to create servlets for your project"></li>
<li>Click Next. Step 3 of the wizard lets you configure the servlet. Of primary
importance are the URL patterns that you need to specify. The patterns identify
the URLs that invoke the servlet. For example, if you enter '<code>/category</code>',
you are directing the servlet to handle a request that appears as follows.
<pre class="examplecode">http://localhost/AffableBean<strong>/category</strong></pre>
The URL patterns should correspond to the views and actions that a user can initiate.
Looking at the <a href="design.html#index">welcome page mockup</a>, a user should
be able to select a category. We can therefore associate the <code>/category</code>
URL with the action of clicking on a category image. Likewise, in the
<a href="design.html#category">category page</a>, users should be able to
add an item to the shopping cart. We can therefore specify <code>/addToCart</code>.</li>
<li>In the URL Pattern(s) field, type in '<code>/category, /addToCart, /viewCart</code>'.
Patterns are separated by commas. You can add more patterns directly in the servlet
class once it's created.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/servlet-wizard2.png"
class="margin-around b-all" alt="Servlet wizard, Step 3: Configure Servlet Deployment"
title="Configure servlet deployment directly in the wizard"></li>
<li>Click Finish. The IDE generates the <code>ControllerServlet</code> and opens it
in the editor. The servlet and URL patterns are included in the <code>@WebServlet</code>
annotation that appears above the class signature.
<pre class="examplecode">
<strong>@WebServlet(name=&quot;ControllerServlet&quot;, urlPatterns={&quot;/category&quot;, &quot;/addToCart&quot;, &quot;/viewCart&quot;})</strong>
public class ControllerServlet extends HttpServlet {</pre>
In the previous step, if you had chosen the '<code>Add information to deployment
descriptor (web.xml)</code>' option in the wizard, the following markup would have
been generated in the application's <code>web.xml</code> file instead.
<pre class="examplecode">
&lt;servlet&gt;
&lt;servlet-name&gt;ControllerServlet&lt;/servlet-name&gt;
&lt;servlet-class&gt;controller.ControllerServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;ControllerServlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;/category&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;ControllerServlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;/addToCart&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;ControllerServlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;/viewCart&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;</pre></li>
<li>Add other URL patterns directly to the <code>@WebServlet</code> annotation's
<code>urlPatterns</code> element. The application requires more URL patterns
for other actions and views. You can type in the following patterns:
<ul class="toc" style="margin: 5px 0 0 -1em">
<li><code>/updateCart</code></li>
<li><code>/checkout</code></li>
<li><code>/purchase</code></li>
<li><code>/chooseLanguage</code></li>
</ul>
Be sure to separate each pattern with a comma. You can also reformat the
annotation as follows:
<pre class="examplecode">
@WebServlet(name=&quot;ControllerServlet&quot;,
urlPatterns = {&quot;/category&quot;,
&quot;/addToCart&quot;,
&quot;/viewCart&quot;<strong>,
&quot;/updateCart&quot;,
&quot;/checkout&quot;,
&quot;/purchase&quot;,
&quot;/chooseLanguage&quot;</strong>})</pre></li>
<li>Finally, include the <code>loadOnStartup</code> element so that the servlet
is instantiated and initialized when the application is deployed. A value of <code>0</code>
or greater will cause this to happen (<code>-1</code> is the default).
<pre class="examplecode">
@WebServlet(name=&quot;ControllerServlet&quot;,
<strong>loadOnStartup = 1,</strong>
urlPatterns = {&quot;/category&quot;,
&quot;/addToCart&quot;,
&quot;/viewCart&quot;,
&quot;/updateCart&quot;,
&quot;/checkout&quot;,
&quot;/purchase&quot;,
&quot;/chooseLanguage&quot;})</pre></li>
</ol>
<br>
<h2 id="implement">Implementing the Controller Servlet</h2>
<p>As previously stated, the controller servlet handles incoming requests by initiating
any actions needed to generate the model for the request, then forwarding the request
to the appropriate view. For a visual representation, refer back to the
<a href="design.html#mvcDiagram">MVC diagram for the AffableBean project</a>.</p>
<p>Looking at the generated code for the new <code>ControllerServlet</code>, you
can see that the IDE's servlet template employs a <code>processRequest</code>
method which is called by both <code>doGet</code> and <code>doPost</code>
methods. (You may need to expand the code fold by clicking the plus icon (
<img src="../../../../images_www/articles/73/javaee/ecommerce/common/code-fold-icon.png"
alt="Code fold icon"> ) in the editor's left margin to view these methods.) Because
this application differentiates between <code>doGet</code> and <code>doPost</code>,
you'll add code directly to these methods and remove the <code>processRequest</code>
method altogether.</p>
<div class="indent">
<div class="feedback-box float-left" style="width: 703px;">
<h3>Modifying File Templates with the IDE's Template Manager</h3>
<p>The IDE provides you with a basic template for any new file you create.
If the template is not optimal for your work patterns, you can alter it
using the IDE's Template Manager. The IDE provides a template for virtually
any file type.</p>
<p>For example, to modify the servlet template:</p>
<ol>
<li>Open the Template Manager by choosing Tools &gt; Templates from
the main menu.</li>
<li>Expand the Web category, then select the Servlet template.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/template-manager.png"
class="margin-around b-all" title="Access and modify file templates via the Template Manager"
alt="Template Manager"/></li>
<li>Click the Open in Editor button.</li>
<li>Modify the template in the editor. The next time you create a new
servlet (e.g., using the Servlet wizard), the new version will be
applied.</li>
</ol>
</div>
</div>
<br style="clear: both;"/>
<br>
<p>Now that you've mapped URL patterns to the servlet using the <code>@WebServlet</code>
annotation, set up the <code>ControllerServlet</code> to handle these patterns. Also,
instantiate a <code>RequestDispatcher</code> to forward the requested pattern to the
appropriate view.</p>
<ol>
<li>Replace the <code>ControllerServlet</code> class template code with
the following code.
<pre class="examplecode">
public class ControllerServlet extends HttpServlet {
/**
* Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals(&quot;/category&quot;)) {
// TODO: Implement category request
// if cart page is requested
} else if (userPath.equals(&quot;/viewCart&quot;)) {
// TODO: Implement cart page request
userPath = &quot;/cart&quot;;
// if checkout page is requested
} else if (userPath.equals(&quot;/checkout&quot;)) {
// TODO: Implement checkout page request
// if user switches language
} else if (userPath.equals(&quot;/chooseLanguage&quot;)) {
// TODO: Implement language request
}
// use RequestDispatcher to forward request internally
String url = &quot;/WEB-INF/view&quot; + userPath + &quot;.jsp&quot;;
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if addToCart action is called
if (userPath.equals(&quot;/addToCart&quot;)) {
// TODO: Implement add product to cart action
// if updateCart action is called
} else if (userPath.equals(&quot;/updateCart&quot;)) {
// TODO: Implement update cart action
// if purchase action is called
} else if (userPath.equals(&quot;/purchase&quot;)) {
// TODO: Implement purchase action
userPath = &quot;/confirmation&quot;;
}
// use RequestDispatcher to forward request internally
String url = &quot;/WEB-INF/view&quot; + userPath + &quot;.jsp&quot;;
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}</pre>
As you continue through the tutorial, you'll return to the <code>ControllerServlet</code>
and implement each of the mapped URL patterns individually.</li>
<li>Examine the code above. There are several points to note:
<ul style="margin: 5px 0 0 -2em">
<li>The servlet uses a <code>userPath</code> instance variable to get the
requested URL pattern from the client:
<pre class="examplecode" style="width: 640px">String userPath = request.getServletPath();</pre>
<code>userPath</code> is used by both <code>doGet</code> and <code>doPost</code>
methods.</li>
<li>URL patterns associated primarily with page requests are managed by the
<code>doGet</code> method. For example, <code>/category</code>,
<code>/viewCart</code>, and <code>/checkout</code> result in the display
of the category, cart, and checkout pages.) </li>
<li>URL patterns associated with form submits and the transport of
sensitive user data (e.g., <code>/addToCart</code>, <code>/updateCart</code>,
and <code>/purchase</code>) are managed by the <code>doPost</code>
method.</li>
<li>For both <code>doGet</code> and <code>doPost</code> methods, the path
to the appropriate view is formed using a <code>url</code> string:
<pre class="examplecode" style="width: 640px">String url = &quot;/WEB-INF/view&quot; + userPath + &quot;.jsp&quot;;</pre>
</li>
<li>The <code>RequestDispatcher</code> is obtained from the <code>HttpServletRequest</code>
and applies the <code>url</code> to forward the request:
<pre class="examplecode" style="width: 640px">request.getRequestDispatcher(url).forward(request, response);</pre>
</li>
<li><code>TODO</code> notes have been used to denote work that still needs
to be done. For example:
<pre class="examplecode" style="width: 640px">// if category page is requested
if (userPath.equals(&quot;/category&quot;)) {
// TODO: Implement category request</pre>
Applying <code>TODO</code> notes in your code is a useful way to keep track
of tasks that you need to complete. You can use the IDE's Tasks window
(Ctrl-6; &#8984;-6 on Mac) to view all TODO notes, as well as any syntax or
compile errors contained in your project.
<br>
<img src="../../../../images_www/articles/73/javaee/ecommerce/page-views-controller/tasks-window.png"
class="margin-around b-all" title="Keep track of implementation tasks with the IDE's Tasks window"
alt="Tasks window"/>
<br>
<p class="tips">You can control the keywords that display in the Tasks window.
Open the Options window (Tools &gt; Options; NetBeans &gt; Preferences on Mac),
then choose Miscellaneous &gt; Tasks.</p></li>
</ul>
</li>
<li>Run the project (press F6; fn-F6 on Mac) and test to see whether the <code>ControllerServlet</code>
is forwarding requests to the appropriate views.
<ul style="margin: 5px 0 0 -2em">
<li>Type in <code>http://localhost:8080/AffableBean/category</code> in the browser's
address bar. The application's <a href="#categoryPage">category page</a>
displays.</li>
<li>Type in <code>http://localhost:8080/AffableBean/viewCart</code> in the browser's
address bar. The application's <a href="#cartPage">cart page</a> displays.</li>
<li>Type in <code>http://localhost:8080/AffableBean/checkout</code> in the browser's
address bar. The application's <a href="#checkoutPage">checkout page</a>
displays.</li>
</ul>
<p class="notes"><strong>Note:</strong> Entering <code>http://localhost:8080/AffableBean/purchase</code>
in the browser's address bar does not allow you to view the <a href="#confirmationPage">confirmation
page</a>. Naturally, this is because the <code>/purchase</code> URL pattern is handled
by the servlet's <code>doPost</code> method, and requests sent from the browser's address
bar are typically sent using the HTTP GET method.</p></li>
</ol>
<p>At this stage, you've created JSP pages that contain placeholders for functional components.
You've also set up the front-end structure of the application. JSP pages now reside within
the <code>WEB-INF</code> folder, header and footer code has been factored out into separate
files, your deployment descriptor is properly configured, and you've set up the
<code>ControllerServlet</code> to handle incoming requests. In the next tutorial unit, you
take measures to enable connectivity between the application and the database.</p>
<p>If you'd like to compare your work with the sample solution for this unit, you can
<a href="https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252Fecommerce%252FAffableBean_snapshot2.zip">download
snapshot 2 of the AffableBean project</a>.</p>
<div class="feedback-box">
<a href="/about/contact_form.html?to=3&amp;subject=Feedback: NetBeans E-commerce Tutorial - Preparing the Page Views and Controller Servlet">Send
Us Your Feedback</a></div>
<br style="clear:both;">
<h2 id="seeAlso">See Also</h2>
<div class="indent">
<h3>NetBeans Tutorials</h3>
<ul>
<li><a href="../javaee-intro.html" target="_blank">Introduction to Java EE Technology</a></li>
<li><a href="../javaee-gettingstarted.html" target="_blank">Getting Started with Java EE Applications</a></li>
<li><a href="../../web/quickstart-webapps.html" target="_blank">Introduction to Developing Web Applications</a></li>
<li><a href="../../web/mysql-webapp.html" target="_blank">Creating a Simple Web Application Using a MySQL Database</a></li>
<li><a href="../../../../community/media.html" target="_blank">Video Tutorials and Demos for NetBeans IDE</a></li>
<li><a href="https://netbeans.org/projects/www/downloads/download/shortcuts.pdf">Keyboard Shortcuts & Code Templates Card</a></li>
<li><a href="../../../trails/java-ee.html" target="_blank">Java EE & Java Web Learning Trail</a></li>
</ul>
<h3>NetBeans Books</h3>
<ul>
<li><a href="https://netbeans.org/kb/articles/netbeans-tips-and-tricks-book.html" target="_blank">100 NetBeans IDE Tips and Tricks</a></li>
<li><a href="http://www.apress.com/book/view/1590598954" target="_blank">Pro NetBeans IDE 6 Rich Client Platform Edition</a></li>
<li><a href="http://apress.com/book/view/1430219548" target="_blank">Beginning Java EE 6 Platform with GlassFish 3: From Novice to Professional</a></li>
<li><a href="https://netbeans.org/kb/articles/books.html" target="_blank">More books about NetBeans IDE</a></li>
</ul>
<h3>External Resources</h3>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=315" target="_blank">Servlet 3.0 Specification</a></li>
<li><a href="https://developer.mozilla.org/en/Common_CSS_Questions" target="_blank">Common CSS Questions</a></li>
<li><a href="http://quirksmode.org/compatibility.html" target="_blank">Browser Compatibility Master Table</a></li>
<li><a href="http://refcardz.dzone.com/refcardz/netbeans-ide-67-update" target="_blank">DZone Refcard for NetBeans Java Editor</a></li>
</ul>
</div>
</body>
</html>