Category: java

Guidelines for Struts2 projects – part 1

Struts2 is a very flexible framework. And with so much flexibility, consistency may be at stake.

Lot’s of freedom brings rules to adhere to. As a team.

Here are some of the rules that I found after some team meetings on how to work with Struts2. As the application architect, some guidelines needed to be put on paper.

Rule: do not use interceptors for business related code and logic; interceptors are the Framework

It is very tempting to create lots of interceptors that will gather all kinds of almost always needed data. For instance to always pull the main object for you application from the database and insert it into the current Action. This results in Actions being dependent on a certain interceptor stack, otherwise it is missing business information. This information can be very specific to (one part of) the application. And if more interceptors are needed to process business information, your action cannot considered to be one coherent component.

So consider Interceptors being the Web Framework. In Struts 1 you would know the exact sequence of calls to the Forms and Actions ( validate, execute, …). In Struts2 this sequence can be tweaked by simply changing the interceptor stack. All developers should have a clear view on what the framework is, and not be dependent on specific interceptor stacks to have their Actions work correctly.

Not following this rule will make

  • Action code harder to read and understand, because there are hidden dependencies
  • testing more difficult, because you need the interceptor stack for testing your Action
  • struts2 configuration more complex, because you will probably end up with many different interceptor stacks
  • Think of it this way: interceptors should only deal with infrastructural concerns, such as logging, calling lifecycle methods on the Actions, transforming values from web pages to actions, security, and others. So if you write an interceptor, check if the interceptor can also be used in other applications, and have no dependencies on the business model of the application you are working on.

    Also watch for having too many parameters on interceptors. Sometimes business logic can creep into an interceptor this way. You will notice that for some actions you will need to set a param of the interceptor to false to exclude some logic from running in that particular interceptor stack. Maybe you are better of to include the logic explicitly in the Action, or in some component that the Action can delegate to. This will make the logic in your Action explicit and better to understand.

    More guidelines will follow…

    How thread safe are Struts2 Interceptors?

    Struts2 In a project where we are using struts2 we wanted to create two custom interceptors. One to start a Transaction at the start of the interceptor stack and one to close that Transaction at the end of the interceptor stack. This would cause all (read only) database calls for the prepare method and all the conversion and validation to run in one transaction.

    Instead of heaving two, very similar, interceptors to start and stop transactions, it’s more convenient to have only one with a parameter to switch start and stop mode. But hold on… the Struts2 docs state clearly that interceptors must have no state. Is setting a parameter on an interceptor, that is stored in a member variable not just that: state?

    And if there is only one interceptor, that will surely fall over when used simultaneously in two or more request, each with different parameters to the interceptor. (Remember that you can override interceptor parameters per stack, or even per action, think of the “excludeMethods” parameter of the validate interceptor). This cannot be a design flaw, or what?

    Unable to find an answer quickly in my Struts2 book or with Google, I put Struts2 to the test. For the first time I tried running Eclipse europa (on the MacBook Pro) with the Web Tools Platform and I was pleasantly surprised at its first time ease of use. Just go to the Eclipse update feature and select WTP. And I had installed Tomcat 6 already, so pointing to the installation directory for the server configuration was enough to get started.

    Next, I downloaded the struts2-blank-2.0.11.1.war and imported this into the server configuration. Setting a breakpoint in the example code worked just fine. Just browsed to

    http://localhost:8080/struts2-blank-2.0.11/index.html

    and bingo: Eclipse stopped at the breakpoint.

    Now for the test. First I changed the example.xml to include a new Interceptor:

    
    		
    			
    			
    				
    green
    				
       				
      				
    red
      				
    			
    		
    
            
                /example/HelloWorld.jsp
                
    orange
                
            
    
           
                /example/HelloWorld.jsp
                
    blue
                
            
    

    Next, implementation of the interceptor:

    package example;
    
    import java.util.logging.Logger;
    
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.interceptor.Interceptor;
    
    public class ThreadSafeInterceptor implements Interceptor {
    
    	private static final long serialVersionUID = 1964558869343105305L;
    
    	private Logger log = Logger.getLogger("threadsafe");
    	private String toggle;  
    
    	public void destroy() {
    		log.info("Object: " + this);
    	}
    
    	public void init() {
    		log.info("Object: " + this);
    	}
    
    	public String intercept(ActionInvocation ai) throws Exception {
    		log.entering(this.toString() , "intercept()");
    		log.info("Object: " + this + " toggle before: " + toggle);
    		String result = ai.invoke();
    		log.info("Object: " + this + " toggle after: " + toggle);
    		return result;
    	}
    
    	public String getToggle() {
    		return toggle;
    	}
    
    	public void setToggle(String toggle) {
    		log.info("Object: " + this + " setToggle("+toggle+")");
    		this.toggle = toggle;
    	}
    
    }
    

    If there was only one interceptor, and the parameters would be set to change color, it must show up that the interceptor gets confused while running!

    Here is what the console showed:

    WARNING: Settings: Could not parse struts.locale setting, substituting default VM locale
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor setToggle
    INFO: Object: example.ThreadSafeInterceptor@89c698 setToggle(green)
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor init
    INFO: Object: example.ThreadSafeInterceptor@89c698
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor setToggle
    INFO: Object: example.ThreadSafeInterceptor@4d3241 setToggle(red)
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor init
    INFO: Object: example.ThreadSafeInterceptor@4d3241
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor setToggle
    INFO: Object: example.ThreadSafeInterceptor@e5a19e setToggle(orange)
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor init
    INFO: Object: example.ThreadSafeInterceptor@e5a19e
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor setToggle
    INFO: Object: example.ThreadSafeInterceptor@d5cdab setToggle(blue)
    Apr 22, 2008 10:04:40 PM example.ThreadSafeInterceptor init
    INFO: Object: example.ThreadSafeInterceptor@d5cdab
    Apr 22, 2008 10:04:40 PM com.opensymphony.xwork2.util.ObjectTypeDeterminerFactory 
    

    Ahh… at startup actually three instances are created! One for each interceptor-ref! So each one holds just one set of parameters, one state. Also note that first the toggle parameter is set and then the init is called. So you could potentially use the parameter value in the init method. Hmm, does it make sense to define the private toggle field as final as well, so it cannot change?

    Next in the log, when pointing the browser to

    http://localhost:8080/struts2-blank-2.0.11/example/HelloWorld.action

    :

    Apr 22, 2008 10:07:36 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@e5a19e toggle before: orange
    Apr 22, 2008 10:07:36 PM com.opensymphony.xwork2.validator.ActionValidatorManagerFactory 
    INFO: Detected AnnotationActionValidatorManager, initializing it...
    Apr 22, 2008 10:07:36 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@4d3241 toggle before: red
    Apr 22, 2008 10:07:37 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@4d3241 toggle after: red
    Apr 22, 2008 10:07:37 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@e5a19e toggle after: orange
    

    Orange, red, red, orange… looks good, the green interceptor is hidden from this stack! Note that only the first occurence of the two interceptors in the stack is overridden. Mind this when using the “param-prepare-param” stack with possible parameter overrides for the param interceptor!

    Calling this url:

    http://localhost:8080/struts2-blank-2.0.11/example/HelloWorldBlue.action

    shows:

    Apr 22, 2008 10:08:10 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@d5cdab toggle before: blue
    Apr 22, 2008 10:08:10 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@4d3241 toggle before: red
    Apr 22, 2008 10:08:10 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@4d3241 toggle after: red
    Apr 22, 2008 10:08:10 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@d5cdab toggle after: blue
    

    As expected it uses the blue instance of the ThreadSafeInterceptor.

    Adding two param fields to see if both interceptors can be “replaced” with new ones for one action fails. Using a second black param entry as follows:

           
                /example/HelloWorld.jsp
                
    blue
    black
                
            
    

    shows:

    Apr 22, 2008 10:51:06 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@9d963f toggle before: black
    Apr 22, 2008 10:51:06 PM com.opensymphony.xwork2.validator.ActionValidatorManagerFactory 
    INFO: Detected AnnotationActionValidatorManager, initializing it...
    Apr 22, 2008 10:51:06 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@1b5077 toggle before: red
    Apr 22, 2008 10:51:07 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@1b5077 toggle after: red
    Apr 22, 2008 10:51:07 PM example.ThreadSafeInterceptor intercept
    INFO: Object: example.ThreadSafeInterceptor@9d963f toggle after: black
    

    The blue one does not even get created! Bummer… Well, we might be stretching the framework a bit, but it’s good to know the interceptors are really thread safe. And it brings the question: is it smart to use two of the same interceptors in one stack?

    Time for one more try, lets make a second interceptor entry for the same class with a different name: threadsafe2.

    		
    			
    			
    			
    				
    green
    				
       				
      				
    red
      				
    			
    		
    

    Now we can use:

           
                /example/HelloWorld.jsp
                
    blue
    black
                
            
    

    And this just works! The console writes out: blue, black, black, blue. Great!

    Java and the Client, will they ever be happy?

    In a recent interview (well, that’s a big word, I was asked a question about Java…) I mentioned that there is still a future for Java on the Client. But is there?

    There are so many Rich Internet Application frameworks and solutions nowadays: Flex, Lazlo, Ajax-based, Silverlight, etc… it dazzles the mind. What to pick? Why learn yet another tool, configuration and/or language?

    As a Java developer, would it not be wonderful to do everything in Java. Drop the XML configuration and remoting. No JSPs or inside-out HTML, tags with HTML, Javascript, XHTML, CSS, and what not…

    And I was amazed with the requirements of web applications: master-detail updates, dynamic drop downs, complex grids with excel behaviour, drag and drop, tabs… and all the roundtrips that are needed to get things done. We’ve come a long way now (see Google apps), but I think there is still something to be said for plain old Java GUI’s.

    That was the entry point for a little project that I wrote. I’ve tagged it the “290% Java project” (stole that from the Oracle statement of a couple of years ago: “300% Java…”): Java in the Data layer, the Application Server layer and the Client layer.

    How to accomplish this? Create a Swing or RCP “lite weight” client. Make this available via Java Web Start. Communicate simple POJOs via the Burlap and/or Hessian protocol, using a Servlet in Tomcat Server. Also use those protocols to store the data on disk (no database!). The remote server calls are defined by a clean Java interface. To create a Swing UI use a tool such as JFormDesigner (I hear good things of Matisse nowadays).

    The client app runs both on Windows and the Mac, using Java 5 or 6.

    This app is now being used for almost 2 years in a row, daily, both at home and at the workplace by around 10 people. It is like a bulletin board for a group, that is closed. Everybody in the group can read all messages, but you can specify who the message is intended for. Furthermore, it shows you directly if the message has been read by all that it is intended for (a feature that I did not come acros in email or other bulletin boards), and when it was read.

    It was such a pleasure to create a UI in Java after all the struggles in the Browser world.

    I presented this approach to a group of Java developers. I was surprised to learn that there is fear to start using this “all Java architecture” approach. The reasons being that there skills to program Swing or RCP are hard to find, JSP and JSF programmers are much easier to find. (Is this true?) Also, Swing seems to be considered hard to do and still has a reputation of being slow. Well… look at NetBeans; great job for a Swing ui! I just love the MVC model of it.

    Some other points:

  • Rolling out a new version of the app is as simple as installing a new server side app: just put the news jars on a central site and Java Web Start will automatically get that new version when users open the application.
  • You can make a shortcut from the desktop to a JWS program.
  • You can use the same POJO model for your data on the server and on the client.
  • The model can be effectively cached in the client app. You can make it smart. In my proof of concept there is a version check of the model on the server. If it has not been changed, there is no need to refetch it. If it has changes (e.g. new or updated messages), only send the delta.
  • You can make use of third party jars on the client machine. For instance to generate PDF docs on the fly using iText. This relieves the server of a lot of memory and processor consumption.
  • You can make truely amazing interfaces using Java 2D, Java 3D, jGoodies, and maybe even JavaFX (there is a JavaFX demo on the Hessian RIA page, I discovered recently!)
  • You can use peer-to-peer architectures to communicate via clients directly (a la Azureus :-) )
  • There are some things to be aware of, or “some interesting issues”:

  • How to deal with security and authorisation.
  • How to secure your data over the line. Note that I used https for all communication. It even works behind corporate firewalls!
  • You need to sign all jars to make communication available, or file system access. Not a big deal with a few lines of ant script.
  • You also need to sign with a trusted certificate, so you will not get annoying popups during the app startup. These are quite expensive for a proof of concept (couple of hunderds of Euros). Although you can use a free Thawte personal certificate that is intended for e-mail.
  • There are some caching issues with JWS. Workaround that by putting version numbers in the jnlp filename or url.
  • What about using a very lite weight jump start client, based on Rich Client Platform of eclipse? You would only need Java Web Start for that little client. And then you can use the OSGi plugin model to dynamically load your app (or portal like app!) with the already present upgrade feature in eclipse.
  • All in all, I really like this concept. Who dares to make the jump??? I think it is really suited for intranet apps that have complex GUI requirements, and need to be very responsive…

    Let me know!