How to Configure Google Guice Servlet For Web Application | Java @ Desk
Home » , , , » How to Configure Google Guice Servlet For Web Application

How to Configure Google Guice Servlet For Web Application

How to Configure Google Guice Servlet For Web Application

As we have seen in our previous post how easy it is to configure the DI (Dependency Injection) using Google Guice. In this post we will see how we can take the advantage of Google Guice Servlet Module to integrate / setup Web Application.

Guice Servlet Module allows us to completely eliminate the web.xml from Web Application Project and configure Servlets / Filters using the Java Configuration File itself.

Benefits – Google Guice provides us Following benefits
1) Constructor Injection, Setter, Field/member variable Injection
2) Type Safe Configuration ( eliminate web.xml file)
3) Modularization.
4) Can Inject the objects like request, response, session, requestParameters inside the servlet using DI.
5) Can define the Scope like Request Scope/ Session Scope using Annotation
6) It’s easy to use and integrate and no need to change the existing file/ servlets /jsp etc.

You can download the required Google Guice API from You need to extract .zip file and add all .jar files in the build path / .classpath of the project.

Let’s see the Components –

1. Configure GuiceFilter in web.xml
Need to Add the GuiceFilter in web.xml. It tells ServletContainer to re-route all the request through GuiceFilter. The Good thing is that all the existing Servlets/ JSP/ Filters will continue to function as normal and we can migrate it later.

2. Install a Servlet Module / Enable Google Guice Servlet Module

In Order to install Servlet Module, we need to take 3 steps –
i. Create a WebServletModule which Extends ServletModule
ii. Create ServletConfig which extends GuiceServletContextListener.
iii. Configure GuiceServletContextListener inside the web.xml

Let’s Create a WebServletModule - First, in Servlet Module we can specify the Servlet / Filters mapping which we use to define inside web.xml. we can think of it as replacement of web.xml with enabled Guice DI capability.
public class WebServletModule extends ServletModule {

 // Specify Mapping of Servlet to URL.
 public void configureServlets(){

ServletConfig – ServletConfig Extends GuiceServletContextListener. Here we need to define all the modules that we want to install. In order to enable the Google Servlet Module we need to install WebServletModule and to define the binding we can have WebAppModule.
public class ServletConfig extends GuiceServletContextListener  {

 Injector injector;
 // Create Injector
 protected Injector getInjector() {
  injector = Guice.createInjector(getModules());
  return injector;
 // List of Modules for the Project. 
 private List<Module> getModules(){
  List<Module> modulesList = new ArrayList<Module>();
  modulesList.add(new WebServletModule());
  modulesList.add(new WebAppModule());
  return modulesList;

Just for Reference–
public class WebAppModule extends AbstractModule {

 protected void configure() {
  bind(User.class); // Later we will see, Bind the

Configure Listener inside the Web.xml – In order to install the modules we need to make a entry to ServletConfig in web.xml.

Now we are done with all the configuration. Lets Create the Some html files and Servlets to run web Application using Google Guice.

User Case Scenario – A User will provide UserName and Email as Input and after submitting the data will be able to see the processes output.

Let’s see the Components Involved –
1. Entry.html – Take a input as username and Email and a submit button.
 <form action="abc.html" method="get">
  UserName : <input type="text" name="userName"/> <br/>
  Email : <input type="text" name="email"/><br>
  <input type="submit" value="Submit"/>

As you can see, after clicking on Submit it will call abc.html and abc.html has been mapped with in

Below is the much awaited
Note -
Servlet Should apply @Singleton annotation.
Instantiate Object using injector.getInstance(User.class); don’t use new operator

This servlet Instantiate the User Object and call the processRequest() of User. We have bind the in
public class WebAppModule extends AbstractModule {

 protected void configure() {

public class EntryServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 Injector injector; // Inject a Injector
    public EntryServlet() {

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 User user = injector.getInstance(User.class); //Need to Create the Instance using this method.
  PrintWriter out = response.getWriter(); // Renders response over UI.
  String responseString = "After Processing"+"\n"+"Name = "+user.getName()+"\n"+"Email  = "+user.getEmail();

Finally User.Java - Just to Keep it simple I have kept all objects inside one class only.
Now you can see, Since we have enabled Guice Servlet Module inside this web Application, I am able to inject request, response, session and requestParameters in
It’s quite easy to use and handle. Inside the process methods I fetched all the parameters passed from UI and set it into the UserObject itself.

public class User {
 private Map<String, String[]> parameters;
 private HttpSession session;
 private ServletRequest request;
 private ServletResponse response;
 private String name;
 private String email;
public String getName() {
  return name;

public void setName(String name) { = name;

public String getEmail() {
  return email;

public void setEmail(String email) { = email;

 public String processRequest(){
  System.out.println("Enrty Servlet");
  String name = ((String[])parameters.get("userName"))[0];
  String email = ((String[])parameters.get("email"))[0];
  System.out.println("name "+name+" Email "+email);
  session.setAttribute("email", email);
  return "Success";

Finally The User Object will be rendered to UI via
Wrap Up – Using the above Configuration we can set up google Guice Servlet Module in Web Application and take the advantages of easy to use, modularize and DI enabled code.

This post is written by
Soumitra Pathak - Linkedin, Facebook
He is a freelance writer, loves to explore latest features in Java technology.


Post a Comment