Guice with Servlet 3

by mmahmoodict on 27 Apr 2013 07:05

package com.mahout.hsqldbtest;
 
import com.google.inject.AbstractModule;
import com.mahout.hsqldbtest.service.DbService;
import com.mahout.hsqldbtest.service.SongService;
 
public class SongModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(SongService.class);
        bind(DbService.class);
    }
 
}
package com.mahout.hsqldbtest.listener;
 
import javax.servlet.annotation.WebListener;
 
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.mahout.hsqldbtest.SongModule;
 
@WebListener
public class BootstrapContextListener extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new SongModule());
    }
}
package com.mahout.hsqldbtest.servlet;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
 
import com.google.inject.Injector;
 
public abstract class AbstractInjectableServlet extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
 
    @Override
    public void init(ServletConfig config) throws ServletException {
 
        ServletContext context = config.getServletContext();
        Injector injector = (Injector) context.getAttribute(Injector.class.getName());
        if (injector == null) {
            throw new ServletException("Guice Injector not found");
        }
        injector.injectMembers(this);
 
    }
}
package com.mahout.hsqldbtest.servlet;
 
import java.io.IOException;
import java.util.Map;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.mahout.hsqldbtest.service.SongService;
 
@Singleton
@WebServlet(value = "/home", loadOnStartup = 1)
public class HomeServlet extends AbstractInjectableServlet implements javax.servlet.Servlet {
 
    private static final long serialVersionUID = 1L;
 
    @Inject
    private SongService songService;
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 
        Map<String, Object> dashboardInfoMap = songService.getDashboardInfo();
        req.setAttribute("dashboardInfoMap", dashboardInfoMap);
        req.getServletContext().getRequestDispatcher("/WEB-INF/jsp/home.jsp").forward(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
 
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License