| More
All posts tagged 'spring'
 


Spring 3.0 and Formatting Annotations

By Jim White (Intertech Director of Training and Instructor)

Have you started to explore Spring 3!  It came out at the end of 2009 (December to be exact).  You can check out one of the easier features - formatting annotations - to add to your applications through an article I wrote for Developer.com.  It was just published to day:  http://www.developer.com/features/article.php/3879471/Spring-Framework-30-and-Annotation-driven-Formatting.htm.

Leave me comments or send me an eval on what you think and what other features of Spring 3.0 you'd like to learn/hear about.


Posted by: Jim White
Posted on: 4/30/2010 at 5:42 PM
Tags: , , ,
Categories: Java
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Spring MVC Command Beans - As Complex As You Need

By Jim White (Intertech Instructor and Director of Training)

It was Spring Framework training again this past week.  How fitting as it was also the first official week of spring and as pro-baseball's Spring Training was wrapping up.

This week, I had two students in my class that are getting ready to develop a new web application for their company.  This web application is going to be built with Spring and Spring MVC.  They have been given a prior web application as a project "template."  So this week's class gave them a great opportunity to learn Spring, and to figure out how to design and build their application around some of the features they have seen in the existing template project.  I love having students in class that have a very concrete purpose for learning the material.  I found these students are eager to learn, and they like challenging me with interesting problems that they want to apply in their applications.  It provides me the opportunity to do what I call "micro-consulting."  In the span of a class, I can't create an entire application, but I can sometimes help solve particular challenges students have.

One of the complex Spring MVC user interfaces my students, Mark and Senthil, know they will have to address deals with showing multiple records in an HTML table and allowing users to randomly edit the data in the table.  A checked checkbox at the front of each row is an indication, on the part of the user, that they have modified something in that row and want the new data provided in that row stored in the database.  A checkbox left unchecked means that the data in that row, regardless of any changes, to be left unsaved.  For demonstration purposes, I have shown a mock up of this kind of UI below for "customer contact" data.  As the contact data is brought up in the edit page, you can change all the data in each row and each field, but unless you also check the checkbox to the left (arrow identifying below), then no update of that row is made in the database.

image

Now, you can argue the merits of this user interface (I like to call it "table-o-data") all you would like.  However, as a practical matter, we all know that the companies we work with design and evolve user interfaces that the business has become comfortable with or find to be productive.  The question put forth to me was can a Spring MVC controller/command bean design be set up to accommodate such a UI?  The answer is absolutely yes!

Spring's MVC components are quite flexible to address all sorts of imaginable UIs.  The Command bean itself is really just the name we give to the set of objects that harvest and provide data from/to the view (which is usually in the form of HTML).

A More Complex Command Bean

          Note:  Code for this example is provided at the link at the bottom of this blog post.

So let's explore how a more complex command bean can be devised to deal with Mark and Senthil's "table-o-data" UI.  In this case, each row represents a single customer contact.  So, at first we build a simple Contact POJO.

public class Contact {
    private Long id = 0L;
    private String firstName;
    private String lastName;
    private Date dateOfBirth = new Date();
    private boolean married = false;
    private int children;
    private boolean updating = false;
    //getters, setters, constructors left off for brevity
}

The updating boolean property will hold the true/false checkbox indication that the Contact data should be updated/saved in the database.

Most Spring MVC references and books use a simple POJO like this one as the command bean behind a view that allows a user to edit a single instance of a contact.  However, in this case, a collection of these Contact beans must be in place to allow multiple rows to be edited.  To accomplish this task, we need another, more complex, "command bean."  Below is the code for a ContactList that servers as our command bean.  Notice that the ContactList wraps a list of Contact objects from above.

public class ContactList {
    private List<Contact> contacts;
    //getters and setters removed for brevity
}

Command beans do not have to be simple objects with no relationship to other objects.  Command beans can have relationships with other object, can be collections of objects, or even a map of data values (see http://forum.springsource.org/showthread.php?t=18687 for an example of a HashMap of data values captured from a UI).

The JSP - Using Spring Form Tags, JSTL with the Command Bean

The trick of using a more complex command bean is finding out how to access and reference it's properties, associated objects, etc. through the form tags in your JSP.  Spring MVC form tags allow you to use dot notation to access properties containing other objects.  You can also use square brackets [ ] to navigate around collections like our list above.  Here is the form portion of the editcontacts.jsp that displays the many customer contacts in the "table-o-data" example shown above.

<form:form action="editcontacts.request" method="post" commandName="contactList">
    <table border="1">
        <tr>
            <th>&nbsp;</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Date of birth</th>
            <th>Married</th>
            <th>Children</th>
        </tr>
        <c:forEach items="${contactList.contacts}" var="contact" varStatus="x">
            <tr>
                <td><form:checkbox path="contacts[${x.index}].updating" value="true"/></td>
                <td><form:input path="contacts[${x.index}].firstName"/></td>
                <td><form:input path="contacts[${x.index}].lastName"/></td>
                <td><form:input path="contacts[${x.index}].dateOfBirth"/></td>
                <td><form:checkbox path="contacts[${x.index}].married" value="true"/></td>
                <td><form:input path="contacts[${x.index}].children"/></td>
            </tr>
        </c:forEach>
    </table>
    <input type="submit" value="Save" />
    <form:errors path="*"/>
</form:form>

Notice how I use JSTL to iterate through the many Contacts in the ContactList (the command bean) which is stored under the name "contactList."   In the form field tags, I use dot notation in the path attribute to access each contact and the properties within the contact (firstName property is accessed out of a contact bean below).  Using a little expression language and square bracket notation, I can access each Contact in the ContactList list.

path="contacts[${x.index}].firstName"

The Controller

What's left is to show you is the important parts of the controller.  In this example, I use a SimpleFormController and configure the controller's command bean as an instance of ContactList.  The XML Spring configuration of the controller is shown below.

</bean>
    <bean id="editContactController" class="com.intertech.controllers.EditContactController">
    <property name="contactService" ref="contactService" />
    <property name="commandClass" value="com.intertech.domain.ContactList" />
    <property name="commandName" value="contactList" />
    <property name="formView" value="editcontacts" />
    <property name="successView" value="confirm" />
</bean>

In the formBackingObject method of the EditContactController, I retrieve the existing Contacts and create the ContactList to populate the edit contacts JSP.

protected Object formBackingObject(HttpServletRequest request)
        throws Exception {
    List<Contact> contacts = contactService.getContacts();
    ContactList list = new ContactList();
    list.setContacts(contacts);
    return list;
}

Then in the doSubmitAction, when the form holding the "table-o-data" is submitted with a POST operation, simply iterate through each contact in the ContactList command bean and determine if the "updating" check box has been checked.  If so, update the contact in the database.

protected void doSubmitAction(Object command) throws Exception {
    ContactList myList = (ContactList) command;
    for (Contact c : myList.getContacts()) {
        if (c.isUpdating()){
            contactService.updateContact(c);
        }
    }
}

Spring MVC Controller Stereotypes

This example uses the Spring MVC 2.5.6 controller hierarchy.  With Spring 3.0, the controller hierarchy is being retired in favor of stereotype components and @Controller annotations.  However, use of command beans is still used in the new MVC architecture.  So the structure of the command bean and JSP does not change.  The controller becomes just a plain Java class with @Controller and @RequestMapping annotations.

Wrap Up

Command beans can be as complex or as simple as they need to be to capture (and possibly redisplay) data in your UI screens.  Don't limit your imagination to simple classes with primitive properties and Strings.  Understand your UI needs and develop a command bean that addresses the UI and not the reverse.

I'd like to thank my students Mark and Senthil for attending my class this week and for providing the idea for this week's blog entry.  The code for the example you see here (complete with DDL and batch files for HSQLDB) is available in a WAR file (optimized for Apache Tomcat 6) stored in a ZIP file (for transport over the Web) located here.  If you would like to learn more about Spring and be the next student that experiences micro-consulting, join me for a class at Intertech by signing up for Complete Spring Core or Complete Spring Web at Intertech.


Posted by: Jim White
Posted on: 3/29/2010 at 12:34 PM
Tags: ,
Categories: Java | Web Development
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed