Archive for the ‘Spring MVC’ Category

Linking between a controller page and a non-initail page of Spring MVC Wizard

Tuesday, October 28th, 2008

For one of the projects where I used Spring MVC 2.5 I had to link a view page with the second page of edit wizard. The reason for the linking is this that view page contains enough information to bypass the first wizard screen for editing the information person is viewing. Here is how to do it.

In the target wizard controller you will need to overwrite the following three methods: two for getting the names of attributes stored in a session and one for getting the page number from request attribute first then request parameter. 
Since wizards work with session based forms, you will need to put the form in the session. To do that, you would need to know the attribute key in your controller. The key value is available in the super class, so you need to make the method visible.

public String getFormSessionAttributeName(HttpServletRequest request) {       
   return super.getFormSessionAttributeName(request);
}

Same with getting the page attribute, which you will need to control which page of the wizard you will link to.

public String getPageSessionAttributeName(HttpServletRequest request) {  
   
return super.getPageSessionAttributeName(request);
}

The other thing is that you will need to pass in the page number, which you can only pass as request argument, not request parameter as expected by the super class. So here is how you can do it:

protected int getTargetPage(HttpServletRequest request, int currentPage) {       
  
Enumeration requestNamesEnum = request.getAttributeNames();
   while (requestNamesEnum.hasMoreElements()) {           
          
String requestName = (String) requestNamesEnum.nextElement();
           
          
if (requestName.startsWith(AbstractWizardFormController.PARAM_TARGET)) {
                   
for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
                      
String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
                      
if (requestName.endsWith(suffix)) {
                                  
requestName = requestName.substring(0, requestName.length() – suffix.length());   
                        
}
                 
}
              
 return Integer.parseInt(requestName.substring(AbstractWizardFormController.PARAM_TARGET.length()));   
            
}
       
} 
    
return WebUtils.getTargetPage(request, PARAM_TARGET, currentPage);
}

Now in your controller you need to prepare all the parameters to call the wizard:

HttpSession session = request.getSession(); 
MyWizardForm wizardForm = new MyWizardForm();
  
wizardForm.setDataId(viewForm.getDataId());
 // populating information from view screen
wizardForm.setMoreData(viewForm.getMoreData());
 
EditWizardController tempEditWizardController = new EditWizardController();
 
request.setAttribute(tempEditWizardController.getPageSessionAttributeName(request), new Integer(0)); //as if user had posted data on page 0
request.setAttribute(“_target1″,”_target1”); //and the landing page should be page 2, after page 1 is validated.
session.setAttribute(tempUniverseEditWizardController.getFormSessionAttributeName(request), wizardForm);

return new ModelAndView(“forward:editUniverse.htm”);

 

And that is it!

Handling java.util.Date in Spring MVC

Wednesday, August 6th, 2008

A lot of times I needed to display and edit data that has date information in it. For example, user registration form might have a birthday field. I do want that field to be java.util.Date and be save in the database as a date, but when rendering to JSP I used to have to convert it to/from a text field. Not anymore! I started using custom PropertyEditorSupport for Date processing. To use this feature, you need to follow 3 steps:

First, you need to create a custom PropertyEditorSupport. Here is the one I used for java.util.Date:

package foo;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

/**
 * @author Henry Naftulin
 * @since Aug 4, 2008
 */
public class DatePropertyEditor extends PropertyEditorSupport {
  Logger log = Logger.getLogger(DatePropertyEditor.class);
  String[] formats = {"yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy"};

Date defaultDate = new Date(0L);

public void setAsText(String textValue) {
  if (textValue == null) {
  setValue(defaultDate);
  return;
  }
  Date retDate = defaultDate;
  try {
  retDate = DateUtils.parseDate(textValue, formats);
  } catch (ParseException e) {
  log.error("Cannot parse " + textValue + " as date.", e);
  }
  setValue(retDate);
  }

}

Second, I need to register the custom property editor with my Spring MVC controller, which I do by overwriting the following method:

protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) throws Exception {
  binder.registerCustomEditor(Date.class, new DatePropertyEditor());
  }

And that is it: you can just render you date field in the JSP and dates typed into the text fields would be converted from the String representation to java.util.Date!