Tuesday, 6 December 2011

Spring MVC Form with Session Attribute

@Controller
@RequestMapping("/jcdFilterList.csv")
@SessionAttributes("jcdFilter")
public class JcdFormController
{

  @Autowired
  private JcdDao jcdDao;

  private List<DropdownItem> filterNames;

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  public JcdFormController()
  {
    logger.info("---------- instantiating ----------");

    filterNames = nameList();
  }

  private static List<DropdownItem> nameList()
  {
    ArrayList<DropdownItem> result = new ArrayList<DropdownItem>();

    // Assign labels
    [...]

    return result;
  }

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  // add reference data to model
  @ModelAttribute("filterNames")
  public List<DropdownItem> getFilterNames()
  {
    return filterNames;
  }

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  @RequestMapping(method = RequestMethod.GET)
  public String showForm(Map<String, Object> model)
  {
    logger.fine("showForm");
    if (model.get("jcdFilter") == null)
    {
      model.put("jcdFilter", new Filter());
    }
    return "filterForm";
  }

  @RequestMapping(method = RequestMethod.POST)
  public String processForm(Map<String, Object> model, @Valid @ModelAttribute("jcdFilter") Filter filter, BindingResult binding) throws JcapsDocException
  {
    logger.fine("processForm");
    logger.fine(filter.toString());
    if (binding.hasErrors())
    {
      return "filterForm";
    }
    else
    {
      model.put(JcdListController.JCD_LIST_KEY, jcdDao.get(filter));
      return "csvList";
    }
  }