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 struts_webforum_jars.zip (855 KB)
- Download struts_webforum_src.zip (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 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&r=1">Some Topic</a>
<a href="/webforum/ViewTopic.do?pid=2&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.