Friday, September 26, 2008

The Domain Model and Struts 2.x

A couple of months ago I had a new requirement where I had to display the look (ui) of only a few of my components in my Struts 2.x application. Specifically, I had to display some dates as date-time while others had to remain the same. I started to hold down for a minute and decided to think how best to tackle the problem. I hate to touch a lot of code for no reason and as many know, changing the domain model code is typically not a good idea.

Struts2 MVC and Converters

In the good old days of Struts 1.x, one would have to register a special Converter object and register it so that BeanUtils can use it when ActionForms are populate via the ActionServlet (wao, I can't believe I had to learn all that). This was a good way to provide good conversion across all your application, however this approach forces the Converter to be applied in all objects of the same type.

As an MVC implementation, the controller should be able to have a way to know what conversion process to use in each action mapping processing session. Struts 2.x provides a way to do this in a clean way with the use of the StrutsTypeConverter class. After creating your own converter class, you can register your converter globally (in a file that must be named xwork-conversion.properties). Alternatively, you can create a -conversion.properties file at the same package level where your model object resides and now you can have custom conversion per property. The latter approach is a powerful feature as it allows you to define a properties file with key,value pair listings. Each key represents the name of the java property of the model object and its value is the fully qualified converter class name. This approach for conversion is very appealing for the following reasons:

  1. Does not mix Struts2 code with Domain Object model code (not even annotations), thus offering a non-intrusive approach to the rendering of the object.

  2. It encourages a development environment where this file can be generated, overriden or even replaced at build time. This scenario is very appealing for companies that do customizations of a product thus encouraging a "configuration management" approach in the presentation tier.

  3. It allows you to provide a different converter per property, leaving the model type unchanged.

I was able to successfully display each property as needed and progressively move each component that was required.

Wednesday, September 24, 2008

Powered by Struts 2.x

After working with Struts 2.x for some months now, I feel more comfortable in commenting on some of the features that I feel have been helping me as well as some others that I feel needs some attention. In writing these, I hope that I may be able to learn some from those who may wish to attempt correcting me.

Overall Configuration
The basic file needed is one named "struts.xml". Properties (constants) can be overridden using a struts.properties files. This file takes priority and this is an interesting approach and this seems to mixed well with Maven environments (as well as Ant, of course). You can modularize your application including files of the same type (same DTD) as struts.xml. The one thing I don't understand is the use of DTD over XSD. Not exactly sure why they haven't adopted XSD as the latter are simply more powerful.

Rendering Engine
The fact that you don't need to JSP for your views has been a significant change for me. I know that you can avoid using JSPs using Struts 1.x but the amount of code (and configuration) could be very tedious. With Struts 2.x support for Velocity and Freemarker are already built-in. I've been using the latter for sometime now and I simply love it.

Now, if you consider the "hype" that OSGI is bringing to the JEE world, a templating engine technology (e.g. Velocity, Freemarker) over JSP technology is more appealing as this will allow OSGI environments to resolve proper templates based on the OSGI headers (within each jar). Struts 2.x comes with bundled with a set of predefined templates that the classloader picks from, thus encouraging this pattern (but not demanding it). I see this as a strategic architectural choice which ought to be observed when considering OSGI powered applications.

Servlet Technology and Controllers
Struts 2.x uses Servlet filters (instead of Servlets) as the driving force of the application. This can be good and bad for several reasons. I have found it to be good thus far. Filters can give you the feeling that "intercepting" a controller is simpler (filtering the request). Struts 2.x has default interceptors for different things such as those that parses the parameters and placed them into the value stack, double token submissions, etc. You can always implement your own.

You have a clear option of which interceptors to use and their ordering. This is a powerful feature that if misused can prove a big problem. I recently found a bug on the way I had configured our interceptors. You can do nesting of interceptors so I was repeating the same interceptor multiple times thus doubling my round-trips to the database. Implementing your own is very trivial.

Additionally, Struts 2.x advertise thread-safety POJOs as your actions (Struts 1.x should remember that this issue can make you rely heavily on request/session attributes). I have found that the nature of making this action objects thread-safe are by virtue of having a "request" scope. Since you have an option to use Spring for dependency injection, you configure/annotated your POJOs with scope "session" and block this behavior. I've found this a problem in some cases. I'm still investigating this issue, but does bring something to the table. You can effectively perform IoC in the way Action (controllers) are used as part of your MVC.

IDE Tooling - The good, the bad and the ugly!
As most fairly new frameworks tooling is what helps the adoption of a framework. Struts 2.x lacks this component very much as there are not that many IDEs with out-of-the-box support for Struts 2.x. As of the today, there are few who show some promise, none of which I would recommend investing (yet!). I am a fan of Eclipse, and I have to say that the WTP project works just fine with Struts 2.x and developing with it has been a breeze. Configuring struts 2.x within eclipse is somewhat trivial and I expect IDE plugins to simply help with XML editing.

I have spent a lot of time reading the struts-core source code and I simply like it. I think its a good practice for any developer trying to understand the framework and I'm sure you'll find it very readable, well commented with few problems (although I'm sure there are some). Overall, my experience with Struts 2.x has been very pleasant and I have good reasons to recommend it as a choice for development of new enterprise applications.

Thursday, October 11, 2007

Introduction to Struts 2.x

I finally had the chance to work on a project using Struts 2.x. As I wrote code my code from scratch, I had to admit that my background from Struts 1.x worked against me in some cases where in others it helped understand basic concepts. All in all, I was very pleased with my experience with Struts 2.x. Granted, documentation is still under progress, however I found the email list to be a great tool to be informed and to receive answers to my specific questions. Although I don’t think I can possibly write about every feature I used in Struts 2.x, I can certainly write an introduction for those who are either new to MVC or trying to move from Struts 1.x to Struts 2.x

Reasons to Migrate

First I need to emphasize that unless you strictly have a good reason (and budget) to change your current MVC architecture, then I would recommend to switch to it. The migration is not as trivial and depending on what kind of code in your presentation view (JSP, Velocity, Freemarker, JSTL, etc) your migration may or may not be that transparent. One thing is for sure, Struts 2.x migration is not meant to be a “drop-in” replacement, so expect several gotchas as you move along. Also, note that regardless of your background, Struts 2.x can also be an appropriate MVC choice for a new application (depending on your needs, of course). If your moving from Struts 1.x, know that both can coexist during your migration, so you don’t need to break your existing code, however the process can become very confusing and unless absolutely necessary would I recommend it.

No Struts 1.x is required to start, in my opinion, however decent understanding of MVC (as with most frameworks) is always a plus. You want to also understand EL expressions (and now UEL as well). Understanding of additional concepts such as JEE Filters, Dependency Injection, Servlet Specification are going to help to get you going really fast, however note that if you have done any JSP work before, you’ll learn that with the Value Stack (Struts 2.x), now you have to account for a new “scope”. It’s not hard to understand or use, however one must understand where the values are coming from.

Using Struts 2.x

At a minimum, you are going to need the following jar files within your lib directory. These come as part of the struts2 distribution:

  1. struts-core-xxx.jar
  2. xwork-xxx.jar
  3. ognl-xxx.jar
  4. freemarker-xxx.jar

Of course there are other libraries needed. These are dependencies to the struts 2 framework (e.g. Collections, BeanUtils, Digester, etc). Although these are not part of the Struts2 project, these are reusable components that are part of the Jakarta Commons project. If you are not familiar with it, I highly recommend spending time on them. All required jar files come as part of the distribution. Of course if you are using maven, you don’t need to worry about any of these (maven places all needed dependencies within the lib directory).

Now you need to setup the org.apache.struts2.dispatcher.FilterDispatcher filter in web.xml. This filter should go primarily mapped to all “/*” (web.xml filter mapping). Now to your struts.xml file. This file needs to be in your classpath. Even if you try to put it somewhere else using a context-param in web.xml, other things will break. To be on the safe side, just put it in your WEB-INF/classes directory. As for “struts.xml”, I’m going to let you read some more on it in the official documentation since it’s pretty self explanatory, however a good thing to know is that the concept of “package” inheritance is widely used (similar to the one used in the tiles framework). This hierarchy allows you to have pre-configured elements in your configuration (e.g. validation, interceptors, etc) that are ready for you to use (thus the convention over configuration). You can change, modify, reuse any file. A good practice to learn is to checkout the source code and see how files are read. Warning, the source code uses maven, so unless you are familiar with how maven uses resources, this may be a bit unusual. Looking at the source code has helped me tremendously in picking up Struts 2 fast.

If you come from a Struts 1.x background, you may want to be aware that type conversion is done for you automatically. So there is no need to play around with custom converters (registered in BeanUtils, or custom processing to process conversions), however this conversion may/may not affect the way your validation occurs. This means that errors detected in the conversion process are managed as “fieldErrors” which in turn can be displayed using the appropriate tag. This may/may not be the desired behavior, but it a much better approach to Struts 1.x where strong typing properties in Form objects didn’t work well with certain validator types.

I hope to write very soon a lot more about specifics features within Struts2 as I find them, specially about the migration process which I’m sure it would be a lot more interesting. In the mean time, checkout Struts 2 and start playing with it. According to the goals of the project, you are supposed to be able to write a web application a lot faster (which I tested to be true) as well as to make it coexist with a Struts 1 application (also tested to be true). Have fun!