Category Archives: J2EE

Struts & Java Tips: Issue #1

The “Issue” thing is a joke. I don’t know what else to call this. I’ve been thoroughly enjoying the last couple weeks I’ve been spending with Struts, I learn something new everyday. One of the things that I happened upon today was a tip from Ted Husted buried deep in his overview of Struts design patterns and strategies page (a great resource btw) which suggests using the LabelValueBean as a core value object class:

When a good number of drop-down controls are being used, standardize on the LabelValueBean object provided in the Struts example. This is an easy way to create both the Label and Value collections the Struts options tag expects.

One of the things that I really like about Struts is the strict separation between presentation, business logic and model. I’ll spend a couple hours writing Action classes, some ActionForms, maybe a utility class or two and then switch over to implementing the JSP using JSTL (and very little time working with the model since I’m using Hibernate, but that’s anothe post). I’m never writing directly to the response with the Action classes, the ActionForms, etc… all of the presentation is done using JSP. The JSP’s become so much more simple. The first couple sites I wrote using servlets & JSP were (and for the most part still are) a complete mishmash of JSP’s with embedded SQL, buggy tags, and scriplets. With Struts, for the most part you don’t have to use scriptlets, you’re left with clean template-like code that the Actions provide data for.

So now I’ve come full circle. The LabelValueBean is an example of the data that the Actions provide to the JSP’s and they become a very useful tool when you’ve got to populate month select boxes, year select boxes, state select boxes, etc., etc. This morning I started out by creating a Month bean (which had only label and value properties), a Year bean (with only label and properties) , and so on… a definite trend. I created a factory class that handled the creation of those beans and returned a collection to the Action instance, which then put the collection into a request attribute for retrieval by the JSP. The code looked something like this:

// code in the factory class
public static Collection getYears() {
 Calendar c = Calendar.getInstance();
 Collection years = new ArrayList();
 int year = c.get(Calendar.YEAR);
 int endyear = year + 10;
 for (int i=year; i<endyear; i++) {
  years.add(new Year(String.valueOf(i), String.valueOf(i)));
 }
 return years;
}

// code in the Action class
Collection years = YearFactory.getYears();
request.setAttribute("years", years);

// code in the JSP
<html:select property="payment_year">
<html:options collection="years" property="value" labelProperty="label" />
</html:select>

There are a couple things in the above code that can be improved. First, like I mentioned before, I should have used the LabelValueBean instead of creating my own Year bean. Because the presentation is completely independent of the business logic, I need only change a single line of code (and an import for you sticklers out there). This:

  years.add(new Year(String.valueOf(i), String.valueOf(i)));

becomes this:

  years.add(new LabelValueBean(String.valueOf(i), String.valueOf(i)));

Next (at this point I should probably mention that I’ve been poring over Effective Java while exercising at night), performance savvy programmers probably winced at the number of unnecessary objects (Item #4) I’ll end up creating with the getYears() method. What I should have done instead was create the years collection and collection elements in a static constructor and store the result as a private static, returning the result when the getYears() method is called. So the above example is refactored to this:

private static Collection years = new ArrayList();
 static {
  Calendar c = Calendar.getInstance();
  int year = c.get(Calendar.YEAR);
  int endyear = year + 10;
  for (int i=year; i<endyear; i++) {
   years.add(new LabelValueBean(String.valueOf(i), String.valueOf(i)));
  }
 }
public static Collection getYears() {
 return years;
}

Finally, a small touch that I learned (and am attempting to use faithfully) from Item #34, “Refer to objects by their interfaces.” In the code examples above I could have declared the return type and the private static to be an ArrayList:

// private static declaration
private static ArrayList years = new ArrayList();
// factory method
public static ArrayList getYears() {

Changing the implementation from an ArrayList to a Vector would have required changes to any of the classes that use this factory, which makes my program less flexible. Instead, using the Collection interface, my program becomes easier to use and to modify:

private static Collection years = new ArrayList();
// could also be this with no changes to the public API
private static Collection years = new Vector();

I’m always interested in your feedback! Thanks for listening.

Tomcat Session Replication/Clustering

I’m considering whether or not to use the new session clustering capabilities of Tomcat 5. Unfortunately there isn’t much information out there on the subject. I found a short mention in this “What’s New in Tomcat 5” article on OnJava and a relatively thorough article on the Tomcat site “Clustering/Session Replication How-To“. Is there anyone out that a) has implemented it and can offer some validation that it works as advertised or b) that has more information beyond what is in the above mentioned articles?

I’m specifically interested in opinions on:

a) Beyond the obvious, what are the implications of using the ‘useDirtyFlag’ in server.xml? How much does it affect performance? Which did you decide to use and why? The comments in server.xml provide the best description of the ‘useDirtyFlag’ I’ve seen yet. For those who haven’t peeked:

true means that we only replicate a session after setAttribute,removeAttribute has been called.
false means to replicate the session after each request.
false means that replication would work for the following piece of code:
<%
HashMap map = (HashMap)session.getAttribute(“map”);
map.put(“key”,”value”);
%>

Setting ‘useDirtyFlag’ to false sounds like it would cause a ton of extra work. Setting it to true just means you have to be more intentional when you want to save data to the session. Thoughts?
b) Which persistence mechanism did you choose (PersistenceManager, JDBCManager, SimpleTcpCluster)?

Also, does anyone know if the Tomcat book that Oreilly pushed out in June of last year covers Tomcat 5? The article above seems to imply that it does, but I looked at a hardcopy at Barnes & Noble and that only covers Tomcat 4.x.

JSP Tag Files

I’ve written my fair share of JSP 1.0 tags, the hell of deciding whether to extend TagSupport or extend BodyTagSupport and implement BodyTag, writing tons of StringBuffer append statements left alot to be desired. Almost all of the tags that I wrote wrapped up some piece of presentation logic with a bunch of HTML, which meant alot of header.append(“html content”) type statements. Luckily, it seems that there were other people who had bad experiences with the JSP 1.2 specification (or at least they understood that it needed improvement) which lead to the JSP 2.0 specification. Among other things, JSP 2.0 includes the ability to create JSP tags *using* JSP syntax, which means that front-end/GUI developers that don’t know Java can now easily create reusaeable tags without having to write and compile a Java class. It’s brain dead simple. Create a file in /WEB-INF/tags/ OR /META-INF/tags/ OR create a jar of all your tag files and place them in /WEB-INF/lib/, save it with a .tag or a .tagx extension, enter some content (ie: “Hello World!”) and then you can invoke the tag in a JSP by importing the taglib:

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>

and then the tag itself:

<tags:helloWorld/>

The prefix is determined by the taglib directive (in this case the prefix is ‘tags’) and the name of the tag is determined by the file name of the tag that you saved.

Using attributes is just as easy. At the beginning of the tag file you can add as many attribute directives as you want:

<%@ attribute name="title" %>

and then write their values to the screen:

<strong>${title}</strong>

I’m just scratching the surface though. There are 2 great articles on java.net to get you started if you want to learn more:

Easy Custom Tags with Tag Files, Part 1
Easy Custom Tags with Tag Files, Part 2

You can also read the JSP 2.0 specification (JSR-152).

As an aside, one of the things I always wanted to be able to do with ColdFusion was to deploy the custom tags I wrote as part of the application, in a non web-accessible directory without having modify the custom tag path through ColdFusion administrator. For instance, if you deploy a ColdFusion application to a shared host and you want to use your own custom tags, you have to either store the custom tags in the same directory as the script that you call them from (which does not help much at all), you an use cfmodule, which is a kludge, or you can ask the ISP/host to either add the directory where your tags live to the custom tag path or to put your custom tags into the existing custom tag path, neither of which is an attractive (or secure!) option. I haven’t used ColdFusion for awhile… can you do that now?

JSTL vs. Struts taglib

The last couple weeks have been spent working on a couple different Struts applications, all of which will be deployed on Tomcat 5 with Hibernate. I’m finding that working with Struts is an enjoyable experience, the framework encourages true separation of HTML presentation and business logic and model.

As someone working on all aspects of the application, one of the things I butt my head against pretty freqently are the limitations of the struts HTML & Logic tags. For example, an application that shows a listing of widgets commonly shows each row representing a widget in alternating colors… grey, white, grey, white, etc. The Struts tags, specifically the logic:iterate tag provides no mechanism for determining what the current row number is. There are a number of solutions out there, almost all of them suggest using scriplets to create a simple counter in the loop:

<%
String LIGHT_COLOR = "LightColor";
String currentColor = DARK_COLOR;
int i = 0;
%>
<logic:iterate id="product" name="products">
<%
if ( i % 2 == 0) {
currentColor = "BLACK";
} else {
currentColor = "WHITE";
}
i++;
%>
<tr ALIGN="center" class="<%=currentColor %>">
<td>
  <bean:write name="product" property="label" />
</td>
</tr>
</logic:iterate>

Of course, the entire reason tags are used is so that you don’t have to use scriptlets, so it seems like a pretty ugly hack to me. Fortunately I’m using Tomcat 5, so I stumbled upon the JSTL forEach tag, which provides effectively the same functionality as the Struts iterate tag, with the benefit of an index and row status so that the above code becomes:

<c:forEach var="product" items="${products}" varStatus="status">
  <c:choose>
   <c:when test="${status.index % 2 == 0}">
   <tr ALIGN="center" class="dark">
   </c:when>
   <c:when test="${status.index % 2 != 0}">
   <tr ALIGN="center" class="light">
   </c:when>
  </c:choose>
</c:forEach>

which is a bit more simple, with the main benefit that you don’t have use any Java code.

Further, it seems that there is alot of overlap between JSTL and the Struts tag library, which isn’t a bad thing. I’m guessing that not everyone has the opportunity to use JSTL since it requires a web container that supports JSP 2.0, but for those who are deploying to JSP 2.0 web containers, how much do you use JSTL versus the Struts tags? Are you phasing out Struts tags for JSTL? Keeping with Struts tags to maintain a sort of purity to your application?

C# Public Properties vs. Java getX() and setX()

Martin Fowler blogged about C# properties a couple weeks back saying that he “.. liked the notion of properties right from the start..” because it’s “.. much more natural to write obj.X = other.X.” Further, ” … from a language point of view, properties and fields look the same. So if I have a field x which I can just read and write to, I can just declare it as a field. I don’t worry about this violating encapsulation, because should I wish to do something more fancy I can just replace it with a property later. It all saves a lot of typing of stupid accessor functions.” For those of you who have never used C#, instead of writing this in Java:

// Java getter & setter
private String foo;
public String getFoo() {
  return this.foo;
}
public void setFoo(String foo) {
  this.foo = foo;
}
// access the private variable foo like this:
bar = obj.getFoo();

you can write this:

// C# public property
private String _foo;
public String Foo {
  get {  return _foo; }
  set {  _foo = value; }
}
// access the private variable _foo like this:
bar = obj.Foo;

I initially liked this feature of C# as well, it definitely seems more natural to use properties. Also, like Martin mentions, it saves you from having to make decisions about encapsulation.. do you use a getX()/setX() method or do I just mark it as public? With C#, you can change the implementation without changing your published API.

Martin points out that in this case beauty is only skin deep. If you use reflection to access the public properties or fields of a C# class, you might be surprised to see that the implementation does in fact change. In the example above, the property ‘Foo’ gets turned into 2 methods: get_Foo() and set_Foo(), which you can see using reflection:

Type type = (typeof(YourClassName));
MemberInfo [] members;
members = type.GetMembers(BindingFlags.Public|BindingFlags.Instance);
Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", type);
for (int i =0 ; i
Martin ends by noting "... now I have to write stupid accessor functions for accessible data values." which is something that your IDE can do for you. In Eclipse, declare your private instance variables and then right click --> Source --> Generate Getter & Setter...

Ant WAR Task & WEB-INF in lowercase

If you use the Ant war task to create, well, war files, and you notice that the resulting archive has a lowercase WEB-INF folder, it’s a not a bug with Ant, as the documentation states:

We regulary receive bug reports that this task is creating the WEB-INF directory, and thus it is our fault your webapp doesn’t work. The cause of these complaints lies in WinZip, which turns an all upper-case directory into an all lower case one in a fit of helpfulness. Please check that jar xvf yourwebapp.war shows the same behaviour before filing another report.

Easy fix. Open up WinZip and click Options –> Configuration and then check the option for ‘Allow all upper case file names’.
Winzip Options Menu

Asynchronous Method Invocation in Java

I’m working on a web application that needs to kick off a process that could take anywhere from 5 seconds to an hour, so I need to be able to call a method and have it return immediately. A google search for ‘java asynchronous method‘ didn’t return much, except this, which seems to indicate that simply spawning a new thread within a method will do the job. Basically you end up with something like this:

public class LongProcess implements Runnable {
  public void startProcess() {
    Thread t = new Thread(this);
    t.start();
  }
  
  public void run() {
    // perform the long running process
  }
}

and then you can kick the process off like this:

LongProcess p = new LongProcess();
p.startProcess();

The other solution I thought of would be to use an asychronous xml-rpc call, although this obviously has more overhead.

Are there any solutions I’m missing? What would you do?

Java Object Caching

I was interested in Java caching techniques a couple months ago (almost a year ago in fact) and looked into the various caching libraries available at that time. Srini Penchikala published an article @ OnJava.com this past December that looks in detail at caching with JCS, which is part of the Turbine Jakarta project. The article itself has some valuable insights, but more importantly it turns out that JSR 107 has a variety of implementations now, one of them on sourceforge called jcache, which just released an alpha version.

Struts ActionForm validate() question

I’m trying to setup a simple contact us form that gathers information from a user, checks that the information is valid and then emails the information off to a third party using Struts v1.1, specifically an ActionForm and an Action. In my struts-config.xml, under <action-mappings>, I have this:

<action
  path="/contact/requestinfo"
  type="com.mycompany.actions.RequestInfoAction"
  name="requestInfoForm"
  scope="request"
  validate="true"
  input="/views/requestinfo.jsp">
  <forward name="success" path="/views/requestinfo_confirm.jsp"/>
</action>
    

and then obviously a <form-bean> definition above that. What I expected to happen was that the initial request would be forwared to the page specified by the input attribute, the user would then submit the form, the validate() method would be called on the ActionForm instance, and then if the validate() method return no ActionErrors, the form would be passed on to the Action. What happens instead is that the validate() method is called on the ActionForm before the user even submits the form, which causes the error messages (“First name is a required field.”) to be displayed before they have even submitted the form.

In the short-term, the workaround is to define an action mapping that simply forwards the user to the input page and then a second mapping that has the validate=true attribute set, so the page flow looks like this:

/contact/requestinfo –> display form –> submit form –> /contact/requestinfoform –> validate() –> if no errors, then servlet forwards to the Action

Is there a way to have to validate() method not called on the intial load of the page? Any thoughts?

Hibernate Code Generation

Justin left a comment about various tools for generating Java code from XML. Last week while I was reading about Hibernate I was interested to read that the same files you use to persist POJO’s to a database using Hibernate can be used to create the Java objects as well. It’s reasonably well documented on the hibernate site, but doesn’t include all the classes you need on the classpath, so here’s an example from my system:

java -cp C:\hibernate\hibernate-2.1\hibernate2.jar;
C:\hibernate\hibernate-extensions-2.1\tools\hibernate-tools.jar;
C:\hibernate\hibernate-2.1\lib\commons-collections.jar;
C:\hibernate\hibernate-2.1\lib\commons-logging.jar;
C:\hibernate\hibernate-extensions-2.1\tools\lib\jdom.jar net.sf.hibernate.tool.hbm2java.CodeGenerator Resource.hbm.xml

where Resource.hbm.xml looks likes this:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
 PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="com.mycompany" auto-import="false">
 <class name="Resource" table="resource">
  <id name="id" type="int" unsaved-value="0" >
    <column name="id" sql-type="int" not-null="true"/>
    <generator class="identity" />
   </id>
   <property name="label" type="string" />
   <property name="filename" type="string" />
   <property name="teaser" type="string" />
   <property name="type" type="string" />
   <property name="url" type="string" />
   <property name="datetimecreated" type="date" />
   <property name="datetimemodified" type="date" />
   <property name="createdby" type="string" />
   <property name="modifiedby" type="string" />
   <property name="active" type="integer" />
   <property name="archive" type="integer" />
 </class>
</hibernate-mapping>

This will automatically create a JavaBean, with full and empty constructors, getters and setters for all the fields, a toString() method, an equals() method, and a hashCode() method. Additionally, you can use an external configuration file to add an interface that the bean implements, change the rendering mechanism, the package, etc.

Cooler still, you can go backwards and create Hibernate mapping files directly from your existing compiled classes using the net.sf.hibernate.tool.class2hbm.MapGenerator.