Discovering Spring MVC

Spring MVC is not taken seriously jet because of almost absent documentation. For 2.0 version they wrote couple more paragraphs. But still only pages 214-250 devoted to Spring MVC itself. Many features left undocumented.

For my recent project I had to build a form having 6 different sets of fields. Depending on selected value in combo-box I process specific set. The rest of fields are ignored. That was easy to decide but how to tell Spring no to bind some fields?

One approach is to process input manually disabling automatic binding by overriding supressBinding function:

protected boolean suppressBinding(HttpServletRequest request) {
  return false;
}

Will work but leaves whole burden of binding on your shoulders. You do not want that. The other approach is letting Spring know which fields you want to process and which not. Take a look:

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
  super.initBinder(request, binder);
  if (! isFormSubmission(request))
    return ;
  try {
    String selectedBenefitType = ServletRequestUtils.getRequiredStringParameter(request, "benefitType");
    List disallowedFields = new ArrayList();
    //disallow processing of any field that do not belong to currently selected benefit
    for (String benefitType:BaseBenefit.benefitTypes){
      if (! selectedBenefitType.equalsIgnoreCase(benefitType)){
        String fieldMask = StringUtils.uncapitalize(benefitType)+".*";
        disallowedFields.add(fieldMask);
      }
    }
    binder.setDisallowedFields(disallowedFields.toArray(new String[disallowedFields.size()]));
    binder.setRequiredFields(new String[]{”benefitType”, “sinceDate”, “untilDate”});
  } catch (ServletRequestBindingException e) {
    logger.error(e.getMessage(), e);
    throw new RuntimeException(e);
  }
}

Here we pass list of unwanted fields to binder.setDisallowedFields and that is it. Those fields will not be bound and you will not receive ‘Can not convert field someDate to java.util.Date’ for fields that are not wanted, not filled and even hidden on the form. As you have probably noticed You can use wild-cards in field names.

I like Spring a lot. And I use it in every single Java project I do. So take my advice. When you want to use Spring MVC seriously, the first step is to tear away Spring MVC paragraph from documentation so you do not pretend that you have it at all. Read an API and dig into source code. Soon you will discover that your web-tier improved a lot.

One Response to “Discovering Spring MVC”

  1. Kamal Mettananda Says:

    I too used to have the spring source with me and do some debugging when ever needed. Spring forum is active and that helps a lot.

Leave a Reply