Home > jee-light > Using FreemarkerServlet in Google Guice to inject Configuration

Using FreemarkerServlet in Google Guice to inject Configuration

Freemarker is a fantastic template parsing framework , and has its own avantages over Apache Velocity.  Google Guice is a straightforward injection framework which injects abstraction-driven ,instance-driven, or annotation driven module classes using bindings.  In order 2 get the best of both these frameworks, the following snippet would aid in doing so.

1) Modify the WEB-INF/web.xml to define FreemarkerServlet

<servlet>
 <servlet-name>freemarker</servlet-name>
 <servlet-class>com.ts.guicefmkr.web.TemplateServlet</servlet-class>
 <init-param>
 <param-name>TemplatePath</param-name>
 <param-value>/WEB-INF/ftl</param-value>
 </init-param>
 <init-param>
 <param-name>NoCache</param-name>
 <param-value>true</param-value>
 </init-param>
 <init-param>
 <param-name>ContentType</param-name>
 <param-value>text/html</param-value>
 </init-param>
 <init-param>
 <param-name>template_update_delay</param-name>
 <param-value>0</param-value>
 </init-param>
 <init-param>
 <param-name>default_encoding</param-name>
 <param-value>ISO-8859-1</param-value>
 </init-param>
 <init-param>
 <param-name>number_format</param-name>
 <param-value>0.##########</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

2) Extend the FreemarkerServlet and implement to Guice’s Module to bind the created  Configuration object

import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
import javax.servlet.ServletException;

import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
public class TemplateServlet extends FreemarkerServlet implements Module
{   private Configuration templateConfig;
    public Configuration getTemplateConfig()
    {      return templateConfig;
    }

     public void setTemplateConfig(Configuration templateConfig) {
        this.templateConfig = templateConfig;
     }

    public void init() throws ServletException
     {   super.init();
         templateConfig = getConfiguration();
        Injector injector = com.google.inject.Guice.createInjector(this);
       }

      public void configure(Binder binder)
     {   binder.bind(Configuration.class).toInstance(templateConfig);
     }
}

Thus you could use Configuration object anywhere in your application using @Inject from Guice.

Categories: jee-light Tags: ,
  1. No comments yet.
  1. No trackbacks yet.