How to Configure Google Guice Servlet For Web Application - Java @ Desk

Tuesday, December 23, 2014

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 Google-Guice-3.0.zip. 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.
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


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.
 
 @Override
 public void configureServlets(){
  serve("/abc.html").with(EntryServlet.class);
 }
 
}


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
 @Override
 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 WebAppModule.java–
public class WebAppModule extends AbstractModule {

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


Configure Listener inside the Web.xml – In order to install the modules we need to make a entry to ServletConfig in web.xml.
<listener>
    <listener-class>com.java.desk.config.ServletConfig</listener-class>
</listener>


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.
<body>
 <center><br><br><br><br><br><br><br><br>
 <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"/>
 </form>
 </center>
</body>


As you can see, after clicking on Submit it will call abc.html and abc.html has been mapped with EntryServlet.java in WebServletModule.java.
serve("/abc.html").with(EntryServlet.class);


Below is the much awaited EntryServlet.java
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 User.java in WebAppModule.java.
public class WebAppModule extends AbstractModule {

 @Override
 protected void configure() {
  bind(User.class);
 }
}

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

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


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 User.java.
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.

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

 
public void setName(String name) {
  this.name = name;
 }

 
public String getEmail() {
  return email;
 }

 
public void setEmail(String email) {
  this.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("name",name);
  session.setAttribute("email", email);
  
  this.setEmail(email);
  this.setName(name);
  return "Success";
 }
}


Finally The User Object will be rendered to UI via EntryServlet.java
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.








No comments:

Post a Comment