Duom
Duom

Reputation: 141

Guice injection in JSP bean

I'm writing a java application using Guice as my DI framework and Hibernate as my Orm. I want to run a simple embedded Jetty server to serve a couple of jsp pages. I managed to run the server using the following code:

Server server = new Server(8081);
final WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/rpga");
webAppContext.setResourceBase("web/WEB-INF/");
webAppContext.setDescriptor("web/WEB-INF/web.xml");
webAppContext.setParentLoaderPriority(true);

final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration","org.eclipse.jetty.annotations.AnnotationConfiguration");

webAppContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$|.*/classes/.*");

webAppContext.setServer(server);

server.setHandler(webAppContext);
server.start();
server.join();

I would like now to use a couple of simple beans to add some data in my jsp. I tried creating a bean and injecting my dao in it but since the bean is not managed by Guice, the Dao is not injected.

my JSP looks like

<html>
   <head>
      <title>Playlist</title>
   </head>
   <body>
        <jsp:useBean id="playlist" class="com.duom.beans.PlaylistBean" /> 
        ...do stuff with playlistBean
   </body>
</html>

And my bean:

import com.google.inject.Inject;

public class PlaylistBean {

    @Inject
    private PlaylistDao playlistDao;

    ...do stuff
}

What am I missing to achieve my goal ?

Upvotes: 3

Views: 431

Answers (1)

Duom
Duom

Reputation: 141

I managed to find a solution to my problem. I managed to clear up my intentions and restart my devs using the right technology.

I switched from JSP to JSF2, I created a factory class for the Guice injector :

public class GuiceFactory {

    private static final Injector injector = Guice.createInjector(new RpgaAppModule());

    public static Injector getInjector() {
        return injector;
    }
}

then on each constructor of my beans I call :

GuiceFactory.getInjector().injectMembers(this);

Don't hesitate to comment if my solution is wrong in terms of design or architecture.

Upvotes: 1

Related Questions