First Steps With Jakarta Struts, Part 2

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:

  • ">Download (855 KB)
  • ">Download (52.2 KB)

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 and, 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 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="" />        </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/;r=1">Some Topic</a>  <a href="/webforum/;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.


Category: java Time: 2005-06-15 Views: 1

Related post

  • First Steps with Jakarta Struts 2005-05-06

    Just over a year ago, I started to learn how to use the Jakarta Struts J2EE Web application framework. During this journey, I realised that I found some aspects of Struts confusing at first, and that many other developers might well suffer the same d

  • First steps with htlatex, I'm losing all the math format! 2015-07-09

    I'm doing my first steps with htlatex, trying to get HTML documents. I have OS: Linux Mint, Tex Live, and I make my *.tex with Texmaker. I know how to use MathJax. I get this: This is how I wish it should look! So I managed this with Pandoc, I simply

  • Only first step with multi step registration 2014-08-22

    This question is an exact duplicate of: Multiple registration phases 1 answer I'm using the module Multi-step Registration for my user accounts. I have six steps in my registration proces. But now I want to show only the FIRST step when a user regist

  • first steps with sockets [on hold] 2016-02-05

    They are the first experience with networking and do not understand where I'm wrong. For the first exercise I simply connect to a port on my IP address, but gives me except when I use accept (); you know help me? Socket firstSocket = new Socket(Addre

  • First steps with amd64 assembly 2012-04-23

    I try to learn amd64 assembler. This is the first thing I tried. This piece of assembly should replicate the functionality of the following piece of C code, which turns a binary sha-256 hash into a human readable form. assembly code 1: .ascii "012345

  • first steps with ISPConfig 3... help please 2014-09-23

    Ok, I have installed ISP3 on my Debian Lenny box. It is sitting on my home network at the address Please consider that I am not familiar with either ISPconfig 2 or 3. I am a noob. I can login to ISP3 at and php

  • Recommended first steps with the BeagleBoard 2010-12-26

    How can I easily start off professional development with the BeagleBoard XM? Which OS should I work with? .. my choices include: Ubuntu Android MeeGo WinCE QNX Angstrom (preinstalled) Symbian Gentoo How do I install an OS onto the board? Which IDE do

  • First steps with LuaLaTeX and ttf fonts 2014-01-25

    I am just starting to use LuaLaTeX. Mainly because I want to use a ttf font for a presentation. My MWE looks like \documentclass{article} \usepackage{fontspec} \setmainfont[]{HelveticaNeue/HelveticaNeueLTCom-Th.ttf} \begin{document} Test \end{documen

  • How to build ui router nesting where navigation is first state - with multiple "wizards" with 3 steps or more 2016-01-31

    I'm trying to build a nested view using AngularJS and UI router. The solution should have multiple steps with different questionares. First step is a menu that leads to different wizards (each with 3 or more steps). Problem is the menu should dissape

  • SitePoint Podcast #54: Building Communities with Derek Powazek, Part 2 2010-03-26

    Episode 54 of The SitePoint Podcast is now available! This week, Kevin Yank (@sentience) and Patrick O'Keefe (@iFroggy) conclude their conversation with Derek Powazek (@fraying), co-creator of JPG Magazine and creator of Fray, about the care and feed

  • Performance problem with custom web part 2011-05-13

    We've implemented a custom web part which we use to render content of an external website into a SharePoint page. During our test we encountered some strange performance issues. When we open a page with the web part for the first time it takes about

  • First Steps of Making a Programming Language 2011-06-15

    I am thorough with programming and have come across languages including BASIC, FORTRAN, COBOL, LISP, LOGO, Java, C++, C, MATLAB, Mathematica, Python, Ruby, Perl, JavaScript, Assembly and so on. I can't understand how people create programming languag

  • Creating a Graph With Quartz 2D: Part 2 2011-10-11

    Graphing with Quartz 2D Creating a Graph With Quartz 2D Creating a Graph With Quartz 2D: Part 2 Creating a Graph With Quartz 2D: Part 3 Creating a Graph With Quartz 2D: Part 4 Creating a Graph With Quartz 2D: Part 5 In the first part of my series Cre

  • Creating a Graph With Quartz 2D: Part 3 2011-10-18

    Graphing with Quartz 2D Creating a Graph With Quartz 2D Creating a Graph With Quartz 2D: Part 2 Creating a Graph With Quartz 2D: Part 3 Creating a Graph With Quartz 2D: Part 4 Creating a Graph With Quartz 2D: Part 5 To create a line graph, I am going

  • Creating a Graph With Quartz 2D: Part 4 2011-10-25

    Graphing with Quartz 2D Creating a Graph With Quartz 2D Creating a Graph With Quartz 2D: Part 2 Creating a Graph With Quartz 2D: Part 3 Creating a Graph With Quartz 2D: Part 4 Creating a Graph With Quartz 2D: Part 5 In this series of articles I am di

  • What are the first steps a tester should perform when using combinational testing? 2012-05-29

    Hypothetically, lets assume that I am testing the "Search and compare flights" functionality of this website*, and I want to apply a combinational testing technique. Where should a tester start this testing process? What should their first steps

  • Software testing: a first step to development? 2012-08-15

    I've been testing Ubuntu daily builds for QA since last month. I wasn't too confident in learning development yet, because I didn't feel familiar with encountering a bunch of code. But I want to write code and develop software one day. So far, I see

  • Getting Started with Fuel CMS, Part 1 2012-12-12

    Getting Started with Fuel CMS Getting Started with Fuel CMS, Part 1 Getting Started with Fuel CMS, Part 2 When you hear the abbreviation CMS, you probably think about Drupal, Joomla, and even WordPress. However, there are alternatives to those heavy

  • First steps into the UX design world 2013-06-17

    I just joined the UX forums and firstly, wanted to say hello - im a newbie. well, actually im actually a motion graphics designer - wanting to make a switch into UX design~ honestly, I have very little web design skills~ so my first question is: woul

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 1.078 (s). 13 q(s)