First Steps With Jakarta Struts, Part 2

Share this article

Last time we looked at Jakarta Struts, I explained the persistence and business object layers and we wrote code to retrieve the list of topics from the database and represent them as objects. We used a Struts ActionMapping and an ActionForward, to get as far as the JSP that will actually display the topics on the screen. Let’s look at that task in a little more detail now.

If you haven’t already, you might first want to download the code that we’ll use:

Displaying the Topics

Struts comes with a bean taglib, that provides JavaBeans-related functionality and an html taglib that renders common HTML attributes and JavaScript event handlers. Both are used within topics.jsp, as is the logic taglib mentioned last time.

The following code fragment (from topics.jsp), illustrates the use of the bean:message tag, which is used to render an internationalised message, based on a message key and locale. This allows us to separate out the user interface string constants that are used in the application, rather than having to hard-code them into the JSPs. These strings are looked up in a Java properties file that’s specified using the message-resources tag, in the Struts configuration file.

<bean:message key="app.doctype" /> 
<html:html locale="true" xhtml="true">
 <head>
   <bean:message key="app.content.language" />
   <bean:message key="app.content.type" />
   <link rel="stylesheet" type="text/css"
     href="<html:rewrite page="/assets/css/webforum.css" />" />
   <title>
     <bean:message key="topics.title" /> - <bean:message
       key="app.title" />
   </title>
 </head>

This code uses bean:message tags to render the DOCTYPE declaration, as well as the HTML Content-Type and Content-Language meta declarations. The html:html tag is used to render the HTML tag at the start of the document, using an XHTML format declaration and appropriate locale.

Within the struts-config.xml file, the declaration for the properties file that contains the string constants appears as follows:

<message-resources parameter="com.johntopley.webforum.view.Resources" 
 null="false"/>

<message-resources parameter="com.johntopley.webforum.view.GlobalErrors"
 null="false" key="GlobalErrors"/>

This section must come after the <action-mappings> section. It tells Struts to expect to find all of the user interface string constants, in the files Resources.properties and GlobalErrors.properties, and that both of these files are located in the com.johntopley.webforum.view package.

The null attribute isn’t very intuitive; set it to false to ensure that any errors arising from an inability to find a message resource within the properties file, are displayed on the JSP. This is particularly useful when debugging. I’ve also declared that I’ll be using a separate properties file, to store error string constants. The key attribute tells Struts that I want the messages from the second property file, to be stored with a separate, named bundle key – GlobalErrors. A bean:message tag must have a bean="GlobalErrors" attribute to display a message from this file. Note that storing the error strings in a properties file, that’s separate from the rest of the user interface text, is entirely optional. I do it because I like the extra separation.

The html:rewrite tag is used in the stylesheet link statement, to generate the correct URL for the path to the stylesheet. This is then passed to the HTML link tag as normal.

Let’s take a look at the Resources.properties file. A convention I like to use, is to prefix application-wide string constants with “app”. I prefix all other string constants, with the name of the JSP in which they’re used. For example, these are the constants for the Topics page:

#-- topics.jsp -- 
topics.guest.welcome.1=Welcome Guest.
topics.guest.welcome.2=Register
topics.guest.welcome.3= or
topics.guest.welcome.4=Log in
topics.guest.welcome.5=to create a new topic.
topics.heading.column1=Subject
topics.heading.column2=Replies
topics.heading.column3=Author
topics.heading.column4=Posted
topics.newtopic=New Topic
topics.notopics=There are no topics to display.
topics.table.summary=A list of topics and summary information about them
topics.title=Topics
topics.viewtopics=View Topics

Recall from last time, that we have a Posts object stored in the HTTP request, that contains an ordered collection of Post objects. We somehow need to loop through this collection and retrieve the relevant information from each Post object. Struts comes to our rescue with three tags from the logic taglib.

We use the iterate tag to iterate through the collection. But first of all, we need to account for the fact that we might be dealing with an empty collection: there may not be any topics to display. The notEmpty tag and its opposite number, the empty tag, allow conditional processing on the basis of whether a particular variable is null, or an empty String, Collection or Map object. Here’s the outline code from topics.jsp:

<logic:notEmpty name="com.johntopley.webforum.postlist" property="posts"> 
 <logic:iterate id="topic" name="com.johntopley.webforum.postlist"
   type="com.johntopley.webforum.model.Post"
   property="posts" length="16">
   .
   <%-- There are posts, so display the details. --%>
   .
 </logic:iterate>
</logic:notEmpty>
<logic:empty name="com.johntopley.webforum.postlist" property="posts">
 .
 <%-- No posts, display a message. --%>
 .
</logic:empty>

There’s quite a lot going on here. The name attribute used in the notEmpty, iterate and empty tags, tells Struts the name of a JavaBean that holds the collection to be iterated over. In this case, it’s com.johntopley.webforum.postlist, which you may remember is the HTTP request key that we stored the Posts objects under, in the ViewTopicsAction Action class. We used a bit of indirection there, because we didn’t refer to the key directly. Instead we referred to it via the POST_LIST_KEY public static variable, in the KeyConstants class. By the way, notice how I prefix the key with the package name, to help avoid namespace collisions within the HTTP request.

The property attribute is also used in all three tags. It tells Struts which of the properties on the bean referred to by name, contains the collection. The value for this attribute, should be set to the name of the accessor (getter) method in the collection class, but without the “get” (or for boolean properties, without the “is”). Our Posts class has a getPosts method, so we simply set property to the value posts.

The id attribute in the iterate tag, creates a local variable within the tag body; we can use this to refer to the current row within the loop. I’ve called it topic. Think of it as being similar to the “i” variable within a “for” loop. I’ve also used the length attribute, to specify that we only want to display the top sixteen topics.

Finally, the type attribute, is the fully-qualified class name, to which we want to downcast the object representing each row. This is important; if we don’t perform this cast, we won’t be able to access the properties of each individual Post object within the collection, as we’ll still be dealing with java.lang.Object(s).

Note that the combination of the notEmpty and empty tags, effectively allows us to create an if/else structure, without having to resort to JSP scriptlet code. It’s good practice to try to avoid scriptlets in JSPs — they should contain only markup, not bare Java code. This conditional if/else processing pattern, is repeated with other tags within the logic taglib.

Adding the body to the loop, gives us our list of topics at last:

<logic:notEmpty name="com.johntopley.webforum.postlist" property="posts"> 
 <logic:iterate id="topic" name="com.johntopley.webforum.postlist"
   type="com.johntopley.webforum.model.Post"
   property="posts" length="16">

   <tr>
     <td class="topics">
       <bean:write name="topic" property="subject" filter="true" />
     </td>
     <td class="replies">
       <bean:write name="topic" property="replyCount" />
     </td>
     <td class="author">
       <bean:write name="topic" property="author" />
     </td>
     <td class="posted">
       <bean:write name="topic" property="timestamp"
         formatKey="app.date.format" />
     </td>
   </tr>
 </logic:iterate>
</logic:notEmpty>
<logic:empty name="com.johntopley.webforum.postlist" property="posts">
 <tr>
   <td class="topics">
     <bean:message key="topics.notopics" />
   </td>
   <td class="replies"></td>
   <td class="author"></td>
   <td class="posted"></td>
 </tr>
</logic:empty>

The most important point to note here is the use of bean:write tags to render the contents of the JavaBean, referred to by that tag’s name attribute. We join it all together by setting the value of this attribute to the topic bean, provided by the iterate tag for each row within the loop. Because we’ve cast the objects within the collection to the correct type, the write tag can access the properties of each Post object, using the JavaBeans convention explained earlier.

Now, we’ve written most of the JSP that’s required to display the list of topics. Without further delay, let’s write the code that makes each topic subject a hyperlink.

Creating Topic Hyperlinks

The Struts html:link tag is used to render a hyperlink, as the name suggests. The code below uses the tag’s forward attribute, to specify the name of the global ActionForward that contains the URI of the hyperlink (in this case, ViewTopic):

<tr> 
 <td class="topics">
   <html:link forward="ViewTopic" name="params">
     <bean:write name="topic" property="subject" filter="true" />
   </html:link>
 </td>

I’ll explain the use of the name attribute in a moment. First of all, I want to explain what the filter attribute is doing in the bean:write tag. Quite simply, when set to true, it replaces HTML reserved characters with their equivalent entities. Although the default value is true, I’ve included it within the code to make the process clear.

Now, back to the task at hand. You may also recall from the first part of this series that we want topic hyperlinks to appear in the unvisited link colour, when new replies are made to a topic. This means that the hyperlink needs to be subtly changed when there’s a new reply. Somehow, we need to encode within the hyperlink not only the unique ID of the topic that we want to view, but also another query parameter that indicates the number of replies to that topic.

The link tag lets us reference a JavaBean that contains a Map of query parameters – or has a property that itself contains such a Map. In this case, we can create such a bean and refer to it using the name attribute within the link tag. The jsp:useBean tag is used outside the logic:iterate loop to create a page-scope bean called params, which is a HashMap.

Within the loop, we have a two-line scriptlet that:

  • stores the number of replies to the topic in the HashMap under a key named r
  • stores the post ID of the topic in the HashMap under a key named pid

Unfortunately, I couldn’t work out a way to eliminate the scriptlet code. But at least it’s only two lines. I’m sure it could be eliminated using the JSTL, but that’s the subject for another tutorial! The complete code is shown below:

<jsp:useBean id="params" class="java.util.HashMap" scope="page" /> 
<logic:notEmpty name="com.johntopley.webforum.postlist" property="posts">
 <logic:iterate id="topic" name="com.johntopley.webforum.postlist"
   type="com.johntopley.webforum.model.Post"
   property="posts" length="16">
   <%
     params.put("r", topic.getReplyCount());
     params.put("pid", topic.getPostID());
   %>
   <tr>
     <td class="topics">
       <html:link forward="ViewTopic" name="params">
         <bean:write name="topic" property="subject" filter="true" />
       </html:link>
     </td>
     .
     .
     .
   </tr>
 </logic:iterate>
</logic:notEmpty>

The actual hyperlinks end up looking like this:

<a href="/webforum/ViewTopic.do?pid=1&amp;r=1">Some Topic</a> 
<a href="/webforum/ViewTopic.do?pid=2&amp;r=18">Another Topic</a>
Next Time

In the next instalment we’ll look at adding to the listed topics hyperlinks that, when clicked upon, allow users to view the topic text and any associated replies.

John TopleyJohn Topley
View Author

John is a J2EE developer based in the UK, with a particular interest in user interface development and Web standards. John's Weblog and knowledge base is at http://www.johntopley.com/.

Share this article
Read Next
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
12 Outstanding AI Tools that Enhance Efficiency & Productivity
12 Outstanding AI Tools that Enhance Efficiency & Productivity
Ilija Sekulov
React Performance Optimization
React Performance Optimization
Blessing Ene Anyebe
Introducing Chatbots and Large Language Models (LLMs)
Introducing Chatbots and Large Language Models (LLMs)
Timi Omoyeni
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Ampere Computing
Scale Your React App with Storybook and Chromatic
Scale Your React App with Storybook and Chromatic
Daine Mawer
10 Tips for Implementing Webflow On-page SEO
10 Tips for Implementing Webflow On-page SEO
Milan Vracar
Get the freshest news and resources for developers, designers and digital creators in your inbox each week