Struts 2 and JQGrid – An alternative to other visually rich web applications

Happy New Year to one and all. My first blog for the New Year.  Struts 2 and JQGrid offer an elegant alternative to changing languages or trying other frameworks that involve other languages. Imagine if you have inherited an application that was written in Java and used maybe Struts 2? Even if it didn’t involve Struts, migrating an existing project in Java to Struts 2 is easier than migrating an existing application to another language. We can reuse the expertise of the seasoned developers that are already present in team. Why re-train?

JQGrid offers a comprehensive toolset that leverages the power of Ajax and lends this power to Struts 2 via the Struts 2 JQGrid. Visit I admit this is rapidly evolving package that we don’t hear much of but can be useful.

it is now an accepted fact that JavaScript plays an important part in web applications it allows us to create rich applications that have attractive visual effects. This is the power JQGrid lends to especially Java developers that don’t want to move much out of their Java realm.

In my next blog I plan to build an application that will illustrate the various features of the JQGrid toolset. Indeed we will explore some of the lesser known concepts that add amazing features to filtering, sorting and searching tabular data.

Yes there are other languages other frameworks but if your team is skilled in Java wouldn’t it be wise to invest in enhancing the skills and utilizing the existing abilities than to retrain in completely new languages.

Then of course there is the “rapid part” and learning curve. If the extra features of the JQGrid require a greater learning curve than learning another framework from scratch then this might not be the best. My perspective is that the learning curve for JQGrid is actually very gentle. However the last word lies with the team.

A Struts 2 JQgrid application can be setup in such a way that the code will have alot of reuseable components. Making dealing with tabular data throughout the application easier and seems to be faster than the new code generators out there for web applications.

Lastly in the application i present in my next blog, I will add an important part that is not by default offered in the JQGrid plugin, this is creating reports. I use an interesting yet powerful alternative for this.

With these thoughts in mind I take my leave until next time.

Posted in Uncategorized | 1 Comment

Picking Dates in Struts 2 and JQGrid

I have spent sometime analysing the power of Struts 2 and JQGrid. In a time when so many frameworks are out there, so many projects, some of which perform code generation, the question is can Struts 2 still have a place in the new world, the new era that has seen the rise of web technologies with mouth watering graphics and tantalizing visual effects?

I am happy to say that yes it can. Within the JQGrid Struts 2 is a framework that has the capability to make it through and past 2010 into the second decade of this new century that has dawned upon us.

Today I write about dates and date picking in the Struts 2 JQGrid plugin. The reason being there seems to be, to my knowledge, no clear explanation on this. In my next post I will give a full tutorial on the use of JQGrid and more comprehensive coverage on this wonderful plugin.

We want to be able to have a date picker in the Add Record screen. In the picture below confirmBy is a date field and when we click on it:

Also when we edit a record, on the Edit Record screen, we click on the date field we have:

The settings for this are as follows. First in the sjg:GridColumn we have:

Where the datePick function will be:

There we are. We have added date picking functionality in the Add Record screen and the Edit Record screen.


Posted in Computers and Internet, Java programming, JavaScript, Uncategorized | Leave a comment

Spring ROO and an Idea

 I have being playing around with Spring ROO. It is a project with great potential and the facility to integrate seamlessly with maven is an added advantage.

There are many tutorials on “An enterprise Java Application in 10 minutes with ROO”, this is not a tutorial but rather looks at enhancing ROO for use in projects The reader who is unfamiliar with Spring ROO is advised to look at . for an introduction to Spring ROO.

How one draw back that seems to plague Spring ROO is the lack of sorting and filtering functionality on the web frontend lists. In other words how do we sort tabular data? This question  is obviously an important one and vital to many web applications.

An answer that we could employ is displaytag a little known but help tag library that could assist us to sort and export tabular data to excel and csv files.

In the generated list.jspx we have:


If we had to use display tag instead we would have :

Now we could actually make changes to the code generation and the annotations to alter and create our default JSPs to use the display tag. However for this exercise we can assume that we did it by hand and produced the above.

The result when running the application with mvn tomcat:run we have in our browser( ):

We can even extend the above to use displaytags exporting abilities to export to excel:

Posted in Uncategorized | 4 Comments

Digesting Struts 2 and Dojo

Digesting Struts 2 and Dojo

I was playing around with Struts 2 and Ajax mainly Dojo. Now how would one wire a struts action to return Dojo – JavaScript object? We will examine this below and setup a sample app that will use Struts and Dojo. We offer this as an alternative to JSON. The advantage of this over JSON is that an exist Struts 2 application could still generate JavaScript Objects without interfering with the Java classes. So where as when JSON is used your program must return a JSON object here your program can return normal data to pages and from these JavaScript objects can be constructed and used.

We will load a user’s information on selection of the user and dynamically append the user’s details.


Once the user is selected we will have his information dynamically appended to the screen as below:


The way this application will function is that struts will on success return a result to a JSP that will then dynamically have the XML created. The will then read in this XML and generate a JavaScript object with which we can use to update the page. We will start by creating the project for the application in Eclipse (Similar process for Netbeans)


The classes look like:

package struts2dojoexample.action;




import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;


import struts2dojoexample.pojo.User;


import com.opensymphony.xwork2.ActionSupport;


public class LoadUserAction extends ActionSupport implements ServletRequestAware,

ServletResponseAware {


private String user;

private String username;

private String password;

private HttpServletRequest request;

private HttpServletResponse response;


public String execute() {

User user1 = new User();




user1.setStreetAddress(“On Earth”);


// Put the DTO in request so we can use it to render XML in the JSP.

getServletRequest().setAttribute(“user”, user1);

return SUCCESS;



public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setUser(String user) {

this.user = user;



public String getUser() {

return user;




public void setServletRequest(HttpServletRequest request){

this.request = request;



public HttpServletRequest getServletRequest(){

return request;



public void setServletResponse(HttpServletResponse response){

this.response = response;



public HttpServletResponse getServletResponse(){

return response;






As you can see in Struts 2 you can implement ServletRequestAware and ServletResponseAware

When these are implemented we now have access to our session.

package struts2dojoexample.pojo;


import java.lang.reflect.Field;


public class User {


private String username;

private String password;

private String surname;

private String emailAddress;

private String streetAddress;


public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setSurname(String surname) {

this.surname = surname;



public String getSurname() {

return surname;



public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;



public String getEmailAddress() {

return emailAddress;



public void setStreetAddress(String streetAddress) {

this.streetAddress = streetAddress;



public String getStreetAddress() {

return streetAddress;



public String getAsXML(){

StringBuffer sb = new StringBuffer(512);

sb.append(“<user username=\”” + username + “\” “);

sb.append(“surname=\”” + surname + “\” “);

sb.append(“emailAddress=\”” + emailAddress + “\” “);

sb.append(“streetAddress=\”” + streetAddress + “\”>\n”);


return sb.toString();



* Overriden toString method.


* @return A reflexivelybuilt string representation of this bean.


public String toString() {


String str = null;

StringBuffer sb = new StringBuffer(1000);

sb.append(“[“ + super.toString() + “]={“);

boolean firstPropertyDisplayed = false;

try {

Field[] fields = this.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (firstPropertyDisplayed) {

sb.append(“, “);

} else {

firstPropertyDisplayed = true;


sb.append(fields[i].getName() + “=” + fields[i].get(this));



str = sb.toString().trim();

} catch (IllegalAccessException iae) {



return str;


} // End toString().



Next we have the web.xml:





<?xml version=“1.0” encoding=“UTF-8”?>


<web-app version=“2.4” xmlns=; xmlns:xsi=; xsi:schemaLocation=;>















<!– Session timeout config. –>





<!– Welcome file config. –>






The struts.xml

<?xml version=“1.0” encoding=“UTF-8” ?>


“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”;>




<constant name=“struts.devMode” value=“true” />


<package name=“default” namespace=“/” extends=“struts-default”>

<action name=“LoadUserAction” class=“struts2dojoexample.action.LoadUserAction”>

<result name=“success”>/User.jsp</result>





The javascript files are list below:


We have the ControlEvents.js this is where we control the events the user creates like the select list drop down menu.

Dojo.js is the dojo toolkit downloadable from

User.js is the script file container the user object in JavaScript. In the ControlEvents.js we use the JSDigester that is provided by the JavaWebparts tags. This enables us to generated JavaScript objects.

ControlEvents.js looks like this:


var user = null;

var aconsole = null;

// This function is called when the User dropdown selection changes.

function loadUser() {

// If an operation is in progress, usually involving the server, don’t do it.

//if (processing) { return false; }

// Get name of selected collection.

var username =document.getElementById(“userslist”).value;

// Ignore the first item, our “dummy” collection.

if (username == “none”) {

return false;


// Make AJAX call.{

url: “LoadUserAction.action”,

content: {user: username},

error: function(type, errObj) { alert(“Error”); },

load: function(type, data, evt) {

// Now that we have received back the XML describing the collection,

// we’ll use JSDigester to parse it.

var jsDigester = new JSDigester();

jsDigester.addObjectCreate(“user”, “User”);


user = jsDigester.parse(data);


if (aconsole != null ) {

removeAllChildren ( aconsole );


var div = document.createElement(“p”);

var txt=document.createTextNode(“Name: “ +user.username );

div.appendChild ( txt );

txt=document.createTextNode(“Surname: “ +user.surname );

var div1 = document.createElement(“p”);

div1.appendChild ( txt );

txt=document.createTextNode(“Email Address: “ +user.emailAddress );

var div2 = document.createElement(“p”);

div2.appendChild ( txt );

txt=document.createTextNode(“Street Address: “ +user.streetAddress );

var div3 = document.createElement(“p”);

div3.appendChild ( txt );






mimetype: “text/plain”,

transport: “XMLHTTPTransport”




function removeAllChildren( node ){

var childCount = node.childNodes.length;

for ( var count = 1; count <= childCount; count++) {

node.removeChild ( node.childNodes[0] );




User.js :

// User object.

function User() {

this.username = null;

this.surname = null;

this.emailAddress = null;

this.streetAddress = null;


User.prototype.setUsername = function(inName) {

this.username = inName;


User.prototype.getUsername = function() {

return this.username;


User.prototype.setSurname = function(inSurname) {

this.surname = inSurname;


User.prototype.getSurname = function() {

return this.surname;


User.prototype.setEmailAddress = function(inEmailAddress) {

this.emailAddress = inEmailAddress;


User.prototype.getEmailAddress = function() {

return this.emailAddress;


User.prototype.setStreetAddress = function(inStreetAddress) {

this.streetAddress = inStreetAddress;


User.prototype.getStreetAddress = function() {

return this.streetAddress;


User.prototype.toString = function() {

return “User=[username=” + this.username +

“,surname=” + this.surname +

“,emailAddress=” + this.emailAddress + “,streetAddress=” + this.streetAddress + “]”;



The libraries:



There some additional libraries for expansion of this application like the MySQL driver for Database connectivity to MySQL.

There you are it runs. So we managed to dynamically update a page and translate our Java in to JavaScript. This example could be extended and enhanced to embrace the vast functionality of the Dojo Toolkit.








Posted in Computers and Internet, Java programming, JavaScript | Leave a comment

Hello world!

Welcome to This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | 1 Comment

Dating, Where clauses and Hibernate

I recently ran into an interesting problem involving hibernate and dates across different database systems mainly Microsoft SQL 2008 and IBM Informix.

It appears that in HQL queries you can use Informix’s today for obtaining the current date and time:

query = session.createQuery();

String whereClause = "from myTable where myDateColumn > today -10";

This query finds the today 10 days from the current time.

When we run the query as below:

List<MyTable> myTableResults = query.list();

THis executes successfully in IBM Informix but in MSSQL we get the following error:

column today not found

So what do we do now? it appears that NOW() does not work.

Looking through various information and issues on the internet and hibernate tutorial and forums I found that hibernate can support certain functions of a specific database. This ties in with the hibernate dialect and JDBC driver.

I found that GETDATE() works within the where clause. So updating the above to:

String whereClause = "from myTable where myDateColumn > GETDATE() -10";

This worked well. So this raises more questions. How can we in general see which functions the RDMS provides that hibernate will support in its HQL queries – the where clause?

It should be noted that in the select part of the query we have more freedom. As dates can be retrieved.

Also it should be noticed that MS SQL has a newer driver sqljdbc4.jar and sqljdbc.jar. The difference in these two is quite big when we consider dates. For example SQL 2005 had fewer date types then SQl 2008. So this leads to problems when using the older driver(sqljdbc.jar) on SQL 2008.


Another important insight is in the Dialect class there exists the method Dialect.getCurrentTimestampSQLFunctionName() which can give us the database-specific SQL function for retrieving the current timestamp.

Also we cannot use Java’s

new Date() in the where clause part of the query as this does not always work. The format the date will be in might not translate well into a string. We could try parameters in queries using AbstractQueryImpl.setParameter(String name, Object val).

However a problem could arise when using Java’s new Date() in as a paramter in a query as opposed to using a database function, this problem would be that time from Java would be based on the application as opposed to the database server itself. So if the two are at different locations and setup differently we could have problems.

Hence we can make our application cater for different types of RDMS systems based on the type and hence use various functions to aid development.

Hence when dealing with date types one has to be cautious specially if developing on an open source RDMS and then using a commerial RDMS. This saves on licencing but when deploy issues like dates can give problems!

Posted in Computers and Internet | Leave a comment

Nice and Naughty Transactions in Hibernate and Spring

I came across a very interesting fact about Spring transaction management.


Spring provides us with two ways of handling transaction

1) Using proxies,

2) Using DI through the getTemplate() method.


Now what happens when we consider 1) we mean:

Declaring in an XML file the transactionManager and transactionTemplate bean:


<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" singleton="true">

            <property name="sessionFactory">

                  <ref bean="sessionFactory" />



      <bean id="transactionTemplate" class="" singleton="false">

            <property name="transactionManager">

                  <ref bean="transactionManager" />




Then we use proxies and provide:


<bean id="myTableManagerTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" singleton="true" lazy-init="true">

            <property name="transactionManager">

                  <ref bean="transactionManager"/>


            <property name="target">

                  <ref bean="myTableManagerImpl"/>


            <property name="transactionAttributes">





            <prop key=" *">PROPAGATION_NOT_SUPPORTED,readOnly</prop>




            <property name="preInterceptors">


                        <ref bean="callMonitor"/>





With the use of interceptors we can now use doInHibernate() and have transaction support without any extra coding:


protected Object updateObject(final Context ctx, final Object o) {

            return getHibernateTemplate().execute(new HibernateCallback() {


                  public Object doInHibernate(Session session) throws HibernateException, SQLException {

                        return update(ctx, session, o);





However we can use alternative 2)


            try {

                  TransactionTemplate transactionTemplate = SpringFactory.getTransactionTemplate( TransactionDefinition.ISOLATION_READ_COMMITTED, TransactionDefinition.PROPAGATION_REQUIRED, false );

                  return ( List )transactionTemplate.execute( new TransactionCallback() {


                        public Object doInTransaction( TransactionStatus transactionStatus ) {

                              return getMyTableDAO().find( ctx, myId );


                  } );

            } catch( Exception e ) {

                  log.error( e.getMessage(), e );                



Here we are programmatically creating a transaction based on Spring’s DI.


What happens if we use both together? That is 1) and 2) in an application we could have errors like:


Session cannot be closed!


This is because we are using proxies for transactions and also programmatically controlling transactions. If our TransactionDefinition fields : PROPAGATION_REQUIRED, PROPAGATION_NEVER, PROPAGATION_NOT_SUPPORTED, PROPAGATION_REQUIRES_NEW etc are not adjusted and used correctly we could have problems and errors with sessions being closed prematurely and incorrectly controlled. Also the HibernateTemplate controls the sessions for us. As stated in the Spring documentation:

The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

 This can lead to sessions not being closed properly and resources not been freed and hence lead to memory leaks(Which I have experienced!).


Final word of advice is: carefully watch your transactions!


Posted in Computers and Internet | Leave a comment