<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FactoryPattern.com &#187; java web apps</title>
	<atom:link href="http://www.factorypattern.com/category/java-web-apps/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.factorypattern.com</link>
	<description>Just another Object Oriented Weblog</description>
	<lastBuildDate>Sat, 02 Jan 2010 22:08:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Guice Servlets Integration</title>
		<link>http://www.factorypattern.com/guice-servlets/</link>
		<comments>http://www.factorypattern.com/guice-servlets/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 09:36:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[guice]]></category>
		<category><![CDATA[java web apps]]></category>
		<category><![CDATA[servlets]]></category>
		<category><![CDATA[bootstrapping]]></category>
		<category><![CDATA[google guice]]></category>
		<category><![CDATA[web applications]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/guice-servlets-integration/</guid>
		<description><![CDATA[Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems:
- [...]]]></description>
			<content:encoded><![CDATA[<p>Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems:<br />
- Because we can not control the servlet creation we can not use Guice to inject servlet members in the classic way.<br />
- Bootstrapping: we need a mechanism to bootstrap Guice into the application. The best way is to do it at start up before any http request will be invoked.<br />
<span id="more-37"></span><br />
The key element to bootstrap Google Guice to a java servlet based application is <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html">ServletContext</a>. For each web application there is only one ServletContext instance per JVM. ServletContext is used to manage data which is accessible to all the servlets, and it can be used by the servlets to share data between them. Starting with Servlet 2.3 specification Sun provides a listener mechanism which can be used to instantiate objects at the application start up, outside of any servlet scope in the ServletContext.</p>
<p>This techniques can not be used in distributed environments. If we use it we&#8217;ll have one injector instance on each JVM because on distributed environments for each JVM there is one ServletContext. ServletContext on one JVM is not visible from another JVM, so if we can not use guice scopes distributed on multiple machines.</p>
<h2>Initializing Guice Injector in ServletContext</h2>
<p>As we said there is only one instance of javax.servlet.ServletContext(as long as we don&#8217;t have a distributed application). We can trigger the initialization of the ServletContext using <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html">ServletContextListener</a>. All we have to do is to implement the ServletContextListener.contextInitialized to create the google guice injector, and to set it as an attribute in the ServletContext:</p>
<pre name="code" class="java">package com.exam.web.guice;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

public class GuiceServletContextListener implements ServletContextListener {
    public static final String KEY = Injector.class.getName(); 

    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
    	servletContextEvent.getServletContext()
    		.setAttribute(KEY, getInjector(servletContextEvent.getServletContext()));
    } 

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	servletContextEvent.getServletContext().removeAttribute(KEY);
    } 

    @SuppressWarnings("unchecked")
    private Injector getInjector(ServletContext servletContext) {
        String className = servletContext.getInitParameter("module");
        try {
            Class<? extends Module> module = (Class<? extends Module>) Class.forName(className);
            return Guice.createInjector(module.getConstructor().newInstance());
        }
        catch (ClassNotFoundException e) { throw new RuntimeException(e); }
        catch (NoSuchMethodException e) { throw new RuntimeException(e); }
        catch (InvocationTargetException e) { throw new RuntimeException(e); }
        catch (IllegalAccessException e) { throw new RuntimeException(e); }
        catch (InstantiationException e) { throw new RuntimeException(e); }
    }
}</pre>
<p>Then we have to change the web.xml to define the listener to be used by the web application container:</p>
<pre name="code" class="xml">
<listener>
<listener-class>
            com.exam.web.guice.GuiceServletContextListener
        </listener-class>
    </listener>
</pre>
<h2>Storing module configuration in web.xml</h2>
<p>We use web.xml to define which module to be used by Guice in <context-param> block. When we create the guice injector the parameter is read and used:</p>
<pre name="code" class="php">String className = servletContext.getInitParameter("module");</pre>
<p>The class name is defined like this in web.xml:</p>
<pre name="code" class="XML">
    <context-param> 
<param-name>module</param-name>
<param-value>com.webapplication.bus.HibernateDaoModule</param-value>
        <description>Guice Module to be used for the servlets app</description>
    </context-param>
</pre>
<p>Finally in the servlet we can use this expression to get the injector:<br />
(Injector) servletContext.getAttribute(GuiceServletContextListener.KEY)</p>
<p>We can add an injector field to the servlet and &#8220;inject&#8221; the injector into it when the servlet is initialized(a super servlet class can be created to define this code in only one place):</p>
<pre name="code" class="java">public class MyServlet  extends HttpServlet {

	Injector injector;
        ...

	@Override
	public void init(ServletConfig config) throws ServletException {

        HibernateUtil.Configure(true);  

	    ServletContext servletContext = config.getServletContext();
	    injector = (Injector) servletContext.getAttribute(GuiceServletContextListener.KEY);
	    injector.injectMembers(this);

	    managersRegistry = injector.getInstance(ManagersRegistry.class);

		super.init(config);
	}
}</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/guice-servlets/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/guice-servlets/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/google-guice-tutorial/" title="Google Guice Tutorial">Google Guice Tutorial</a></li><li><a href="http://www.factorypattern.com/google-guice-starts-a-new-google-age/" title="Google Guice Starts a New Google Age?">Google Guice Starts a New Google Age?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/guice-servlets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Storing parameters in web.xml: context-param &amp; init-param</title>
		<link>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/</link>
		<comments>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 22:48:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[java web apps]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/</guid>
		<description><![CDATA[There are two options to store parameters in web.xml:
- context parameters &#8211; available to the entire scope of the web application
- init parameters &#8211; available in the context of a servlet or filter in the web application
Context Parameters

&#60;?xml version="1.0" encoding="UTF-8"?&#62;
&#60;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&#62;
  &#60;context-param&#62;
    &#60;description&#62;This is a context [...]]]></description>
			<content:encoded><![CDATA[<p>There are two options to store parameters in web.xml:<br />
- <strong>context parameters</strong> &#8211; available to the entire scope of the web application<br />
- <strong>init parameters</strong> &#8211; available in the context of a servlet or filter in the web application</p>
<h2>Context Parameters</h2>
<p><span id="more-30"></span></p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt;
  &lt;context-param&gt;
    &lt;description&gt;This is a context parameter example&lt;/description&gt;
    &lt;param-name&gt;ContextParam&lt;/param-name&gt;
    &lt;param-value&gt;ContextParam value&lt;/param-value&gt;
  &lt;/context-param&gt;
...
&lt;web-app&gt;</code></pre>
<p>The following code can be be invoked from a servlet or a filter to retrieve the ContextParam value. The parameter can be read successfully from any servlet or filter class.</p>
<pre><code>@Override
	public void init(ServletConfig config) throws ServletException {
		String contextParam = config.getServletContext().getInitParameter("ContextParam");
	}

//or
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String contextParam = this.getServletContext().getInitParameter("ContextParam");
		...
	}
	...
}

String value = this.getServletContext().getInitParameter("ContextParam");</code></pre>
<h2>Init Parameters</h2>
<pre><code>...
&lt;servlet&gt;
    &lt;servlet-name&gt;A Servlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.controller.TestServlet&lt;/servlet-class&gt;
    &lt;init-param&gt; 
        &lt;description&gt;This is an init parameter example&lt;/description&gt; 
        &lt;param-name&gt;InitParam&lt;/param-name&gt; 
        &lt;param-value&gt;init param value&lt;/param-value&gt; 
    &lt;/init-param&gt; 
&lt;/servlet&gt;
...</code></pre>
<p>The following code can be be invoked to retrieve the value of InitParam. The parameter can be accessed only from com.controller.TestServlet.</p>
<pre><code>public class DefaultController extends HttpServlet
{
	@Override
	public void init(ServletConfig config) throws ServletException {
		String initParam  = config.getInitParameter("InitParam");
	}

//or
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String initParam = getServletConfig().getInitParameter("InitParam");
		...
	}
	...
}</code></pre>
<h2>Iterating through context-params and init-params</h2>
<p>It&#8217;s possible to iterate through the paramters if required:</p>
<pre><code>public class DefaultController extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Enumeration contextParams = getServletContext().getInitParameterNames();

		Sytem.out.println("context-params: ");
		while (params.hasMoreElements()) {
			String name = (String) params.nextElement();
			Sytem.out.println(name + " = " + config.getInitParameter(name));
		}

		Enumeration initParams = getServletConfig().getInitParameterNames();

		Sytem.out.println("init-params: ");
		while (params.hasMoreElements()) {
			String name = (String) params.nextElement();
			Sytem.out.println(name + " = " + config.getInitParameter(name));
		}

		...
	}
	...
}</code></pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.779 seconds -->
