views:

1545

answers:

0

Hi all,

i was strugling today trying to migrate from Freemarker to Tiles2 + Freemarker.

My freemarker templates use macros that come from spring.ftl.

If i provide a fremarker servlet in web.xml, my model is visible to freemarker, but specific spring variables (naturally) are not populated into the model as springs FreemarkerView is responsible for that.

If i configure a separate DispatcherServlet for specific url (say "/tpl/*") and configure freemarker resolver as default view resolver for that servlet and provide UrlFilenameViewController as default controller, special spring variables do get populated to model, but my own model is not visible: it is bound as a request attribute. I can access my model via ${Request.mymodel.myvar} but this way i have to change all my freemarker templates and i see something smelly in the idea.

Now my solution was to extend UrlFilenameViewController and add my model from request to ModelAndView:

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)  {
     ModelAndView mav = super.handleRequestInternal(request, response);

     HashMap<String, Object> map = new HashMap<String, Object>();

     Enumeration<String> attributes = request.getAttributeNames();

     while(attributes.hasMoreElements()) {
      String attribute = attributes.nextElement();

      if("model".equals(attribute)) {
       logger.debug("FreemarkerViewController.handleRequestInternal: putting attribute to model: " + attribute + "=" + request.getAttribute(attribute));
       map.put(attribute, request.getAttribute(attribute));
      }
     }
     logger.debug("FreemarkerViewController.handleRequestInternal: VIEW: " + mav.getViewName());
     return new ModelAndView(mav.getViewName(), map);
    }

But this solution is somewhat smelly too - if i add something to the model in my business controllers, i have to add is here.

Is there an elegant solution for my problem?