Open Source Software Technical Articles

Want the Best of the Wazi Blogs Delivered Directly to your Inbox?

Subscribe to Wazi by Email

Your email:

Connect with Us!

Current Articles | RSS Feed RSS Feed

Tags take Struts beyond the basics

  
  
  

Struts, a web application framework, helps developers get Java web apps up and running using a Model-View-Controller architecture that helps keep apps clear, straightforward, and easy to maintain. It's easy to get started with Struts on Tomcat, but once you're there, what are some neat things Struts can do? The vital component for making the most of Struts is its tag system.

Struts tags let you control page output, interact with data, present information to users, and get information back from them. There are two types of Struts tags: generic tags, which control page flow and interact with data, and UI tags, which cover user interaction. This article focuses on generic tags; later this week we'll look at UI tags. I'll assume that, as in our getting started article, you're serving your Struts apps via Tomcat; if not, change the deployment details to fit your setup.

Control Tags

Tags are little snippets of markup that allow you to easily embed Struts instructions into your HTML or JSP pages. With generic tags, the instructions control the flow of page execution and rendering, and also handle data extraction, creation, and manipulation. Here are a couple of examples of how to use control tags.

An If/Else If/Else control structure is often useful when you're setting up a web app; you want to be able to show different things to users depending on what values are set. The code below displays a different text string depending on the value of the myDecade variable.

Store this if.jsp file in $CATALINA_HOME/webapps/mystruts:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
</head>
 
<body>
<h1>If, Else, and ElseIf tags</h1>
 
<s:set name="myDecade" value="decade"/>
 
<s:if test="%{#myDecade=='1990'}">
    Child of the 1990s.
    Value is: <s:property value="decade" />
</s:if>
<s:elseif test="%{#myDecade=='2000'}">
    You Millennial, you.
    Value is: <s:property value="decade" />
</s:elseif>
<s:else>
    Bang up to the minute?
    Value is: <s:property value="decade" />
</s:else>
 
</body>
</html>

Right at the top of the JSP file we set up the location of the Struts tags with the taglib line, and state that any Struts tags will be preceded (for identification) with s.

As we do here, you'll find yourself using the set and property tags frequently along with other generic or UI tags. Here we set a variable named myDecade, and automatically call the getDecade() of the associated Action class to obtain its value. If the tag instead had value="foo", then it would be set to the value returned by getFoo().

We then use the if tag to test the value of myDecade. The if tag has a single parameter: test, which determines if the body of the tag is to be displayed. In Struts 2, the %{foo} notation is a marker that the content inside the brackets (foo) should be evaluated as an OGNL statement, not as a string. Here, that statement is #myDecade=='1990', which compares the myDecade object with the value "1990." If this returns true (i.e. if they match), the body of the if tag is shown. Otherwise, we move onto the elseif tag, which works in exactly the same way. If that too returns false then we fall through to the else tag, which has no test and so will be true automatically if reached.

Next, we need to set up the associated Action class, WEB-INF/src/example/IfDecade.java, which is a simple class with only one variable and its getter/setter methods. The decade value is hard-coded here to show you how this works; in real life you'd likely get it from the user, and I'll show you how to do that in next article in this series. Here's IfDecade.java:

package example;

import com.opensymphony.xwork2.ActionSupport;
  public class IfDecade extends ActionSupport {
  private String decade = "1990";

  public String execute() {
    return SUCCESS;
  }
  public String getDecade() {
    return decade;
  }
  public void setDecade(String decade) {
    this.decade = decade;
  }
}

Finally, WEB-INF/classes/struts.xml links the above files:

<struts>
  <package name="default" extends="struts-default">
    <action name="ifDecadeAction" class="example.IfDecade" >
        <result name="success">/if.jsp</result>
    </action>
  </package>

</struts>

To compile this, type:

cd WEB-INF 
javac -cp lib/xwork-core-2.3.4.1.jar -d classes src/example/IfDecade.java

Restart Tomcat, and look at http://localhost:8080/mystruts/ifDecadeAction.action to see the if/elseif/else code in action:

 ifelse resized 600

Iterator tags

The iterator tag is another useful one for data control. It allows you to iterate over a list or collection of values, and to output different values based on your current value. To try it out, add this Java file at WEB_INF/src/example/IteratorDecade.java; this creates a list and its getter and setter methods:

package example;

import com.opensymphony.xwork2.ActionSupport; import java.util.ArrayList; import java.util.List;
    public class IteratorDecade extends ActionSupport {
  private List decades;

  public String execute() {
    decades = new ArrayList();
    decades.add("1950s");
    decades.add("1960s");
    decades.add("1970s");
    decades.add("1980s");
    decades.add("1990s");
    decades.add("2000s");
    decades.add("2010s");
    return SUCCESS;
  }
  
  public List getDecades() {
    return decades;
  }
  
  public void setDecades(List decades) {
    this.decades = decades;
  }
}

Now create iterator.jsp to control the display:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
</head>
 
<body>
<h1>Iterators</h1>
 
<ul>
<s:iterator value="decades">
  <li><s:property /></li>
</s:iterator>
</ul>

<ol>
<s:iterator value="decades" status="decadesStatus">
  <s:if test="#decadesStatus.last == true">
    <li><s:property /> (no more decades yet after this!) </li>
  </s:if>
  <s:else>
    <li><s:property /> </li>
  </s:else>
</s:iterator> 
</ol>
 
</body>
</html>

Unlike our if/elseif/else example, this time we don't need to set the value first. Instead, we set it directly in the iterator tag, where value="decades" generates an iterator over the list returned by getDecades() in the associated class. As before, if the iterator had value="foo", it would use the List returned by getFoo(). There are two examples here. In the first iterator example, while the iterator still has values to return, each one is output by the property tag. This simply refers to the most recent value on the stack, which here is the most recent value returned by the iterator.

The second iterator example adds a status value. This creates an IteratorStatus object, which can then be used to test various properties. Here, the last() method of the IteratorStatus object is used to output something different if we're on the last member of the iterator. Other available IteratorStatus methods include first(), odd(), and even().

To link the two files, add these three lines in struts.xml:

<action name="iteratorDecadeAction" class="example.IteratorDecade" >
  <result name="success">/iterator.jsp</result>
</action>

Compile as above, restart Tomcat, and go to http://localhost:8080/mystruts/iteratorDecadeAction to see it working:

iterator resized 600

Other generic control tags are shown on the Struts tag reference page. They include other ways of merging, comparing, and working with lists, but they all work in a similar way to the two examples we've seen.

Data tags

The other type of generic tags are ones that work with data. One such tag is the URL tag. At its simplest, it looks like this:

<a href="<s:url value="http://www.google.com"  />" target="_blank">Google</a> 

This creates a URL pointing at http://www.google.com. In this case, there's obviously not much value over hard-coding this, but URL tags can also be used for Struts actions, can be set as variables, and can be parametized. For example, you could try adding this line to the if.jsp file you created in the earlier section:

<s:url action="ifDecadeAction.action" var="ifUrlTag" >
    <s:param name="decade">2000</s:param>
</s:url>
<a href="<s:property value="#ifUrlTag" />" >Setting decade (via property)</a> 

Reload the page with http://localhost:8080/mystruts/ifDecadeAction.action and click the "Setting decade" link. You'll see the page reload with the decade set to 2000. (A more sophisticated option would be to use a dropdown menu or similar tool to choose the decade; we'll look at form controls in the second part of this article series.)

Here, the URL is set up in advance, with an action, a variable name (ifUrlTag), and a parameter passed in. More on parameters in a moment, but this creates a URL /mystruts/ifDecadeAction.action?decade=2000. This is constructed from the root context (/mystruts/), the action value (ifDecadeAction.action; ifDecadeAction would also do the same thing), and the decade value. So clicking on this passes decade=2000 to IfDecade.setDecade(), and oututs the result via the if.jsp page, as set above in struts.xml.

We've already discussed the set and property tags. To avoid confusion, remember that set is used to set a particular value only within the JSP; it doesn't call any setFoo() method in the action class.

Finally, you may find the param tag useful. It parametizes other tags, so you can use it within other tags to provide a particular value. In one of the examples above, we had:

<s:url action="ifDecadeAction.action" var="ifUrlTag" >
    <s:param name="decade">2000</s:param>
</s:url>

Here, param passes the decade=2000 parameter into the URL set up by the url tag. You could achieve the same thing with:

<s:url action="ifDecadeAction.action" var="ifUrlTag" >
    <s:param name="decade" value="2000"></s:param>
</s:url>

The two ways of using the tag are exactly equivalent.

More data tags: bean instantiates a JavaBean class, i18n allows you to access multiple resource bundles, and text renders an I18n resource message. You can also use the push tag to change what's on the top of the stack, to make it quicker to access a particular bean or value. For more tags and more details, see the Struts Generic Tag Reference page. For more on UI tags, watch this space for the second part of this two-part series.




This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.

Comments

Fastrack designer watches panerai replica include the common company via Titan. These are your prefered by designer watches involving kids whom enjoy cool patterns along with exclusive variations. Your acceptance pertaining to Fastrack designer watches one of several junior is caused by their various design and style habits along with cool variations. Your patterns echo your thinking process involving junior. Fastrack replica rolex uk for ladies can be bought in essentially the most interesting habits along with patterns. These are quite popular while using most up-to-date capabilities along with technological innovation plus accessible in most price tags via lowest for you to greatest charge. Fastrack designer watches for ladies are essential just as one addition corresponding hublot replica using costume along with perspective. Your displaying attribute involving Fastrack designer watches are generally his or her joining together good quality. They have got a real mix along with go with center. Designer watches pertaining to guys are generally dashing along with designer watches for ladies are generally lovely using fine along with complicated patterns. Fastrack swiss replica rolex designer watches for ladies are generally suitable for different types involving instances unique a party or possibly a laid-back pay a visit to, these kind of suits to the situation. Natural leather series and also series throughout plastic-type material along with material can be bought in Fastrack designer watches. They have got presented a number of particular string watches replica involving fashion clever series including internet marketer fashion along with campus fashion designer watches. While you would imagine involving high-class, make certain that your This particular language inspiredArticle Look for, Cartier company can be presents itself your current small listing. 
Posted @ Tuesday, September 02, 2014 11:28 PM by sdbacx
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics