Using Nitobi Grid in Struts 2 is a snap. What we need is a server action that can service requests made by the Grid on the client side by returning XML. We can use the Nitobi Server Library to help us do that.
N.B. We'll be using the updated Nitobi Server Library found in the Java Refresh circa May 8th '07.
Writing the Action
In a nutshell, our Action will obtain needed parameters from the request, set up a connection to the database, query the database, and use the returned ResultSet to build a com.nitobi.server.handler.GetHandler object. We use the GetHandler object to output XML back to the Grid (we'll see this in the next step).
The Code
We begin by getting the parameters sent by the Grid from the ActionContext:
Now we set up our connection to the database. This example uses an MS Access database so the following will need to be changed depending on your DBMS.
Next, we prepare the SQL query and execute it to obtain the ResultSet:
Now that we have a ResultSet, we can use the com.nitobi.server.handler.GetHandler classto create an XML document to return to the Grid.
We can populate the GetHandler directly from the ResultSet:
Along with the ResultSet, we also need to pass the name of the field that will uniquely identify each record. The easiest way to do that is to use the primary key of the table (which is ContactID in this case).
Finally, we write out the XML to the HttpServletResponse (which we can get from the ActionContext instance) and close up the connections we've opened:
We return null because we don't need to forward control to a Result for rendering. Instead, we wrote the XML directly to the HttpServletResponse.
Configuring struts.xml
Because we are returning XML directly back to the client from the Action, we don't need to define a Result:
Food For Thought
The Action we defined above obviously has a dependency on HttpServletResponse and that can make it more difficult to test. As an alternative, you can use the Nitobi Struts 2 plugin that defines a custom Nitobi Result type. Have a look at the Struts 2 demo included in the samples directory of your Nitobi Complete UI installation for an example of how to use the plugin.
Knowledgebase
To be notified of new articles when they're available, subscribe to our RSS feed.